@canonry/canonry 7.0.0 → 7.1.1

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.
Files changed (34) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +3 -1
  2. package/assets/assets/AuditHistoryPanel-CZWzgyrD.js +1 -0
  3. package/assets/assets/{BacklinksPage-HIM0fmV7.js → BacklinksPage-D23A-ahd.js} +1 -1
  4. package/assets/assets/{HistoryPage-BjEVp-fk.js → HistoryPage-BKGVxmNz.js} +1 -1
  5. package/assets/assets/{MeasurementPropertyPage-BnVDR2y_.js → MeasurementPropertyPage-BSxn6_RB.js} +1 -1
  6. package/assets/assets/ProjectPage-D9W8G_1m.js +8 -0
  7. package/assets/assets/{RunsPage-fJQe2qJc.js → RunsPage-CeBBjLSE.js} +1 -1
  8. package/assets/assets/{SettingsPage-1yam5tl6.js → SettingsPage-Jp5Yp4cz.js} +1 -1
  9. package/assets/assets/SiteHealthSection-DzVegBeN.js +4 -0
  10. package/assets/assets/{TrafficPage-BdNEscz8.js → TrafficPage-B66AYwWk.js} +2 -2
  11. package/assets/assets/{TrafficSourceDetailPage-CMEgr4Aw.js → TrafficSourceDetailPage-CXtq1yES.js} +1 -1
  12. package/assets/assets/{extract-error-message-D2dhaJaW.js → extract-error-message-BVa0lOze.js} +1 -1
  13. package/assets/assets/{index-CgT2Btdn.css → index-CMe_-fAB.css} +1 -1
  14. package/assets/assets/index-DuhS0WLM.js +86 -0
  15. package/assets/assets/{react-sigma_core.esm.min-oP23IWpt.js → react-sigma_core.esm.min-60drsJa6.js} +1 -1
  16. package/assets/assets/{v2-overview-adapter-DYatWs7N.js → v2-overview-adapter-CLUi2Lkv.js} +1 -1
  17. package/assets/index.html +2 -2
  18. package/dist/{chunk-A5PALGQD.js → chunk-22R5E5CY.js} +94 -190
  19. package/dist/{chunk-TUHQ5BBQ.js → chunk-2OQ6D26U.js} +2 -5
  20. package/dist/{chunk-LXWY4NKP.js → chunk-IAMECH2N.js} +3 -3
  21. package/dist/{chunk-HQJ25LI7.js → chunk-MTSFSXCG.js} +2 -2
  22. package/dist/{chunk-RRIZ5AKI.js → chunk-U2S5ABOR.js} +2 -2
  23. package/dist/{chunk-EZ54X4XH.js → chunk-VDX3LYKL.js} +110 -78
  24. package/dist/{chunk-OOUDIVIU.js → chunk-YGHPT5B2.js} +434 -182
  25. package/dist/cli.js +8 -8
  26. package/dist/{demo-server-LHHDVXQW.js → demo-server-TIMYQLXS.js} +4 -4
  27. package/dist/index.js +6 -6
  28. package/dist/{intelligence-service-ZVKZLLKL.js → intelligence-service-YCMRTVCI.js} +2 -2
  29. package/dist/mcp.js +4 -4
  30. package/package.json +10 -10
  31. package/assets/assets/AuditHistoryPanel-DBYsgVsn.js +0 -1
  32. package/assets/assets/ProjectPage-BhCM47KA.js +0 -8
  33. package/assets/assets/SiteHealthSection-DysU2M6C.js +0 -4
  34. package/assets/assets/index-D9ODLKpH.js +0 -86
@@ -1,8 +0,0 @@
1
- import{j as e,r as o,t as Yc,u as $e,L as qs,h as ps,o as Ot,B as yi,C as kl,D as Jc,k as Xc,l as Zc}from"./vendor-tanstack-ZXXkndVj.js";import{T as je,t as ed,a as td,s as bi,M as ma,I as Be,f as et,R as Qn,m as sd,B as T,c as nd,b as ad,d as rd,S as id,e as Al,u as vi,g as od,n as Kn,C as ld,h as Rl,i as Pl,j as ji,k as cd,l as dd,o as yn,p as Il,q as Tl,r as ve,v as Ja,w as H,x as le,y as Os,z as It,A as Xe,D as ud,E as md,F as hd,G as Ml,H as pd,J as xd,K as Sn,L as bn,N as gd,O as fd,P as Pn,Q as Ht,U as yd,V as bd,W as Wi,X as ql,Y as zt,Z as Ni,_ as vd,$ as jd,a0 as Nd,a1 as wd,a2 as Yi,a3 as Ee,a4 as Sd,a5 as Cd,a6 as fr,a7 as kd,a8 as Ad,a9 as Rd,aa as Pd,ab as Id,ac as Td,ad as Md,ae as qd,af as $d,ag as Ld,ah as Ed,ai as Dd,aj as Od,ak as Fd,al as Kd,am as $l,an as Zs,ao as Gd,ap as Ll,aq as tr,ar as _d,as as Ye,at as Ud,au as Bd,av as Vd,aw as sr,ax as Qd,ay as zd,az as Hd,aA as Gn,aB as Wd,aC as Yd,aD as Jd,aE as El,aF as Yr,aG as Xd,aH as wi,aI as Zd,aJ as _n,aK as us,aL as ur,aM as Ms,aN as Dl,aO as Xa,aP as Jr,aQ as eu,aR as Ji,aS as Ol,aT as nr,aU as tu,aV as Fl,aW as Kl,aX as Gl,aY as su,aZ as un,a_ as yr,a$ as nu,b0 as au,b1 as ru,b2 as iu,b3 as ou,b4 as ca,b5 as Xi,b6 as Ma,b7 as br,b8 as lu,b9 as cu,ba as Zi,bb as vr,bc as vn,bd as _l,be as Si,bf as Ul,bg as du,bh as uu,bi as eo,bj as mu,bk as hu,bl as pu,bm as xu,bn as gu,bo as fu,bp as yu,bq as bu,br as vu,bs as ju,bt as Nu,bu as wu,bv as Su,bw as Cu,bx as ku,by as Au,bz as Ru,bA as Pu,bB as Iu,bC as Tu,bD as Mu,bE as qu,bF as $u,bG as Lu,bH as Eu,bI as Du,bJ as Ou,bK as Fu,bL as As,bM as Ku,bN as wt,bO as Gu,bP as _u,bQ as Uu,bR as Bu,bS as Vu,bT as Qu,bU as zu,bV as Hu,bW as Wu,bX as Yu,bY as Ju,bZ as Xu,b_ as Zu,b$ as em,c0 as tm,c1 as sm,c2 as nm,c3 as am,c4 as rm,c5 as im,c6 as om,c7 as lm,c8 as cm,c9 as dm,ca as um,cb as mm,cc as hm,cd as Bl,ce as jr,cf as pm,cg as xm,ch as to,ci as gm,cj as fm,ck as ym,cl as bm,cm as vm,cn as jm,co as Nm,cp as Vl,cq as wm,cr as Ql,cs as zl,ct as Hl,cu as Wl,cv as Sm,cw as Cm,cx as km,cy as Am,cz as Rm,cA as Pm,cB as Im,cC as so,cD as Tm,cE as Mm,cF as qm,cG as $m,cH as Lm,cI as Em,cJ as Dm,cK as Om,cL as no,cM as Fm,cN as Km,cO as Gm,cP as _m,cQ as Um,cR as Bm,cS as Vm,cT as Qm,cU as zm,cV as Hm,cW as Wm,cX as Ym,cY as Nr,cZ as Jm,c_ as Xm,c$ as Zm,d0 as eh,d1 as th,d2 as sh,d3 as nh,d4 as ah,d5 as rh,d6 as ih,d7 as oh,d8 as lh,d9 as ch,da as dh,db as uh,dc as Yl,dd as mh,de as hh,df as ph,dg as xh,dh as gh,di as fh,dj as qa,dk as yh,dl as bh,dm as vh,dn as ao,dp as jh}from"./index-D9ODLKpH.js";import{u as jn,D as Xs,a as Fs,b as Jl,M as Za,c as Ls,S as Nh}from"./SiteHealthSection-DysU2M6C.js";import{A as Ci,V as Xl,a as wh,u as ki,U as ro,b as Sh,c as Ch,d as io}from"./v2-overview-adapter-DYatWs7N.js";import{o as Bt,C as ha,f as Nn,a as ms,b as Ut,c as At,d as ns,e as it,g as hs,h as zn,M as Zl,i as kh,j as ba,p as Ah,k as Rh,l as oo,m as Ph}from"./ChartPrimitives-CYlrwLJs.js";import{g as ec,y as pa,U as Ih,z as Th,L as Mh,D as qh,l as $h,j as ar,I as Lh,J as Eh,C as Un,X as Dh,e as Oh,K as Fh,P as Kh,N as Gh,O as tc}from"./vendor-lucide-N6vOpZmh.js";import{u as _h,a as Uh,b as Bh,t as Vh,e as Qh,c as Ct}from"./extract-error-message-D2dhaJaW.js";import{R as en,C as tn,a as xa,X as sn,Y as nn,T as an,b as Xr,L as rr,A as Ys,d as Ds,e as zh}from"./vendor-recharts-D-cUuLZo.js";import{A as Hh}from"./AuditHistoryPanel-DBYsgVsn.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B4giJcws.js";import"./vendor-yaml-GWJz5H2G.js";const Wh=1e6;function Yh(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/Wh);if(n.showTinyAsLessThan&&t>0&&r===a.format(0)){const l=10**-(a.resolvedOptions().maximumFractionDigits??0);return`<${a.format(l)}`}return r}const $a={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 sc(t,s){return t!=="viewer"||s!==null}function nc(t,s){return t==="research"&&!s?"tracked":t}function ac(t,s){return s.measurementScope==="project"?!1:s.measurementScopeKey?!(s.measurementScope==="group"?t.groups:s.measurementScope==="property"?t.targets:t.markets).some(a=>a.stableKey===s.measurementScopeKey):!0}function Zr(t,s){return t.find(n=>n.kind===s.measurementScope&&(n.kind==="project"||n.id===s.measurementScopeKey))}function Jh(t){return t.measurementScope!=="project"||t.marketKey!==void 0}function Xh(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 ei({state:t,label:s,className:n}){return e.jsx(je,{tone:td(t),className:n,children:s??ed(t)})}const mn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],lo={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Zh={"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."},ep="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function tp(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:et(t.score,Qn.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 sp({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(Be,{text:ep})]}),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:et(a.share)})]},a.label))})]})}function np({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=o.useState("non-brand"),l=o.useId(),i=t.scope==="pooled",c=!i&&t.branded.snapshotsTotal>0,d=c?a:"non-brand",h=i?"pooled":d,u=d==="branded"?t.branded:t.breakdown,p=d==="branded"?t.breakdown:t.branded,g=tp(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:p.snapshotsTotal>0}),m=bi(g.headline),y=h==="non-brand"?ma[t.tone]:"text-secondary";function x(b){const N=mn.findIndex(M=>M.value===d);let C=null;b.key==="ArrowRight"||b.key==="ArrowDown"?C=(N+1)%mn.length:b.key==="ArrowLeft"||b.key==="ArrowUp"?C=(N-1+mn.length)%mn.length:b.key==="Home"?C=0:b.key==="End"&&(C=mn.length-1),C!==null&&(b.preventDefault(),r(mn[C].value),b.currentTarget.querySelectorAll('[role="radio"]')[C]?.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(Be,{text:Zh[h]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":l,className:"segmented flex-wrap",onKeyDown:x,children:mn.map(b=>{const N=b.value===d;return e.jsx("button",{type:"button",role:"radio","aria-checked":N,tabIndex:N?0:-1,onClick:()=>r(b.value),className:`segmented-option min-h-11 ${N?"segmented-option-active":""}`,children:b.label},b.value)})}):e.jsx("span",{className:"mention-share-class",children:lo[h]})]}),g.numeric?e.jsxs("p",{className:`mention-share-value ${y}`,children:[m.figure,m.sign?e.jsx("span",{className:"text-faint",children:m.sign}):null]}):e.jsx("p",{className:"mention-share-value-text",children:g.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:lo[h]}),` · ${g.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),g.showRows&&e.jsx(sp,{breakdown:u,projectLabel:s})]})}function va({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 da({options:t,value:s,onChange:n,label:a,className:r=""}){const l=o.useId();function i(c){const d=t.findIndex(u=>u.value===s);let h=null;c.key==="ArrowRight"||c.key==="ArrowDown"?h=(d+1)%t.length:c.key==="ArrowLeft"||c.key==="ArrowUp"?h=(d-1+t.length)%t.length:c.key==="Home"?h=0:c.key==="End"&&(h=t.length-1),h!==null&&(c.preventDefault(),n(t[h].value),c.currentTarget.querySelectorAll('[role="radio"]')[h].focus())}return e.jsx("div",{role:"radiogroup","aria-label":a,className:`segmented ${r}`.trim(),onKeyDown:i,children:t.map(c=>{const d=c.value===s,h=c.description?`${l}-${c.value}`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button",role:"radio","aria-checked":d,"aria-describedby":h,tabIndex:d?0:-1,onClick:()=>n(c.value),className:`segmented-option pointer-coarse:min-h-11 ${d?"segmented-option-active":""}`,children:c.label}),c.description?e.jsx("span",{id:h,className:"sr-only",children:c.description}):null]},c.value)})})}const ap=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],rp={"7d":"last 7 days","30d":"last 30 days","90d":"last 90 days",all:"all sweeps"},ip={"non-brand":"Non-brand",branded:"Branded",all:"All queries"},op={"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."},lp={"select-query-class":"no query type selected","no-competitors":"no competitors configured","insufficient-observed":"needs 3 observed competitors, each named in 3 or more answers","no-answers":"no answer text","no-mentions":"no brands named",unavailable:"competitor data unavailable"},co="Mention share: your share of the brand mentions in these answers, each brand counted at most once per answer. Named: answers that name the brand. Cited: answers whose sources link to its site. Company names in answers are observations. Only competitor sites count toward mention share.",ti=100;function cp(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function rc(t){return t==="unavailable"?"Unavailable":"Not measured"}function si(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 Rs(t,s,n){return t===1?s:n}function ic(t){const s=t.label.trim(),n=nd(t.domain);return s&&s.toLowerCase()!==t.domain.toLowerCase()&&s.toLowerCase()!==n.toLowerCase()?s:null}function oc({row:t}){const s=ic(t);return s?e.jsxs(e.Fragment,{children:[s," ",e.jsx("span",{className:"av-of",children:t.domain})]}):e.jsx(e.Fragment,{children:t.domain})}function dp(t){const s=ic(t);return s?`${s} (${t.domain})`:t.domain}function uo(t,s){return s&&t>=ti?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:t})]}):e.jsx("strong",{children:t})}function ni({action:t,domain:s,mutation:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(null);async function c(){if(!a){r(!0),i(null);try{await n(s)===!1&&i(`Could not ${t} competitor. Try again.`)}catch{i(`Could not ${t} competitor. Try again.`)}finally{r(!1)}}}return e.jsxs(e.Fragment,{children:[e.jsxs(T,{type:"button",size:"sm",variant:"outline",disabled:a,onClick:()=>{c()},children:[t==="pin"?"Pin":"Unpin"," ",e.jsx("span",{className:"sr-only",children:s})]}),l?e.jsx("span",{role:"alert",className:"sr-only",children:l}):null]})}function up({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 Ln({count:t,of:s,state:n,toneClass:a}){return n!=="measured"?e.jsx("span",{className:"text-[13px] text-secondary",children:rc(n)}):e.jsxs("span",{className:"whitespace-nowrap",children:[e.jsx("span",{className:`av-n-sm ${a}`,children:t})," ",e.jsxs("span",{className:"av-of",children:["of ",s]})]})}function mo({percent:t,state:s,toneClass:n}){if(s!=="measured"||t===null)return e.jsx("span",{className:"text-[13px] text-secondary",children:s==="measured"?"Not measured":rc(s)});const{figure:a,sign:r}=bi(et(t,Qn.percent));return e.jsxs("span",{className:`av-n-sm ${n}`,children:[a,r?e.jsx("span",{className:"text-faint",children:r}):null]})}function mp({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(oc,{row:l})}),e.jsx("td",{className:"text-[13px] text-secondary",children:si(l.surfaceClass)}),e.jsx("td",{children:e.jsx(Ln,{count:l.mentionCount,of:n,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Ln,{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(up,{urls:l.sampleUrls}):null,r?e.jsx(ni,{action:"pin",domain:l.domain,mutation:r}):null]})})]},l.domain))})]})})}function hp({onAddCompetitor:t}){const s=o.useId(),[n,a]=o.useState(""),[r,l]=o.useState(!1),[i,c]=o.useState(null);async function d(){const h=n.trim();if(!(!h||r)){l(!0),c(null);try{if(await t(h)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("Could not add competitor. Try again.")}finally{l(!1)}}}return e.jsxs("details",{className:"inline-disclosure",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:h=>{h.preventDefault(),d()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange: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(T,{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 pp({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:l,onPin:i,onUnpin:c,onAddCompetitor:d,error:h,onRetry:u,isLoading:p=!1,scopeLabel:g}){const m=o.useId(),y=a&&!r,x=s?.pinned??n,b=s?.observed??[],N=s?.otherSources??[],C=s?.evidence,M=cp(s),k=s?.basis==="observed",f=k?b.filter(E=>E.shareOfVoice!==null):x,v=k?b.filter(E=>E.shareOfVoice===null):b,S=s?.filters.queryClass,q=s?.marketState?.draft?.pendingCompetitorDomains.length??0,I=s?.truncated===!0,w=C?.answeredResults??0,V=C?C.answeredResults+C.missingAnswerTextResults:0,F=S==="non-brand"&&s?.project.shareOfVoice!=null?ma[sd(s.project.shareOfVoice)]:"text-primary",W=E=>y?E.pinned?c?e.jsx(ni,{action:"unpin",domain:E.domain,mutation:c}):null:i?e.jsx(ni,{action:"pin",domain:E.domain,mutation:i}):null:null,B=f.some(E=>W(E)!==null),Q=[g,S?ip[S]:null,rp[t],s?.basis?k?"observed competitors only":"tracked competitors only":null].filter(Boolean).join(" · "),te=[];if(s&&!k&&f.length===0&&te.push({key:"no-pins",text:"No pinned competitors."}),s?.reason&&te.push({key:"reason",text:`Mention share: ${lp[s.reason]}`}),s&&v.length>0){const E=v.length;te.push({key:"others",text:I&&E>=ti?`${ti} or more other competitors seen`:`${E} other ${Rs(E,"competitor","competitors")} seen`})}q>0&&te.push({key:"pending",text:`${s?.scope.kind==="all-markets"?"Pending publication across markets":"Pending publication"}: ${q} ${Rs(q,"competitor","competitors")}`});const O=[C&&C.missingAnswerTextResults>0?"Answer data incomplete":null,C&&C.incompleteSourceResults>0?"Citation data incomplete":null].filter(Boolean);O.length>0&&te.push({key:"incomplete",text:O.join(" · "),className:ma.caution});const U=[];if(s&&C){U.push(s.runCount!==void 0?e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:s.runCount})," ",Rs(s.runCount,"sweep","sweeps"),", ",e.jsx("strong",{children:C.answeredResults})," ",Rs(C.answeredResults,"answer","answers")]}):e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:C.answeredResults})," ",Rs(C.answeredResults,"answer","answers")]})),!s.reason&&M==="measured"&&s.project.shareOfVoice!==null&&U.push(e.jsxs(e.Fragment,{children:["Mention share: you ",e.jsx("strong",{children:s.project.mentionCount}),f.map(P=>e.jsxs(Yc.Fragment,{children:[", ",P.domain," ",e.jsx("strong",{children:P.mentionCount})]},P.domain))," ","of ",e.jsx("strong",{children:C.mentionCredits})," ",k?"brand mentions":"tracked-brand mentions"]})),U.push(e.jsxs(e.Fragment,{children:["Answers with source links: ",e.jsx("strong",{children:C.sourceResults})]})),v.length===0&&U.push("Other competitors seen: none"),C.missingAnswerTextResults>0&&U.push(e.jsxs(e.Fragment,{children:["No answer text: ",e.jsx("strong",{children:C.missingAnswerTextResults})," ",Rs(C.missingAnswerTextResults,"answer","answers"),", left out of mention share"]})),C.incompleteSourceResults>0&&U.push(e.jsxs(e.Fragment,{children:["Incomplete source lists: ",e.jsx("strong",{children:C.incompleteSourceResults})," ",Rs(C.incompleteSourceResults,"answer","answers"),", not counted as misses"]}));const E=C.excludedProbeResults+C.excludedNonCompletedResults;E>0&&U.push(e.jsxs(e.Fragment,{children:["Left out: ",e.jsx("strong",{children:E})," ",Rs(E,"answer","answers")," from spot checks or unfinished sweeps"]}))}const se=[...s?[{name:"You",row:s.project}]:[],...f.map(E=>({name:E.domain,row:E}))].filter(E=>E.row.sampleUrls.length>0);M==="measured"&&se.length>0&&U.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsx("summary",{children:"Sample pages cited"}),e.jsx("div",{className:"av-subdetails-body",children:se.map(({name:E,row:P})=>e.jsxs("div",{children:[e.jsx("p",{children:E}),e.jsx("ul",{className:"space-y-1 font-mono text-[11px] text-muted",children:P.sampleUrls.map(Y=>e.jsx("li",{className:"break-all",children:Y},Y))})]},P.domain))})]})),s&&v.length>0&&U.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other competitors seen: ",uo(v.length,I)]}),e.jsx("div",{className:"av-subdetails-body",children:e.jsx(mp,{rows:v,state:M,named:w,cited:V,onPin:y?i:void 0})})]}));const D=s?.observedNames??[];if(D.length>0){const E=s?.observedNamesTotal??D.length;U.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Company names in answers: ",E>D.length?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:D.length})," of ",e.jsx("strong",{children:E})]}):e.jsx("strong",{children:D.length})]}),e.jsx("ul",{className:"av-subdetails-body",children:D.map(P=>e.jsxs("li",{children:[P.name," · ",P.answerCount," ",Rs(P.answerCount,"answer","answers")]},P.name))})]}))}return N.length>0&&U.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other sites cited: ",uo(N.length,I)]}),e.jsx("ul",{className:"av-subdetails-body",children:N.map(E=>e.jsxs("li",{children:[e.jsxs("span",{children:[dp(E)," · ",si(E.surfaceClass)," · ",E.citationCount," ",Rs(E.citationCount,"citation","citations")]}),E.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:E.sampleUrls.map(P=>e.jsx("li",{className:"break-all",children:P},P))}):null]},E.domain))})]})),e.jsxs("section",{"aria-labelledby":m,"aria-busy":p,className:"overview-brief",children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:m,className:"av-card-title",children:"Competitors over time"}),e.jsx(Be,{text:S?`${op[S]} ${co}`:co})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsx("p",{className:"av-card-meta",children:Q}),e.jsx(da,{label:"Competitors over time window",className:"flex-wrap",options:ap,value:t,onChange:l})]})]}),e.jsxs("div",{className:"av-card-body space-y-3",children:[h?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:h}),u?e.jsx(T,{type:"button",size:"sm",variant:"outline",onClick:u,children:"Retry competitors over time"}):null]}):null,p&&!s&&x.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||f.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(mo,{percent:s.project.shareOfVoice,state:M,toneClass:F})}),e.jsx("td",{children:e.jsx(Ln,{count:s.project.mentionCount,of:w,state:M,toneClass:F})}),e.jsx("td",{children:e.jsx(Ln,{count:s.project.citationCount,of:V,state:M,toneClass:F})}),B?e.jsx("td",{className:"av-brand-actions"}):null]}):null,f.map(E=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(oc,{row:E})}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:si(E.surfaceClass)}),e.jsx("td",{children:e.jsx(mo,{percent:E.shareOfVoice,state:M,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Ln,{count:E.mentionCount,of:w,state:M,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Ln,{count:E.citationCount,of:V,state:M,toneClass:"text-primary"})}),B?e.jsx("td",{className:"av-brand-actions",children:W(E)}):null]},E.domain))]})]}):null,te.length>0?e.jsx("div",{className:"space-y-1 text-[13px] text-secondary",children:te.map(E=>e.jsx("p",{className:E.className,children:E.text},E.key))}):null]}),e.jsx(va,{items:U}),y&&d?e.jsx("div",{className:"border-t border-subtle px-5 py-3",children:e.jsx(hp,{onAddCompetitor:d})}):null]})}function ho({history:t,maxDots:s=12,signal:n="citations"}){const a=t.slice(-s);if(a.length===0)return e.jsx("span",{className:"text-[13px] text-secondary",children:"No data"});const r=n==="mentions"?"Mention":"Citation",l=n==="mentions"?{cited:"mentioned","not-cited":"not mentioned",lost:"mention lost",emerging:"new mention",pending:"mention pending"}:{cited:"cited","not-cited":"not cited",lost:"citation lost",emerging:"new citation",pending:"citation pending"},i={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},c={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},d=a.length-1,h=new Date(a[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(a[d].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),p=`${a.length} ${a.length===1?"run":"runs"}`,g=a.map((m,y)=>{const x=new Date(m.createdAt).toLocaleDateString();return`${y===d?"Latest run, ":""}${x}: ${l[m.citationState]??m.citationState}${m.model?`, model ${m.model}`:""}`}).join("; ");return e.jsxs("div",{className:"inline-flex w-max items-center gap-2 whitespace-nowrap",role:"img","aria-label":`${r} history across ${p}. ${g}`,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:p,"aria-hidden":"true",children:a.map((m,y)=>{const x=!!(m.model&&y>0&&a[y-1]?.model&&a[y-1].model!==m.model),b=y===d;return e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 ${c[m.citationState]??"rounded-sm"} ${i[m.citationState]??"bg-mono-700"} ${x?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[l[m.citationState]??m.citationState,new Date(m.createdAt).toLocaleDateString(),m.model?`model ${m.model}`:null,x?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${m.runId}:${m.createdAt}`)})}),e.jsxs("span",{className:"text-[11px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{children:"latest"})]})]})}function ai(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 ja="__cited__",Na="__mentioned__",Ks="__mentionShare__";function $s(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Bt(n),end:Bt(a),sweepCount:s.sweepCount??1}}function ga(t,s=new Date){return rd(t,s)}function wa(t,s=new Date){const n=$s(t);if(!n)return null;const a=ga(n.start,s),r=ga(n.end,s);return a===r?a:`${a} to ${r}`}function Ai(t,s=new Date){const n=$s(t),a=wa(t,s);return!n||!a?"Sweep date unavailable":`${a} · ${n.sweepCount} ${n.sweepCount===1?"sweep":"sweeps"}`}function xp(t){const s=$s(t);return s?ad(s.start):""}function fa(t){return t.trim().toLowerCase()}function gp(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
2
- `)}const fp={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",muse:"Muse",local:"Local"};function rt(t){const s=fa(t);return fp[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ri(t){return Math.round(t*1e3)/10}function ii(t){return t.byProvider??{}}function yp(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?ja:Na,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(p=>({date:p.startDate,[d]:ri(p[h])})),series:[d],hasData:a,singleBucket:r}}const l=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys(ii(d))))].sort();return{rows:t.buckets.map(d=>{const h={date:d.startDate},u=ii(d);for(const p of i){const g=u[p];h[p]=g?ri(g[l]):null}return h}),series:i,hasData:a,singleBucket:r}}function lc(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function bp(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function vp(t){return t.servedModelAttribution??{}}function jp(t){return t.modelServiceMismatch??{}}function Np(t){return t.modelPointerChanges??{}}function ua(t){return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function ya(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 wp(t){return ua([...t.models,...t.includesUnknown?["an unknown model"]:[]])}function Sp(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 Cp(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:Sp(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function kp(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 Ap(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[Ks]:r?.rate==null?null:ri(r.rate)}}),n=s.map(a=>a[Ks]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Ks],hasData:n.length>0,singleBucket:n.length===1}}function Rp(t,s,n){return s==="mentionShare"?Ap(t):yp(t,s,n)}function Pp(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 Ip(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=ii(t.buckets[r])[s];if(l)return l[a]}return null}function We(t){return Date.parse(t)}function cc(t,s){const n=$s(t);if(!n)return!1;const a=We(s);return a>=We(n.start)&&a<=We(n.end)}function dc(t){return t.basketChanges??[]}function uc(t,s){return s.filter(n=>cc(t,n.at)).sort((n,a)=>We(n.at)-We(a.at))}function ir(t,s){return fa(t)==="perplexity"&&s.status==="known"&&!s.model.includes("/")}function Mp(t){return Object.entries(t).filter(([s,n])=>!ir(s,n.configured)).sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>({provider:s,mismatch:n}))}function qp(t){return[...dc(t)].sort((s,n)=>We(n.at)-We(s.at)).map(s=>({at:Bt(s.at),added:s.added,removed:s.removed}))}function $p(t,s){const n=[...t.events].sort((r,l)=>We(r.observedAt)-We(l.observedAt));let a=n[0]?.from??t.latestObservation.state;for(const r of n)We(r.observedAt)<=We(s)&&(a=r.to);return a}function po(t,s,n,a){return{provider:t,at:Bt(s.observedAt),onOrBefore:s.fromPreWindowAnchor===!0,anchorAt:s.anchorObservedAt?Bt(s.anchorObservedAt):null,from:s.from,to:s.to,served:n,reroute:a}}function Lp(t,s){const n=[];for(const[a,r]of Object.entries(t)){const i=s[a]?.events??[],c=new Set(r.events.map(d=>d.observedAt));for(const d of r.events){const h=ir(a,d.to)?i.find(u=>u.observedAt===d.observedAt):void 0;n.push(po(a,d,h?{from:h.from,to:h.to}:null,!1))}for(const d of i)c.has(d.observedAt)||ir(a,$p(r,d.observedAt))&&n.push(po(a,d,null,!0))}return n.sort((a,r)=>We(r.at)-We(a.at)||a.provider.localeCompare(r.provider))}function Ep({latest:t,queryChanges:s,modelRows:n,now:a=new Date}){const r=[...s.map(g=>g.at),...n.map(g=>g.at)];if(r.length===0)return null;const l=g=>t!==void 0&&cc(t,g),i=s.filter(g=>l(g.at)),c=i.reduce((g,m)=>g+m.added.length,0),d=i.reduce((g,m)=>g+m.removed.length,0),h=n.filter(g=>l(g.at)).length,u=t?wa(t,a):null;if(u===null||c+d+h===0){const g=r.reduce((m,y)=>We(y)>We(m)?y:m);return`No changes since ${ga(g,a)}`}const p=[u];return c>0&&p.push(`${c} ${c===1?"query":"queries"} added`),d>0&&p.push(`${d} ${d===1?"query":"queries"} removed`),h>0&&p.push(`${h} new ${h===1?"model":"models"}`),p.join(" · ")}function Dp(t,s,n,a=null){const r=We(t);if(!Number.isFinite(r))return null;const l=s.filter(h=>We(h)<r);if(l.length>0)return Bt(l.reduce((h,u)=>We(u)>We(h)?u:h));const i=n.map(h=>$s(h)).filter(h=>h!==null).sort((h,u)=>We(h.start)-We(u.start)),c=i.findIndex(h=>We(h.start)<=r&&r<=We(h.end));if(c===-1)return null;const d=i[c];return We(d.start)===r?c>0?i[c-1].end:a&&We(a)<r?Bt(a):null:d.sweepCount===2&&We(d.end)===r?d.start:null}function Op(t){const s=new Map,n=(a,r)=>{const l=s.get(a);l?l.push(r):s.set(a,[r])};for(const a of[...t].sort((r,l)=>r.revision-l.revision)){const r=We(a.at);for(const l of a.removed)n(l,{at:r,member:!1});for(const l of a.added)n(l,{at:r,member:!0})}return new Map([...s].filter(([,a])=>a.at(-1).member))}function Bn(t,s){let n=!t[0].member;for(const a of t)a.at<=s&&(n=a.member);return n}function Fp(t,s,n){return t.some(a=>a.at>s&&a.at<=n)}function oi(t,s){const n=We(s.start),a=We(s.end);return s.sweepCount>2?Fp(t,n,a):Bn(t,n)!==Bn(t,a)}function mc(t,s,n,a){const r=We(s),l=We(n),i={added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]},c=new Set;for(const[p,g]of Op(t)){if(!a(g))continue;c.add(p);const m=Bn(g,r),y=Bn(g,l);m!==y?(y?i.added:i.removed).push(p):(m?i.removedAndAddedBack:i.addedAndRemovedAgain).push(p)}if(c.size===0)return null;const d=p=>[...p.added,...p.removed].some(g=>c.has(g)),h=t.filter(p=>We(p.at)>r&&We(p.at)<=l&&d(p)).sort((p,g)=>We(p.at)-We(g.at)),u=[...new Set(h.flatMap(p=>[...p.added,...p.removed]))].filter(p=>c.has(p));return{changes:h,keys:u,moves:i}}function Kp(t,s){if(t.length<2)return null;const n=t[0],a=t.at(-1),r=$s(n),l=$s(a),i=r?.start??n.startDate,c=l?.end??a.endDate,d=mc(s,i,c,h=>Bn(h,We(i))!==Bn(h,We(c))||r!==null&&oi(h,r)||l!==null&&oi(h,l));return!d&&n.queryCount===a.queryCount?null:{...d??{changes:[],keys:[],moves:{added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]}},firstCount:n.queryCount,latestCount:a.queryCount}}function hc(t,s){const n=$s(t);if(!n)return null;const a=mc(s,n.start,n.end,r=>oi(r,n));return a?{...a,firstCount:t.queryCount,latestCount:t.queryCount}:null}function wr(t){return`${t} ${t===1?"query":"queries"}`}function Gp(t){const s=[],n=a=>s.length===0?wr(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(`${wr(t.removedAndAddedBack.length)} removed and added back`),t.addedAndRemovedAgain.length>0&&s.push(`${wr(t.addedAndRemovedAgain.length)} added and removed again`),ua(s)}function xo(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 go=320;function fo(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function yo(t){return t==="non-brand"?0:t==="branded"?1:2}function _p(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 Up(t){return t.phrase}function bo(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 vo(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 Bp(t,s){return t.map(n=>pc(n,s))}function pc(t,s){return s==="citations"?t:{...t,citationState:bo(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:bo(n,s)}))}}function jo(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,l=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",c=l==="cited"||l==="emerging";return r==="lost"||l!==null&&c&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||l!==null&&!c&&i?{key:s,label:`New ${n}`,tone:"positive"}:l===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Vp(t){const s=ai(Bp(t,"mentions")),n=ai(t);return[jo(s,"mentions"),jo(n,"citations")]}function Qp({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 No({items:t}){return e.jsx("div",{className:"query-evidence-signals","aria-label":"Latest run mention and citation signals",children:Vp(t).map(s=>e.jsx(Qp,{signal:s},s.key))})}function xc({queryClass:t,actions:s}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"query-evidence-toolbar",children:[t?e.jsx(id,{queryClass:t}):null,s?e.jsx("div",{className:"query-evidence-actions",children:s}):null]}),t?e.jsx(Al,{queryClass:t,legend:!1}):null]})}function zp({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed",providerSelection:a,onProviderSelectionChange:r,addedQueries:l=[],actions:i,actionPanel:c}){const{openEvidence:d}=vi(),h=o.useId(),[u,p]=o.useState(new Set),g=od(),[m,y]=o.useState("mentions"),[x,b]=o.useState(n),[N,C]=o.useState("all"),[M,k]=o.useState(""),f=a??M,v=D=>{k(D),r?.(D)},S=o.useMemo(()=>[...new Set([...t.map(D=>D.provider).filter(Boolean),...f?[f]:[]])].sort(),[t,f]),q=o.useMemo(()=>{const D=new Map;for(const E of t){if(f&&E.provider!==f)continue;const P=E.query,Y=E.queryClass??null,re=s?E.location??null:null,ne=JSON.stringify([P,Y,re]),de=D.get(ne)??{key:ne,phrase:P,queryClass:Y,location:re,items:[],rawItems:[]};de.items.push(pc(E,m)),de.rawItems.push(E),D.set(ne,de)}return[...D.values()].sort((E,P)=>yo(E.queryClass)-yo(P.queryClass))},[t,m,s,f]),I=o.useMemo(()=>q.filter(D=>N==="all"||(N==="unclassified"?D.queryClass===null:D.queryClass===N)),[q,N]),w=jn({rows:I,getSearchText:Up}),V=o.useMemo(()=>{const D=new Map;for(const E of w.filteredRows){const P=D.get(E.queryClass)??new Set;P.add(E.phrase),D.set(E.queryClass,P)}return D},[w.filteredRows]),F=o.useMemo(()=>new Set(l.map(Kn)),[l]),W=g?6:5,B=w.rows.map(D=>D.key),Q=B.length>0&&B.every(D=>u.has(D)),te=D=>{p(E=>{const P=new Set(E);return P.has(D)?P.delete(D):P.add(D),P})},O=m==="mentions"?"mentioned":"cited",U=m==="mentions"?"Mention History":"Citation History",se=m==="mentions"?"mentioned":"cited";return e.jsxs("div",{className:"query-evidence",children:[e.jsx(xc,{queryClass:N,actions:i}),c,e.jsxs("div",{className:"query-evidence-view-row",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"query-evidence-tabs",role:"tablist","aria-label":"Citation tracking view",children:["mentions","citations"].map(D=>e.jsx("button",{id:`${h}-${D}`,type:"button",role:"tab","aria-controls":h,"aria-selected":m===D,tabIndex:m===D?0:-1,onClick:()=>y(D),onKeyDown:E=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(E.key))return;E.preventDefault();const P=E.key==="Home"?"mentions":E.key==="End"||D==="mentions"?"citations":"mentions";y(P),document.getElementById(`${h}-${P}`)?.focus()},children:D==="mentions"?"Mentions":"Citations"},D))}),e.jsx(Be,{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:x==="detailed",onChange:D=>b(D.target.checked?"detailed":"compact")}),"Show answer previews"]}),e.jsx(T,{type:"button",variant:"ghost",className:"min-h-11",disabled:B.length===0,onClick:()=>{p(D=>{const E=new Set(D);for(const P of B)Q?E.delete(P):E.add(P);return E})},children:Q?"Collapse page":"Expand page"})]})]}),t.length>0||f?e.jsxs("div",{className:"query-evidence-filters",children:[e.jsx(Xs,{value:w.query,onChange:w.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:f,onChange:D=>{v(D.target.value),w.setPage(1)},children:[e.jsx("option",{value:"",children:"All engines"}),S.map(D=>e.jsx("option",{value:D,children:rt(D)},D))]})]}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Query class"}),e.jsxs("select",{value:N,onChange:D=>{C(D.target.value),w.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}-${m}`,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"}),g&&e.jsx("th",{scope:"col","aria-label":"Favorable",children:e.jsxs("span",{className:"inline-flex items-center",children:["Favorable",e.jsx(Be,{text:"Query rows show the favorable share of judged answers. Expanded engine rows show each stored answer’s sentiment; factual and unmentioned answers are not judgments."})]})}),e.jsx("th",{scope:"col",children:U}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Answer"})})]})}),_p(w.rows).map(D=>e.jsxs("tbody",{children:[e.jsx("tr",{className:"query-evidence-group",children:e.jsxs("th",{scope:"rowgroup",colSpan:W,children:[fo(D.queryClass)," (",V.get(D.queryClass)?.size??0,")"]})}),D.rows.map(({key:E,phrase:P,queryClass:Y,location:re,items:ne,rawItems:de})=>{const Ce=u.has(E),J=B.indexOf(E),oe=`${h}-query-${J}`,Ne=F.has(Kn(P)),X=ne.map(ee=>ee.citationState),ie=X.includes("cited")?"cited":X.includes("emerging")?"emerging":X.includes("lost")?"lost":X.every(ee=>ee==="pending")?"pending":"not-cited",G=[...new Set(de.map(ee=>ee.queryId).filter(ee=>!!ee))],he=de.map(ee=>ee.sourceSnapshotId).filter(ee=>!!ee),Le=ai(ne),be=ne.filter(ee=>ee.citationState===ld.cited||ee.citationState==="emerging").length;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-row",onClick:()=>te(E),children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("button",{type:"button",className:"query-evidence-query","aria-label":P,"aria-describedby":oe,"aria-expanded":Ce,onClick:ee=>{ee.stopPropagation(),te(E)},children:[e.jsx(ec,{size:16,"aria-hidden":"true",className:Ce?"rotate-90":""}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{children:P}),e.jsxs("span",{id:oe,className:"query-evidence-meta",children:[e.jsx("span",{children:fo(Y)}),s&&e.jsx("span",{children:re??"No location"}),ne.filter(ee=>ee.provider).map(ee=>e.jsx("span",{children:rt(ee.provider)},ee.id))]})]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ei,{state:ie,label:vo(ie,m),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":`${be} of ${ne.length} engines ${se}`,title:`${be} of ${ne.length} engines ${se}`,children:[be,"/",ne.length]})]})}),g&&e.jsx("td",{children:e.jsx(Rl,{queryId:G.length===1?G[0]:null,sourceSnapshotIds:G.length>1?[]:he,queryClass:Y,location:s?re:void 0})}),e.jsx("td",{children:e.jsx(ho,{history:Le,signal:m})}),e.jsx("td",{className:"evidence-change-cell",children:Ne?e.jsx("span",{className:"query-evidence-new",children:"new query"}):e.jsx(No,{items:de})}),e.jsx("td",{})]}),Ce&&ne.map((ee,Re)=>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:ee.provider?rt(ee.provider):"Awaiting engine"})}),e.jsx("td",{children:e.jsx(ei,{state:ee.citationState,className:"rounded-none border-0 bg-transparent p-0 text-sm tracking-normal",label:vo(ee.citationState,m)})}),g&&e.jsx("td",{children:e.jsx(Pl,{queryId:ee.queryId,sourceSnapshotIds:ee.sourceSnapshotId?[ee.sourceSnapshotId]:[],queryClass:ee.queryClass,provider:ee.provider,location:ee.location??null})}),e.jsx("td",{children:e.jsx(ho,{history:ee.runHistory,signal:m})}),e.jsx("td",{className:"evidence-change-cell",children:Ne?null:e.jsx(No,{items:[de[Re]??ee]})}),e.jsx("td",{children:e.jsx(T,{variant:"ghost",className:"min-h-11",type:"button",title:`View ${ee.provider?rt(ee.provider):"saved"} answer for ${ee.query}`,onClick:De=>{De.stopPropagation(),d(ee.id)},children:"View"})})]}),x==="detailed"&&e.jsx("tr",{className:"query-evidence-preview-row",children:e.jsx("td",{colSpan:W,children:e.jsx(Wp,{item:ee,mode:m,onViewFull:()=>d(ee.id)},m)})})]},ee.id))]},E)})]},D.queryClass??"unclassified"))]})}),w.totalRows===0&&(w.hasQuery||N!=="all"||f)?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Fs,{page:w.page,pageSize:w.pageSize,visibleRows:w.rows.length,totalRows:w.totalRows,onPageChange:w.setPage,itemLabel:w.hasQuery||N!=="all"||f?"matches":"queries"})]}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",O==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Hp(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const l=dd(r);return l.length>=4?[l]:[]}),...t.recommendedCompetitors??[]].filter(r=>r.trim().length>2),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 li(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function Wp({item:t,mode:s,onViewFull:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1);if(s==="mentions")return e.jsx(wo,{item:t,onViewFull:n});const c=t.evidenceUrls.length>0?t.evidenceUrls.map(d=>({uri:d,title:t.groundingSources.find(h=>h.uri===d)?.title})):t.groundingSources;return e.jsxs("div",{className:"query-evidence-preview space-y-3",children:[e.jsx("p",{className:"text-[13px] font-medium text-secondary",children:t.evidenceUrls.length>0?"Cited sources":c.length>0?"Grounding sources":"Cited domains"}),c.length>0?e.jsx("ul",{className:"space-y-4",children:c.slice(0,l?void 0:6).map((d,h)=>e.jsxs("li",{className:"min-w-0",children:[e.jsx(ji,{url:d.uri,title:d.title}),li(t,cd(d.uri)??"")&&e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:"Competitor source"})]},`${h}-${d.uri}`))}):t.citedDomains.length>0?e.jsx("ul",{className:"space-y-1 text-sm text-secondary",children:t.citedDomains.slice(0,l?void 0:6).map(d=>e.jsxs("li",{className:"[overflow-wrap:anywhere]",children:[d,li(t,d)?" · competitor source":""]},d))}):e.jsx("p",{className:"text-sm text-secondary",children:"No cited sources captured for this run."}),(c.length>6||c.length===0&&t.citedDomains.length>6)&&e.jsx(T,{type:"button",variant:"ghost",className:"min-h-11","aria-expanded":l,onClick:()=>i(d=>!d),children:l?"Show fewer sources":"View all sources"}),t.answerSnippet.trim()?e.jsxs("details",{open:a,className:"border-t border-subtle pt-1",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:d=>{d.preventDefault(),r(h=>!h)},children:"Answer text"}),a&&e.jsx(wo,{item:t,onViewFull:n,contextOnly:!0})]}):e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."})]})}function wo({item:t,onViewFull:s,contextOnly:n=!1}){const{matchedTerms:a,mentionedCompetitorDomains:r,recommendedCompetitors:l}=t,i=o.useMemo(()=>Hp({matchedTerms:a,mentionedCompetitorDomains:r,recommendedCompetitors:l}),[a,r,l]);if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."});const d=t.answerSnippet.length>go;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(Ci,{headingLevel:4,highlightGroups:i,previewLength:go,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(h=>e.jsxs("span",{className:"[overflow-wrap:anywhere]",children:[h,li(t,h)?" · competitor source":""]},`c-${h}`)),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(h=>e.jsx("span",{className:"[overflow-wrap:anywhere]",children:h},`co-${h}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]})]}),d&&e.jsx(T,{type:"button",variant:"ghost",className:"min-h-11",onClick:h=>{h.stopPropagation(),s()},children:"View full answer"})]})}function La({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 mr({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:()=>n(i),children:r?r(i):i},i))})}const Sr=it[0],Cr=it[1],So=it[2],Co=it[3],Yp=["both","server","ga4"],ko={fontSize:11,paddingTop:6},Ao=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Ro=t=>typeof t=="number"?Ja(Math.round(t)):String(t),is=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function kr(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 Ar({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(Be,{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,c=l??-1;return!(t[c]!=null&&t[c-1]==null&&t[c+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function Xp({projectName:t,sinceMinutes:s}){const[n,a]=o.useState(!0),[r,l]=o.useState(!0),[i,c]=o.useState("both"),d=_h(t,{sinceMinutes:s,granularity:"day",limit:1}),h=Uh(t),p=$e({...Il({client:H,path:{name:t}}),enabled:!!t,staleTime:yn}).data?.connected===!0,g=$e({...Tl({client:H,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&p,staleTime:yn}),m=o.useMemo(()=>d.data?.series?.points??[],[d.data]),y=o.useMemo(()=>{const q=g.data;return new Map((q?.days??[]).map(I=>[I.date,I.sessions]))},[g.data]),x=o.useMemo(()=>{const q=w=>w.measured!==!1;if(m.length===0||q(m[0]))return null;const I=m.findIndex(q)-1;return I<0?{from:m[0].bucket,to:m[m.length-1].bucket}:{from:m[0].bucket,to:m[I].bucket}},[m]),b=d.data?.series?.coverageStart??null,N=d.data?.series?.trends,C=o.useMemo(()=>{const q=kr(N?.crawlerContentHits,m.length),I=kr(N?.aiUserFetchHits,m.length),w=kr(N?.aiReferralLandedHits,m.length);return m.map((V,F)=>({...V,crawlerContentHits:V.measured!==!1?is(V.crawlerContentHits):null,aiUserFetchHits:V.measured!==!1?is(V.aiUserFetchHits):null,aiReferralLandedHits:V.measured!==!1?is(V.aiReferralLandedHits):null,ga4Visits:y.get(V.bucket)??null,crawlTrend:q[F],fetchTrend:I[F],visitTrend:w[F]}))},[m,y,N]),M=d.data?.totals,k=M&&{crawlers:is(M.crawlerContentHits),fetches:is(M.aiUserFetchHits),visits:is(M.aiReferralLandedHits)},f=o.useMemo(()=>m.reduce((q,I)=>({crawlers:q.crawlers+is(I.crawlerContentHits),fetches:q.fetches+is(I.aiUserFetchHits),visits:q.visits+is(I.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[m]),v=k??f,S=v.crawlers>0||v.fetches>0||v.visits>0;if(d.isLoading)return e.jsx(ve,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(d.isError)return e.jsxs(ve,{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(!S){const q=h.data?.sources,I=q!==void 0&&q.length===0,w=!I&&b===null;return e.jsxs(ve,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:I?"No server-side traffic source connected yet.":w?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:I?"Connect a traffic source to see how AI engines read this site over time.":w?"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(ve,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Ar,{label:"AI crawlers",value:Ja(v.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(Ar,{label:"AI page fetches",value:Ja(v.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(Ar,{label:"AI visitors",value:Ja(v.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."})]}),m.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:is(m[m.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:is(m[m.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:is(m[m.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(m[m.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(Be,{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:q=>a(q.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:q=>l(q.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(en,{width:"100%",height:206,children:e.jsxs(tn,{data:C,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(xa,{stroke:ha,vertical:!1}),e.jsx(sn,{dataKey:"bucket",tick:Ut,stroke:ms,tickFormatter:Nn,minTickGap:28}),e.jsx(nn,{tick:Ut,stroke:ms,width:48,allowDecimals:!1}),e.jsx(an,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:At,formatter:Ro}),x&&e.jsx(Xr,{x1:x.from,x2:x.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(rr,{wrapperStyle:ko,iconType:"plainline",iconSize:14,formatter:q=>Ao.has(q)?"":q}),e.jsx(Ys,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Sr,fill:Sr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Ys,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Cr,fill:Cr,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Ds,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Sr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Ds,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Cr,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(Be,{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(mr,{windows:Yp,value:i,onChange:c,label:"Visit measurement source",formatOption:q=>q==="ga4"?"GA4":q==="both"?"Both":"Server"})]}),e.jsx(en,{width:"100%",height:176,children:e.jsxs(tn,{data:C,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(xa,{stroke:ha,vertical:!1}),e.jsx(sn,{dataKey:"bucket",tick:Ut,stroke:ms,tickFormatter:Nn,minTickGap:28}),e.jsx(nn,{tick:Ut,stroke:ms,width:48,allowDecimals:!1}),e.jsx(an,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:At,formatter:Ro}),x&&e.jsx(Xr,{x1:x.from,x2:x.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(rr,{wrapperStyle:ko,iconType:"plainline",iconSize:14,formatter:q=>Ao.has(q)?"":q}),i!=="ga4"&&e.jsx(Ds,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:So,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Ds,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Co,strokeWidth:1.8,strokeDasharray:"5 3",dot:Jp(C.map(q=>q.ga4Visits),Co)}),r&&i!=="ga4"&&e.jsx(Ds,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:So,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const Zp=6,Vn="__other__",On="_socialTotal";function ex(t,s=Zp){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,p)=>p[1]!==u[1]?p[1]-u[1]:u[0].localeCompare(p[0])),r=a.slice(0,s),l=new Set(r.map(([u])=>u)),i=Math.max(0,a.length-s),c=new Map;for(const u of t){let p=c.get(u.date);p||(p={date:u.date,[On]:0},c.set(u.date,p));const g=l.has(u.source)?u.source:Vn;p[g]=(p[g]??0)+u.sessions,p[On]=(p[On]??0)+u.sessions}const d=[...c.values()].sort((u,p)=>String(u.date).localeCompare(String(p.date))),h=r.map(([u])=>u);return i>0&&h.push(Vn),{data:d,sources:h,otherCount:i}}function Fn(t){return t.replace(/\+/g," ")}function gc(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Po="_totalSessions",Io="_organicSessions";function tx(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Po]:i.sessions,[Io]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[Po]:0,[Io]:0},n.set(i.date,c));for(const d of i.bySource)c[d.source]=(c[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([i],[c])=>i.localeCompare(c)).map(([i,c])=>({date:i,...c})),r=a.map(i=>i.date),l=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:l}}const sx=["7d","30d","90d"],nx={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Ws=it,ci=hs.textDim,fc=hs.textFaint,ea=25;function ax(t){return Jl(t.landingPage)}const rx=25,ix=10,Rr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Ea(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function yc(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 ox({projectName:t}){const{data:s,isLoading:n,isError:a}=Bh(t);if(n)return e.jsx(ve,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(ve,{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."," ",!le()&&e.jsx(qs,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(ve,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!le()&&e.jsxs(e.Fragment,{children:[e.jsx(qs,{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(ve,{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(je,{tone:Vh(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?yc(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:le()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(qs,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function lx({projectName:t}){const[s,n]=o.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(ox,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(mr,{windows:sx,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(cx,{projectName:t,window:s}),e.jsx(Xp,{projectName:t,sinceMinutes:nx[s]})]})}function cx({projectName:t,window:s}){const n=ps(),a=s??"30d",[r,l]=o.useState(null),[i,c]=o.useState(null),[d,h]=o.useState(!0),[u,p]=o.useState(!1),[g,m]=o.useState(!1),[y,x]=o.useState(null),[b,N]=o.useState(null),[C,M]=o.useState("sessions"),[k,f]=o.useState("desc"),[v,S]=o.useState("sessions"),[q,I]=o.useState("desc"),[w,V]=o.useState("sessions"),[F,W]=o.useState("desc"),[B,Q]=o.useState("sessions"),[te,O]=o.useState("desc"),[U,se]=o.useState(Rr),[D,E]=o.useState([]),[P,Y]=o.useState([]),[re,ne]=o.useState(!1);async function de(Z){h(!0),x(null);try{const Fe=await n.fetchQuery({...Il({client:H,path:{name:t}}),staleTime:yn});if(Z.current)return;if(l(Fe),!Fe.connected){c(null),se(Rr),E([]),Y([]),h(!1);return}const Ie=a==="all"?void 0:a,Pe=await n.fetchQuery({...ud({client:H,path:{name:t},query:Ie?{window:Ie}:void 0}),staleTime:yn}),qt=Pe.windowStart||Pe.windowEnd?{...Pe.windowStart?{startDate:Pe.windowStart}:{},...Pe.windowEnd?{endDate:Pe.windowEnd}:{}}:void 0,[vt,Yt,nt]=await Promise.all([n.fetchQuery({...Tl({client:H,path:{name:t},query:Ie?{window:Ie}:void 0}),staleTime:yn}).catch(()=>Rr),n.fetchQuery({...md({client:H,path:{name:t},query:Ie?{window:Ie}:void 0}),staleTime:yn}).catch(()=>[]),n.fetchQuery({...hd({client:H,path:{name:t},query:qt}),staleTime:yn}).catch(()=>[])]);if(Z.current)return;c(Pe),se(vt),E(Yt),Y(nt),h(!1)}catch(Fe){if(Z.current)return;x(Fe instanceof Error?Fe.message:"Failed to load GA4 data"),h(!1)}}o.useEffect(()=>{const Z={current:!1};return de(Z),()=>{Z.current=!0}},[t,a,n]);async function Ce(){p(!0),x(null),N(null);try{const Z=await Ml(t);N(`Synced ${Z.rowCount.toLocaleString()} page rows, ${Z.aiReferralCount.toLocaleString()} AI and ${Z.socialReferralCount.toLocaleString()} social referral rows (${Z.days} days)`),await It(n,"ga"),await de({current:!1})}catch(Z){x(Z instanceof Error?Z.message:"Sync failed")}finally{p(!1)}}async function J(){m(!0),x(null),N(null);try{await pd(t),await It(n,"ga"),l({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),N("GA4 disconnected")}catch(Z){x(Z instanceof Error?Z.message:"Disconnect failed")}finally{m(!1)}}function oe(Z){G.setPage(1),C===Z?f(Fe=>Fe==="desc"?"asc":"desc"):(M(Z),f("desc"))}function Ne(Z){v===Z?I(Fe=>Fe==="desc"?"asc":"desc"):(S(Z),I("desc"))}function X(Z){w===Z?W(Fe=>Fe==="desc"?"asc":"desc"):(V(Z),W("desc"))}const ie=o.useMemo(()=>i?.topPages?[...i.topPages].sort((Z,Fe)=>{const Ie=Z[C],Pe=Fe[C];return typeof Ie=="string"&&typeof Pe=="string"?k==="asc"?Ie.localeCompare(Pe):Pe.localeCompare(Ie):k==="asc"?Ie-Pe:Pe-Ie}):[],[i?.topPages,C,k]),G=jn({rows:ie,getSearchText:Z=>Jl(Z.landingPage),pageSize:ix}),he=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((Z,Fe)=>{const Ie=Z[v],Pe=Fe[v];return typeof Ie=="string"&&typeof Pe=="string"?q==="asc"?Ie.localeCompare(Pe):Pe.localeCompare(Ie):q==="asc"?Ie-Pe:Pe-Ie}):[],[i?.aiReferrals,v,q]),Le=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((Z,Fe)=>{const Ie=Z[B],Pe=Fe[B];return typeof Ie=="string"&&typeof Pe=="string"?te==="asc"?Ie.localeCompare(Pe):Pe.localeCompare(Ie):te==="asc"?Ie-Pe:Pe-Ie}):[],[i?.aiReferralLandingPages,B,te]),be=jn({rows:Le,getSearchText:ax,pageSize:rx}),ee=be.totalRows>0?`${be.totalRows.toLocaleString()} ${be.hasQuery?be.totalRows===1?"match":"matches":be.totalRows===1?"row":"rows"}`:be.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Re(Z){be.setPage(1),B===Z?O(Fe=>Fe==="desc"?"asc":"desc"):(Q(Z),O("desc"))}const De=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((Z,Fe)=>{const Ie=Z[w],Pe=Fe[w];return typeof Ie=="string"&&typeof Pe=="string"?F==="asc"?Ie.localeCompare(Pe):Pe.localeCompare(Ie):F==="asc"?Ie-Pe:Pe-Ie}):[],[i?.socialReferrals,w,F]),{socialChartData:qe,socialChartSources:xe,socialOtherCount:K}=o.useMemo(()=>{const Z=ex(P);return{socialChartData:Z.data,socialChartSources:Z.sources,socialOtherCount:Z.otherCount}},[P]),{chartData:Oe,chartSources:R,dateRange:ye}=o.useMemo(()=>{const Z=tx(U,D);return{chartData:Z.data,chartSources:Z.sources,dateRange:Z.dateRange}},[U,D]);if(d&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return le()||Os()?e.jsx(ve,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(dx,{projectName:t,onConnected:()=>{(async()=>(await It(n,"ga"),await de({current:!1})))()}});const Ke=i?.organicSharePctDisplay??"0%",ze=i?.channelBreakdown?.organic.sharePctDisplay??Ke,Je=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,pe=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,ht=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Ve=i?.paidAiSessionsBySession??0,tt=i?.paidAiSharePctBySessionDisplay??"0%",Wt=i?new Set(i.aiReferrals.map(Z=>Z.source.toLowerCase())).size:0,dt=he[0]??null,st=i?.totalDirectSessions??0,pt=i?.directSharePctDisplay??"0%",St=i?.channelBreakdown?.direct.sessions??st,Rt=i?.channelBreakdown?.direct.sharePctDisplay??pt,Ge=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,A=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",ke=i?.socialSessions??0,ue=i?.socialSharePctDisplay??"0%",He=i?.channelBreakdown?.social.sessions??ke,Tt=i?.channelBreakdown?.social.sharePctDisplay??ue,Mt=i?new Set(i.socialReferrals.map(Z=>Z.source.toLowerCase())).size:0,ot=De[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})]})]})]}),!le()&&!Os()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(T,{variant:"outline",size:"sm",disabled:u,onClick:Xe(Ce),children:[e.jsx(pa,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(T,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:g,onClick:Xe(J),children:[e.jsx(Ih,{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(Be,{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(Pr,{value:Ea(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Pr,{value:Ea(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Ke} of total`,tone:"positive"}),e.jsx(Pr,{value:i.totalUsers===null?"—":Ea(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."}),!le()&&!Os()&&e.jsxs(T,{variant:"outline",size:"sm",disabled:u,onClick:Xe(Ce),children:[e.jsx(pa,{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(Be,{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."})]})]}),ye&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(ye.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(ye.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),Oe.length>0&&e.jsxs(ve,{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:R.length>0?"AI vs. total sessions":"All sessions (baseline)"}),R.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),R.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(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:Oe,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(sn,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:ms},tickFormatter:Nn}),e.jsx(nn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...ns,labelFormatter:At,formatter:(Z,Fe)=>{const Ie=typeof Z=="number"?Z.toLocaleString():String(Z??0),Pe=String(Fe??"");return Pe==="_totalSessions"?[Ie,"Total Sessions"]:Pe==="_organicSessions"?[Ie,"Organic Sessions"]:[Ie,Pe]}}),e.jsx(rr,{wrapperStyle:{fontSize:11,color:hs.text},formatter:Z=>Z==="_totalSessions"?"Total Sessions":Z==="_organicSessions"?"Organic Sessions":Z}),e.jsx(Ys,{type:"monotone",dataKey:"_totalSessions",stroke:hs.textFaint,fill:hs.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),R.map((Z,Fe)=>e.jsx(Ys,{type:"monotone",dataKey:Z,stackId:"ai",stroke:Ws[Fe%Ws.length],fill:Ws[Fe%Ws.length],fillOpacity:.4,strokeWidth:1.5},Z))]})})})]}),e.jsxs(ve,{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(bs,{label:"Organic",value:ze,hint:`${Je.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(bs,{label:"Social",value:Tt,hint:`${He.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(bs,{label:"Direct",value:Rt,hint:`${St.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(bs,{label:"Visitors from AI (at least)",value:ht,hint:Ve>0?`${pe.toLocaleString()} sessions · ${Ve.toLocaleString()} paid`:`${pe.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(bs,{label:"Other channels",value:A,hint:`${Ge.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."})]}),dt&&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:dt.source})," via ",dt.medium,", accounting for ",dt.sessions.toLocaleString()," sessions.",Ve>0&&e.jsxs("span",{children:[" Paid AI: ",Ve.toLocaleString()," sessions (",tt,")."]})]})]}),e.jsxs(ve,{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?`${Wt} 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(os,{label:"Source",sortKey:"source",current:v,dir:q,onSort:Ne,align:"left"}),e.jsx(os,{label:"Medium",sortKey:"medium",current:v,dir:q,onSort:Ne,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(os,{label:"Sessions",sortKey:"sessions",current:v,dir:q,onSort:Ne,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:he.map(Z=>e.jsx(mx,{referral:Z},`${Z.source}:${Z.medium}:${Z.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(ve,{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:ee})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Xs,{value:be.query,onChange:be.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),be.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(os,{label:"Landing Page",sortKey:"landingPage",current:B,dir:te,onSort:Re,align:"left"}),e.jsx(os,{label:"Source",sortKey:"source",current:B,dir:te,onSort:Re,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(os,{label:"Sessions",sortKey:"sessions",current:B,dir:te,onSort:Re,align:"right"})]})}),e.jsx("tbody",{children:be.rows.map(Z=>e.jsx(hx,{row:Z},`${Z.landingPage}:${Z.source}:${Z.medium}:${Z.sourceDimension}`))})]})}),e.jsx(Fs,{page:be.page,pageSize:be.pageSize,visibleRows:be.rows.length,totalRows:be.totalRows,onPageChange:be.setPage,itemLabel:be.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:()=>be.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(Be,{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(ve,{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(bs,{label:"Social Sessions",value:Ea(ke),hint:`${ke.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(bs,{label:"Share of Traffic",value:ue,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(bs,{label:"Platforms",value:String(Mt),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."})]}),ot&&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:`${ot.source} via ${ot.medium}`,children:gc(Fn(ot.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:ot.medium,children:["via ",Fn(ot.medium)," · ",ot.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(bs,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(bs,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(bs,{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."})]})]})]}),qe.length>0&&e.jsxs(ve,{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"})]}),K>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",xe.length-1," sources · ",K," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:qe,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(sn,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:ms},tickFormatter:Nn}),e.jsx(nn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...ns,labelFormatter:At,formatter:(Z,Fe)=>{const Ie=typeof Z=="number"?Z.toLocaleString():String(Z??0),Pe=String(Fe??"");if(Pe===On)return[Ie,"Total Social"];if(Pe===Vn){const qt=`Other (${K} source${K===1?"":"s"})`;return[Ie,qt]}return[Ie,Fn(Pe)]}}),e.jsx(Ys,{type:"monotone",dataKey:On,stroke:fc,fill:hs.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),xe.map((Z,Fe)=>{const Pe=Z===Vn?ci:Ws[Fe%Ws.length];return e.jsx(Ys,{type:"monotone",dataKey:Z,stackId:"social",stroke:Pe,fill:Pe,fillOpacity:.4,strokeWidth:1.5},Z)})]})})}),e.jsx(xx,{sources:xe,otherCount:K})]}),e.jsxs(ve,{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?De.length>ea&&!re?`Top ${ea} of ${De.length}`:`${De.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(os,{label:"Source",sortKey:"source",current:w,dir:F,onSort:X,align:"left"}),e.jsx(os,{label:"Medium",sortKey:"medium",current:w,dir:F,onSort:X,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(os,{label:"Sessions",sortKey:"sessions",current:w,dir:F,onSort:X,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(re?De:De.slice(0,ea)).map(Z=>e.jsx(px,{referral:Z},`${Z.source}:${Z.medium}:${Z.channelGroup}`))})]})}),De.length>ea&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>ne(Z=>!Z),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:re?`Show top ${ea}`:`Show all ${De.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(Be,{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(Xs,{value:G.query,onChange:G.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(os,{label:"Landing Page",sortKey:"landingPage",current:C,dir:k,onSort:oe,align:"left"}),e.jsx(os,{label:"Sessions",sortKey:"sessions",current:C,dir:k,onSort:oe,align:"right"}),e.jsx(os,{label:"Organic",sortKey:"organicSessions",current:C,dir:k,onSort:oe,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:G.rows.map(Z=>e.jsx(ux,{page:Z},Z.landingPage))})]})}),G.totalRows===0&&G.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Fs,{page:G.page,pageSize:G.pageSize,visibleRows:G.rows.length,totalRows:G.totalRows,onPageChange:G.setPage,itemLabel:G.hasQuery?"matches":"pages"})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${yc(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function dx({projectName:t,onConnected:s}){const[n,a]=o.useState(""),[r,l]=o.useState(null),[i,c]=o.useState(null),[d,h]=o.useState(!1),[u,p]=o.useState(null),g=o.useRef(null),m=o.useCallback(x=>{const b=x.target.files?.[0];if(!b)return;p(null),l(b.name);const N=new FileReader;N.onload=()=>{const C=N.result;try{const M=JSON.parse(C);if(!M.client_email||!M.private_key){p("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),c(null);return}c(C)}catch{p("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},N.onerror=()=>{p("Failed to read file."),c(null)},N.readAsText(b)},[]);async function y(){if(p(null),!n.trim()){p("Property ID is required.");return}if(!i){p("Please upload a service account key file.");return}h(!0);try{await xd(t,{propertyId:n.trim(),keyJson:i});try{await Ml(t)}catch{}s()}catch(x){p(x instanceof Error?x.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(ve,{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:x=>a(x.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:g,type:"file",accept:".json,application/json",onChange:m,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>g.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(Th,{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(T,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:Xe(y),children:d?"Connecting & syncing…":"Connect GA4"})]})}function os({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 bc={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Pr({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 ${bc[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function bs({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(Be,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${bc[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function ux({page:t}){const s=et(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 vc={session:"Session",first_user:"First Visit",manual_utm:"UTM"},jc={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 mx({referral:t}){const s=et(t.share),n=vc[t.sourceDimension]??t.sourceDimension,a=jc[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 hx({row:t}){const s=vc[t.sourceDimension]??t.sourceDimension,n=jc[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(Za,{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 px({referral:t}){const s=et(t.share),n=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Fn(t.source),r=Fn(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 xx({sources:t,otherCount:s}){const n=[{key:On,color:fc,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Vn)n.push({key:Vn,color:ci,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Fn(r);n.push({key:r,color:Ws[a%Ws.length]??ci,label:gc(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 gx(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 fx="Search Console is not connected yet. Your Canonry team can set this up.",yx=["7d","30d","90d","all"],Da=500,To=[{key:"clicks",label:"Clicks",color:it[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:it[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:zn.caution,format:t=>et(t)},{key:"position",label:"Avg position",color:it[2],inverted:!0,format:t=>t.toFixed(1)}],zs=25,bx="canonry:google-oauth-complete";function vx(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const i=t.prior[s],c=t.trailing[s];return i!==null&&c!==null&&i<=0&&c>0?`new in the last ${a}d`:i===null||i<=0?`no prior ${a}d to compare`:c===null?`no value in the last ${a}d`:"comparison unavailable"}return r===0?`→ no change vs prior ${a}d`:`${(n?r<0:r>0)?"↑":"↓"} ${et(Math.abs(r))} vs prior ${a}d`}function jx(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,l=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,c=`${r.startDate} to ${r.endDate}`,d=`Tile percentages compare these ${s} ${l} (${c}) with the ${s} ${l} before them (${i}).`;return n!=="split-window"?d:`${d} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function Mo(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function qo(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 $o(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Nx({projectName:t,refreshNonce:s}){const n=ps(),{isAdmin:a}=Sn(),r=Os(),[l,i]=o.useState(!1),[c,d]=o.useState([]),[h,u]=o.useState([]),[p,g]=o.useState([]),[m,y]=o.useState(null),[x,b]=o.useState([]),[N,C]=o.useState([]),[M,k]=o.useState(null),[f,v]=o.useState(""),[S,q]=o.useState(""),[I,w]=o.useState("30"),[V,F]=o.useState(!1),[W,B]=o.useState("30d"),[Q,te]=o.useState(["clicks","impressions"]),[O,U]=o.useState(!0),[se,D]=o.useState(null),[E,P]=o.useState(0),[Y,re]=o.useState({startDate:"",endDate:"",query:"",page:""}),[ne,de]=o.useState(0),[Ce,J]=o.useState(!1),[oe,Ne]=o.useState(0),[X,ie]=o.useState(!1),[G,he]=o.useState(""),[Le,be]=o.useState(!0),[ee,Re]=o.useState(!1),[De,qe]=o.useState(!1),[xe,K]=o.useState(!1),[Oe,R]=o.useState(!1),[ye,Ke]=o.useState(!1),[ze,Je]=o.useState(!1),[pe,ht]=o.useState(null),[Ve,tt]=o.useState(!1),[Wt,dt]=o.useState(!1),[st,pt]=o.useState(null),[St,Rt]=o.useState(null),[Ge,A]=o.useState([]),[ke,ue]=o.useState(new Set),[He,Tt]=o.useState({}),[Mt,ot]=o.useState(new Set),[Z,Fe]=o.useState(""),[Ie,Pe]=o.useState(null),[qt,vt]=o.useState(""),[Yt,nt]=o.useState(!1),[$t,Zt]=o.useState(!1),[vs,js]=o.useState(!1),[Ns,Gs]=o.useState(!1),[ft,xs]=o.useState("indexed"),[Ze,Ft]=o.useState(null),es=!!(Y.query.trim()||Y.page.trim()||Ze),as=Ze!==null,gs=o.useMemo(()=>{if(!Ze)return p;const{key:j,dir:z}=Ze;return[...p].sort((ce,Se)=>{const at=j===bn.CTR?Number.isFinite(ce.ctr)?ce.ctr:0:ce[j],Ue=j===bn.CTR?Number.isFinite(Se.ctr)?Se.ctr:0:Se[j];return z==="asc"?at-Ue:Ue-at})},[p,Ze]),jt=jn({rows:gs,pageSize:Ls}),Pt=X?jt.rows:gs,ts=jn({rows:(st??[]).filter(j=>j.path.toLowerCase().includes(Z.trim().toLowerCase())),pageSize:Ls}),[Kt,_s]=o.useState([]),[Nt,Jt]=o.useState(null),[xt,_]=o.useState(1),ae=o.useMemo(()=>{if(Kt.length<2)return null;const j=Kt[Kt.length-1],z=Kt[Kt.length-2];return{indexed:j.indexed-z.indexed,notIndexed:j.notIndexed-z.notIndexed}},[Kt]);o.useEffect(()=>{_(1)},[pe,ft,Nt]);const Ae=o.useMemo(()=>Nt?(pe?.reasonGroups??[]).find(j=>j.reason===Nt):void 0,[pe,Nt]),me=o.useMemo(()=>pe?ft==="indexed"?pe.indexed:ft==="deindexed"?pe.deindexed:ft==="notIndexed"?Nt?Ae?.urls??[]:(pe.reasonGroups??[]).length===0?pe.notIndexed:[]:[]:[],[pe,ft,Nt,Ae]),Te=Math.max(1,Math.ceil(me.length/zs)),_e=Math.min(Math.max(1,xt),Te),mt=(_e-1)*zs,yt=o.useMemo(()=>pe?.indexed.slice(mt,mt+zs)??[],[pe,mt]),ss=o.useMemo(()=>pe?.notIndexed.slice(mt,mt+zs)??[],[pe,mt]),L=o.useMemo(()=>pe?.deindexed.slice(mt,mt+zs)??[],[pe,mt]),we=o.useMemo(()=>(Ae?.urls??[]).slice(mt,mt+zs),[Ae,mt]),[lt,Lt]=o.useState(!1),[Xt,Qe]=o.useState(null),[bt,rs]=o.useState(null),[Hn,fs]=o.useState(null);function rn(j,z){const ce=Qh(j),Se=gx(ce);Se?(rs(Se),Qe(null)):(rs(null),Qe(ce.message||z))}const Et=c.find(j=>j.connectionType==="gsc"),ws=(Et?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),on=Ge.length>0?Ge:(st??[]).map(j=>j.path),Sa=on.filter(j=>st?.some(z=>z.path===j&&z.isSitemapsIndex)).length,Wn=Sa===1?"Resubmit sitemap index":Sa>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Vi=p.length>0||x.length>0||N.length>0,Ca=gd(),ln=fd();async function ka(j,z=!1){if(r){u([]);return}if(!j){u([]),v("");return}qe(!0);try{const{sites:ce}=await n.fetchQuery({...Md({client:H,path:{name:t}}),staleTime:z?0:zt});u(ce),v(j.propertyId??ce[0]?.siteUrl??""),rs(null)}catch(ce){u([]),rn(ce,"Failed to load Search Console properties")}finally{qe(!1)}}async function Ss(j){R(!0);const z=j??ne;try{const ce=es?Da:Ls,Se=es?0:z,at={limit:String(ce)};Y.startDate&&(at.startDate=Y.startDate),Y.endDate&&(at.endDate=Y.endDate),Y.query&&(at.query=Y.query),Y.page&&(at.page=Y.page),Se>0&&(at.offset=String(Se)),W&&W!=="all"&&!Y.startDate&&(at.window=W);const Ue=await n.fetchQuery({...jd({client:H,path:{name:t},query:at}),staleTime:zt}),ut=Ue.rows;es?(J(!1),g(ut),Ne(ut.length),ie(!0)):(J(Se+ut.length<Ue.totalMatching),g(ut),Ne(0),ie(!1))}catch(ce){g([]),J(!1),Ne(0),Qe(ce instanceof Error?ce.message:"Failed to load GSC performance data")}finally{R(!1)}}async function Us(){try{const j={};Y.startDate&&(j.startDate=Y.startDate),Y.endDate&&(j.endDate=Y.endDate),W&&W!=="all"&&!Y.startDate&&(j.window=W);const z=await n.fetchQuery({...vd({client:H,path:{name:t},query:j}),staleTime:zt});y(z)}catch{y(null)}}async function Bs(j=!1){Ke(!0);try{const z=G.trim()||void 0,ce={limit:"20"};z&&(ce.url=z);const[Se,at]=await Promise.all([n.fetchQuery({...Id({client:H,path:{name:t},query:ce}),staleTime:j?0:zt}),n.fetchQuery({...Td({client:H,path:{name:t}}),staleTime:j?0:zt})]);b(Se),C(at)}catch(z){b([]),C([]),Qe(z instanceof Error?z.message:"Failed to load GSC inspection history")}finally{Ke(!1)}}async function Cn(j=!1){tt(!0);try{const[z,ce]=await Promise.all([n.fetchQuery({...Sd({client:H,path:{name:t}}),staleTime:j?0:zt}),n.fetchQuery({...Cd({client:H,path:{name:t}}),staleTime:j?0:zt}).catch(()=>[])]);ht(z),_s(ce)}catch(z){ht(null),_s([]),Qe(z instanceof Error?z.message:"Failed to load coverage data")}finally{tt(!1)}}async function kn(j){Lt(!0),Qe(null);try{const z=await Yi(t,{urls:j}),{succeeded:ce,failed:Se,total:at}=z.summary;Ee({title:"Indexing requested",detail:Se===0?`${ce} URL${ce!==1?"s":""} submitted for indexing.`:`${ce}/${at} submitted successfully, ${Se} failed.`,tone:Se===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(z){Qe(z instanceof Error?z.message:"Failed to request indexing")}finally{Lt(!1)}}async function Yn(){Lt(!0),Qe(null);try{const j=await Yi(t,{urls:[],allUnindexed:!0}),{succeeded:z,failed:ce,total:Se}=j.summary;Ee({title:"Indexing requested",detail:ce===0?`${z} unindexed URL${z!==1?"s":""} submitted for indexing.`:`${z}/${Se} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(j){Qe(j instanceof Error?j.message:"Failed to request indexing")}finally{Lt(!1)}}async function An(){dt(!0),Qe(null);try{const j=await fr(t);n.setQueryData(kd({client:H,path:{name:t}}),j),pt(j.sitemaps),Rt(j.summary),A(j.preferredSubmissionUrls),ue(new Set),Tt({}),j.sitemaps.length===0&&fs("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(j){Qe(j instanceof Error?j.message:"Failed to list sitemaps")}finally{dt(!1)}}async function hr(j){const z=ke.has(j);if(ue(ce=>{const Se=new Set(ce);return z?Se.delete(j):Se.add(j),Se}),!(z||He[j])){ot(ce=>new Set(ce).add(j));try{const ce=await fr(t,j);Tt(Se=>({...Se,[j]:ce.sitemaps}))}catch(ce){Qe(ce instanceof Error?ce.message:"Failed to load sitemap files")}finally{ot(ce=>{const Se=new Set(ce);return Se.delete(j),Se})}}}async function Vs(j){if(!ws||j.length===0)return;const z=[...new Set(j)];Zt(!0),Qe(null),Pe({completed:0,total:z.length});let ce=0,Se=0,at=0,Ue=null;try{for(let Dt=0;Dt<z.length;Dt+=50){const ct=z.slice(Dt,Dt+50);try{const Me=await Ad(t,ct);ce+=Me.summary.accepted,Se+=Me.summary.failed,at+=ct.length,Pe({completed:at,total:z.length})}catch(Me){at+=ct.length;const Cs=ct.length,dn=z.length-at,Rn=Me instanceof Error?Me.message:"The batch request failed",ys=`${ce} accepted, ${Se} failed, ${Cs} unconfirmed, ${dn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Ue=`Sitemap submission stopped after a batch request failed. ${ys} ${Rn}`,Qe(Ue),Ee({title:"Sitemap resubmission partially completed",detail:ys,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const ut=z.length;Ee({title:Se===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:Se===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ce}/${ut} sitemap submissions; ${Se} failed. Indexing is not guaranteed.`,tone:Se===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),vt("")}catch(ut){Qe(ut instanceof Error?ut.message:"Failed to submit sitemap to Google")}finally{Zt(!1),Pe(null),await An(),Ue&&Qe(Ue)}}async function Qi(){Zt(!0);const j=st??[];try{const z=j.filter(Se=>Se.isSitemapsIndex),ce=[];for(let Se=0;Se<z.length;Se+=4)(await Promise.all(z.slice(Se,Se+4).map(async Ue=>{const ut=He[Ue.path];if(ut)return ut;const Dt=await fr(t,Ue.path);return Tt(ct=>({...ct,[Ue.path]:Dt.sitemaps})),Dt.sitemaps}))).forEach((Ue,ut)=>{ce.push(...Ue.length>0?Ue.map(Dt=>Dt.path):[z[Se+ut].path])});await Vs([...j.filter(Se=>!Se.isSitemapsIndex).map(Se=>Se.path),...ce])}catch(z){Qe(z instanceof Error?z.message:"Failed to load sitemap files"),Zt(!1)}}async function cn(j){nt(!0),Qe(null);try{await Rd(t,"gsc",j),await It(n,"google"),d(z=>z.map(ce=>ce.connectionType==="gsc"?{...ce,sitemapUrl:j}:ce)),Ee({title:"Default sitemap updated",detail:j,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(z){Qe(z instanceof Error?z.message:"Failed to set the default sitemap")}finally{nt(!1)}}async function Jn(j){try{await ln.mutateAsync({projectName:t,projectLabel:t,opts:j?{sitemapUrl:j}:void 0})}catch{}}async function Xn(){be(!0),Qe(null);try{const[j,z]=await Promise.all([r||!a?Promise.resolve(null):ql().catch(()=>null),n.fetchQuery({...Ni({client:H,path:{name:t}}),staleTime:zt}).catch(()=>[])]);i(!!j?.google?.configured),d(z);const ce=z.find(Se=>Se.connectionType==="gsc");await Promise.all([r?Promise.resolve():ka(ce),Ss(),Us(),Bs(),Cn(),!r&&ce?.propertyId?An():Promise.resolve()])}finally{be(!1)}}o.useEffect(()=>{Xn()},[t,s,a]),o.useEffect(()=>{de(0),D(null),re(j=>j.startDate||j.endDate?{...j,startDate:"",endDate:""}:j),P(j=>j+1),Us()},[W]);const Aa=o.useRef(!1);o.useEffect(()=>{if(!Aa.current){Aa.current=!0;return}de(0),jt.setPage(1),Ss(0)},[E]);function Qs(j){const z=se===j?null:j;D(z),re(ce=>({...ce,startDate:z??"",endDate:z??""})),P(ce=>ce+1)}const Zn=o.useRef(!1);o.useEffect(()=>{if(!Zn.current){Zn.current=!0;return}de(0),Ss(0)},[as]);async function Ra(){if(!l){Qe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Re(!0),Qe(null),fs(null);try{let j=function(Me){if(Me.source!==Se||Me.origin!==at||!Me.data||typeof Me.data!="object")return;const Cs=Me.data;Cs.type!==bx||Cs.connectionType!=="gsc"||ct(!0)};const{authUrl:z,redirectUri:ce}=await wd(t,"gsc");if(!z.startsWith("https://accounts.google.com/")){Qe("Unexpected OAuth redirect URL. Please try again.");return}const Se=window.open(z,"_blank","width=600,height=700");if(!Se){window.location.assign(z);return}const at=ce?new URL(ce).origin:window.location.origin;let Ue=!1,ut=null;const Dt=()=>{ut!==null&&window.clearInterval(ut),window.removeEventListener("message",j)},ct=async Me=>{if(!Ue){Ue=!0,Dt(),fs(Me?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await It(n,"google"),await Xn()}finally{fs(null)}}};window.addEventListener("message",j),fs("Finish the Google consent flow in the popup. This page will refresh automatically."),ut=window.setInterval(()=>{Se.closed&&ct(!1)},1e3)}catch(j){Qe(j instanceof Error?j.message:"Failed to start OAuth flow")}finally{Re(!1)}}async function pr(){Qe(null),fs(null);try{await Nd(t,"gsc"),await It(n,"google"),d(j=>j.filter(z=>z.connectionType!=="gsc")),u([]),v("")}catch(j){Qe(j instanceof Error?j.message:"Failed to disconnect")}}async function Pa(){if(f){K(!0),Qe(null);try{await qd(t,"gsc",f),await It(n,"google"),d(j=>j.map(z=>z.connectionType==="gsc"?{...z,propertyId:f}:z)),Ee({title:"GSC property updated",detail:`${t} is now linked to ${f}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(j){Qe(j instanceof Error?j.message:"Failed to save GSC property")}finally{K(!1)}}}async function xr(){Qe(null),fs(null);try{await Ca.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(I,10)||void 0,full:V||void 0}}),await It(n,"gsc")}catch{}}async function Ia(){if(S.trim()){Je(!0),Qe(null),fs(null);try{const j=await Pd(t,S.trim());await It(n,"gsc"),k(j),q(""),await Bs()}catch(j){Qe(j instanceof Error?j.message:"Failed to inspect URL")}finally{Je(!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"})]})}),bt&&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:bt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:bt.message}),(Pn(bt.enableUrl)||Pn(bt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Pn(bt.enableUrl)&&e.jsx("a",{href:Pn(bt.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 ↗"}),Pn(bt.indexingApiUrl)&&e.jsx("a",{href:Pn(bt.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:()=>rs(null),children:"×"})]})}),Xt&&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:[Xt,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Qe(null),children:"×"})]}),Hn&&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:[Hn,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>fs(null),children:"×"})]}),Le?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Et?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:Et.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",pe?.lastInspectedAt?Ht(pe.lastInspectedAt):"never"]}),!r&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Xe(pr),children:"Disconnect"})]}):a?e.jsxs(ve,{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(je,{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(T,{type:"button",variant:"outline",size:"sm",disabled:ee,onClick:Xe(Ra),children:ee?"Opening…":"Connect Google Search Console"}):e.jsx(T,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(qs,{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(ve,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:fx})}),(Et||Vi)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ve,{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(Be,{text:`${jx(m?.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 ${Da.toLocaleString()} matching rows while the table shows ${Ls} per page.`})]}),m?.window?.startDate&&m.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[m.window.startDate," to ",m.window.endDate,(m.window.daysSinceLatestData??0)>0&&` · latest data ${m.window.daysSinceLatestData} day${m.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mr,{windows:yx,value:W,onChange:j=>{B(j),de(0),jt.setPage(1)},label:"Search Console time period",formatOption:j=>j==="all"?"All":j}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:Oe,onClick:()=>{de(0),jt.setPage(1),Ss(0),Us()},children:Oe?"Loading…":"Apply filters"})]})]}),m&&m.daily.length>0&&(()=>{const{totals:j,daily:z,trends:ce,periodComparison:Se}=m,Ue=To.filter(Me=>Q.includes(Me.key)).map(Me=>({dataKey:Me.key,label:Me.label,color:Me.color,axisId:Me.key,inverted:Me.inverted,formatValue:Me.format,trend:O?ce?.[Me.key]??null:null})),ut=Me=>j[Me]??null,Dt=new Map(z.map(Me=>[Me.date,Me])),ct=z.length===0?[]:yd(z[0].date,z[z.length-1].date).map(Me=>Dt.get(Me)??{date:Me});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:To.map(Me=>{const Cs=Q.includes(Me.key),dn=ut(Me.key),Rn=dn===null;return e.jsxs("button",{type:"button","aria-pressed":Cs,disabled:Rn,className:`rounded-md border px-3 py-2 text-left transition-colors ${Cs?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Rn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{te(ys=>ys.includes(Me.key)?ys.length===1?ys:ys.filter(Ta=>Ta!==Me.key):[...ys,Me.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:Cs?Me.color:"transparent",border:`1px solid ${Me.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:Me.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:dn===null?"—":Me.format(dn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:vx(Se,Me.key,Me.inverted)})]},Me.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:O,onChange:Me=>U(Me.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(Zl,{data:ct,xKey:"date",series:Ue,xTickFormatter:Nn,labelFormatter:At,onSelectX:Qs,selectedX:se})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:z.map(Me=>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":se===Me.date,onClick:()=>Qs(Me.date),children:[At(Me.date),": ",Me.clicks," clicks, ",Me.impressions," impressions"]},Me.date))}),se&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",At(se)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Qs(se),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:Y.startDate,onChange:j=>re(z=>({...z,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:Y.endDate,onChange:j=>re(z=>({...z,endDate:j.target.value}))}),e.jsx(Xs,{value:Y.query,onChange:j=>re(z=>({...z,query:j})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Xs,{value:Y.page,onChange:j=>re(z=>({...z,page:j})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),p.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(bn).map(j=>e.jsx("th",{className:"text-right","aria-sort":Ze?.key===j?Ze.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:()=>{jt.setPage(1),Ft(z=>z?.key===j?z.dir==="desc"?{key:j,dir:"asc"}:null:{key:j,dir:"desc"})},children:[bd[j],Ze?.key===j?Ze.dir==="desc"?" ↓":" ↑":""]})},j))]})}),e.jsx("tbody",{children:Pt.map((j,z)=>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(Za,{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:et(j.ctr)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.position.toFixed(1)})]},`${j.date}:${j.query}:${j.page}:${z}`))})]})}),e.jsx(Fs,{page:X?jt.page:Math.floor(ne/Ls)+1,pageSize:Ls,visibleRows:Pt.length,totalRows:X?oe:void 0,hasNextPage:X?void 0:Ce,disabled:Oe,itemLabel:X?"matches":"rows",onPageChange:j=>{if(X){jt.setPage(j);return}const z=(j-1)*Ls;de(z),Ss(z)}}),X&&oe>=Da?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Da.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(ve,{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(Be,{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:[pe&&pe.notIndexed.length>0&&e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:lt,onClick:()=>{Yn()},children:lt?"Requesting…":`Request indexing (${pe.notIndexed.length})`}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:Ve,onClick:()=>{Cn(!0)},children:Ve?"Loading…":"Reload saved coverage"})]})]}),pe&&pe.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const j=pe.summary.indexedShare??0,z=pe.summary.notIndexedShare??0,ce=54,Se=2*Math.PI*ce,at=Se*(1-j),Ue=Se*z,ut=Se*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:ce,fill:"none",stroke:hs.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:zn.positiveDeep,strokeWidth:"14",strokeDasharray:Se,strokeDashoffset:at,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),pe.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:hs.textFaint,strokeWidth:"14",strokeDasharray:`${Ue} ${Se-Ue}`,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:et(pe.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:pe.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:pe.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(pe.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(pe.reasonGroups??[]).length," ",(pe.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),pe.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:pe.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 z=j==="indexed"?pe.indexed.length:j==="notIndexed"?pe.notIndexed.length:pe.deindexed.length,ce=j==="indexed"?"Indexed":j==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":ft===j,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${ft===j?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{xs(j),Jt(null)},children:[ce," (",z,")"]},j)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[ft==="indexed"&&pe.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:yt.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))})]}),ft==="notIndexed"&&!Nt&&(pe.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:(pe.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:()=>Jt(j.reason),onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),Jt(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))})]}),ft==="notIndexed"&&!Nt&&(pe.reasonGroups??[]).length===0&&pe.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:ss.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))})]}),ft==="notIndexed"&&Nt&&(()=>{const j=(pe.reasonGroups??[]).find(z=>z.reason===Nt);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:()=>Jt(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(T,{type:"button",variant:"outline",size:"sm",disabled:lt,onClick:()=>{kn(j.urls.map(z=>z.url))},children:lt?"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:we.map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:z.url}),e.jsx("td",{className:"text-secondary",children:z.crawlTime?z.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:lt,onClick:()=>{kn([z.url])},title:"Request indexing",children:"Index"})})]},z.id))})]})]}):null})(),ft==="deindexed"&&pe.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:L.map((j,z)=>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}-${z}`))})]}),(ft==="indexed"&&pe.indexed.length===0||ft==="notIndexed"&&!Nt&&pe.notIndexed.length===0||ft==="deindexed"&&pe.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Fs,{page:_e,pageSize:zs,visibleRows:Math.min(zs,me.length-mt),totalRows:me.length,onPageChange:_,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":Ns,onClick:()=>Gs(j=>!j),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Ns?"Hide snapshots":Kt.length>0?`View ${Kt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",pe.summary.indexed.toLocaleString()," indexed, ",pe.summary.notIndexed.toLocaleString()," not indexed.",ae&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ae.indexed>=0?"+":"",ae.indexed.toLocaleString()," indexed, ",ae.notIndexed>=0?"+":"",ae.notIndexed.toLocaleString()," not indexed."]})]}),Ns&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:Kt.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:Kt.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:Ve?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),!r&&e.jsxs(e.Fragment,{children:[e.jsxs(ve,{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(Be,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:Wt||!Et?.propertyId,onClick:()=>{An()},children:Wt?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:qt,onChange:j=>vt(j.target.value),onKeyDown:j=>j.key==="Enter"&&void Vs([qt.trim()])}),e.jsx(T,{type:"button",size:"sm",disabled:!ws||$t||!qt.trim(),onClick:()=>{Vs([qt.trim()])},children:$t?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(T,{type:"button",size:"sm",variant:"outline",disabled:!ws||$t||on.length===0,onClick:()=>{Vs(on)},children:$t?"Resubmitting…":Wn}),e.jsx(T,{type:"button",size:"sm",variant:"outline",disabled:!ws||$t||!st?.length,onClick:()=>{Qi()},children:"Resubmit all files"}),St&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",St.indexes," index",St.indexes===1?"":"es",", ",St.files," file",St.files===1?"":"s"]}),Ie&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Ie.completed,"/",Ie.total]})]}),!ws&&Et&&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:Xe(Ra),children:"Reconnect"})]}),st&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:st.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Xs,{value:Z,onChange:j=>{Fe(j),ts.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:ts.rows.flatMap(j=>{const z=Mo(j),ce=qo(j),Se=$o(j),at=He[j.path]??[],Ue=ke.has(j.path),ut=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Za,{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":Ue,"aria-label":`${Ue?"Collapse":"Expand"} files in ${j.path}`,onClick:()=>{hr(j.path)},children:Mt.has(j.path)?"Loading…":`${Ue?"▾":"▸"} Index${He[j.path]?` (${at.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:Se}),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:z.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ce||"—"}),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:!ws||$t,onClick:()=>{Vs([j.path])},children:j.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Et?.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:Yt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{cn(j.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:ln.isPending,onClick:()=>{Jn(j.path)},children:"Inspect URLs"})]})})]},j.path),Dt=j.isSitemapsIndex&&Ue?at.map(ct=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Za,{value:ct.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:$o(ct)}),e.jsx("td",{className:"text-secondary",children:ct.lastSubmitted?ct.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ct.lastDownloaded?ct.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Mo(ct).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:qo(ct)||"—"}),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:!ws||$t,onClick:()=>{Vs([ct.path])},children:"Resubmit"}),Et?.sitemapUrl===ct.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:Yt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{cn(ct.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:ln.isPending,onClick:()=>{Jn(ct.path)},children:"Inspect URLs"})]})})]},`${j.path}:${ct.path}`)):[];return[ut,...Dt]})})]}),e.jsx(Fs,{page:ts.page,pageSize:Ls,visibleRows:ts.rows.length,totalRows:ts.totalRows,onPageChange:ts.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(ve,{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:S,onChange:j=>q(j.target.value),onKeyDown:j=>j.key==="Enter"&&void Ia()}),e.jsx(T,{type:"button",size:"sm",disabled:ze||!Et?.propertyId||!S.trim(),onClick:Xe(Ia),children:ze?"Inspecting…":"Inspect URL"})]}),M&&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:M.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:M.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:Wi(M.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:Ht(M.crawlTime)})]})]})]})]}),e.jsxs(ve,{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(T,{type:"button",variant:"outline",size:"sm",disabled:ye,onClick:()=>{Bs(!0)},children:ye?"Loading…":"Refresh history"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:G,onChange:j=>he(j.target.value)}),e.jsx(T,{type:"button",size:"sm",variant:"outline",disabled:ye,onClick:()=>{Bs(!0)},children:"Apply filter"})]}),x.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:x.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:Wi(j.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Ht(j.inspectedAt)})]},j.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(ve,{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"})]})}),N.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:N.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:Ht(j.transitionDate)})]},`${j.url}:${j.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Et&&!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:()=>js(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 ${vs?"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"})]})}),vs&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(ve,{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(Be,{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:f,disabled:De||h.length===0,onChange:j=>v(j.target.value),children:h.length===0?e.jsx("option",{value:"",children:De?"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(T,{type:"button",size:"sm",variant:"outline",disabled:De,onClick:()=>{ka(Et,!0)},children:De?"Refreshing…":"Refresh properties"}),e.jsx(T,{type:"button",size:"sm",disabled:!f||xe,onClick:Xe(Pa),children:xe?"Saving…":"Save property"})]})]})]}),e.jsxs(ve,{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:I,onChange:j=>w(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:V,onChange:j=>F(j.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(T,{type:"button",size:"sm",disabled:Ca.isPending||!Et.propertyId,onClick:Xe(xr),children:Ca.isPending?"Queueing…":"Queue sync"}),!Et.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const wx=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Sx({projectName:t,projectId:s}){const n=ps(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),h=$e(Ni({client:H,path:{name:t}})),u=h.data?.find(J=>J.connectionType==="gbp"),p=!!u,g=a?{locationName:a}:void 0,m=$e({...$d({client:H,path:{name:t}}),enabled:p}),y=$e({...Ld({client:H,path:{name:t},query:g}),enabled:p}),x=$e({...Ed({client:H,path:{name:t},query:g}),enabled:p}),b=$e({...Dd({client:H,path:{name:t},query:g}),enabled:p}),N=$e({...Od({client:H,path:{name:t},query:g}),enabled:p}),C=$e({...Fd({client:H,path:{name:t},query:g}),enabled:p}),M=$e({queryKey:["gbp-section-insights",t],queryFn:()=>Kd(t),enabled:p});function k(){It(n,"gbp")}const f=Ot({...Gd(),onSuccess:J=>{$l({id:J.runId,projectId:s,kind:Zs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Ee({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=o.useSyncExternalStore(Ll,tr,tr),S=Object.values(v.runs).some(J=>J.kind===Zs["gbp-sync"]&&J.projectId===s),q=f.isPending||S,I=Ot({..._d(),onSuccess:()=>k()});if(o.useEffect(()=>{if(!a||!m.data)return;const J=m.data.locations.filter(oe=>oe.selected);(J.length<=1||!J.some(oe=>oe.locationName===a))&&r(null)},[a,m.data]),o.useEffect(()=>{if(!l||!m.data)return;(a?[a]:m.data.locations.filter(oe=>oe.selected).map(oe=>oe.locationName)).includes(l)||i(null)},[l,m.data,a]),h.isLoading)return null;if(!u){const J=[{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(ve,{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:J.map((oe,Ne)=>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:Ne+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:oe.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:oe.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:oe.note})]})]},oe.title))})]})})}const w=y.data,V=m.data?.locations??[],F=V.filter(J=>J.selected),W=x.data?.keywords??[],B=b.data?.lodging??[],Q=N.data?.placeActions??[],te=C.data?.places??[],O=V.length>0?V[0].accountName:u.domain,U=a?V.find(J=>J.locationName===a)?.displayName??null:null,se=a?V.filter(J=>J.locationName===a):F,D=new Set(se.map(J=>J.locationName)),E=B.filter(J=>D.has(J.locationName)),P=Q.filter(J=>D.has(J.locationName)),Y=te.filter(J=>D.has(J.locationName)),re=new Set(F.map(J=>J.locationName)),ne=a?W:W.filter(J=>re.has(J.locationName)),de=!a&&F.length>1,Ce=(M.data??[]).filter(J=>!J.dismissed&&wx.has(J.type)&&(!U||J.query===U||J.query===a||J.title.startsWith(U)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(ve,{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(Be,{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(je,{tone:"positive",children:"Connected"}),!le()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:q,onClick:()=>f.mutate({client:H,path:{name:t},body:{}}),children:q?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[O?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:O})," · "]}):null,m.data?`${m.data.totalSelected} of ${m.data.totalDiscovered} locations tracked`:"Loading locations…"]}),F.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:J=>r(J.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),F.map(J=>e.jsx("option",{value:J.locationName,children:J.displayName},J.id))]})]}),F.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[Ce.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Ce.map(J=>e.jsx("div",{className:["insight-card",Dx(J.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:[J.title,J.recommendation?.reason&&e.jsx(Be,{text:J.recommendation.reason})]})},J.id))]}),w&&e.jsx(Gx,{performance:w.performance,freshness:w.freshness,timeseries:w.timeseries}),w?.profileCompleteness&&e.jsx(Cx,{summary:w.profileCompleteness}),se.length>0&&e.jsx(kx,{locations:se,lodging:E,places:Y,placeActions:P,expandedLocation:l,onToggleExpanded:J=>{i(oe=>oe===J?null:J)}}),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"}),x.data&&x.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[et(x.data.thresholdedPct,Qn.percent)," privacy-thresholded"]})]}),ne.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"}),de&&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:ne.slice(0,25).map(J=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:J.keyword}),de&&e.jsx("td",{className:"text-muted",children:V.find(oe=>oe.locationName===J.locationName)?.displayName??J.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:J.valueCount!==null?J.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",J.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[J.periodStart,"–",J.periodEnd]})]},`${J.locationName}:${J.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>d(J=>!J),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",V.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:V.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!le()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:V.map(J=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:J.displayName}),e.jsx("td",{className:"text-muted",children:J.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(je,{tone:J.selected?"positive":"neutral",children:J.selected?"Tracked":"Not tracked"})}),!le()&&e.jsx("td",{className:"text-right",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:I.isPending,onClick:()=>I.mutate({client:H,path:{name:t,locationName:J.locationName},body:{selected:!J.selected}}),children:J.selected?"Untrack":"Track"})})]},J.id))})]})})]})]})})}function Cx({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:ta(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:ta(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:ta(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:ta(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:ta(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(Be,{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 ${Ex(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function kx({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:l}){const i=new Map(s.map(h=>[h.locationName,h])),c=new Map(n.map(h=>[h.locationName,h])),d=new Map;for(const h of a){const u=d.get(h.locationName)??[];u.push(h),d.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(Be,{text:le()?"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,p=c.get(h.locationName)??null,g=d.get(h.locationName)??[],m=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(je,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(je,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Nc(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Rx,{location:h})}),e.jsx("td",{children:e.jsx(Px,{lodging:u})}),e.jsx("td",{children:e.jsx(Tx,{place:p,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(qx,{actions:g})}),e.jsx("td",{className:"text-right",children:e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:()=>l(h.locationName),children:m?"Hide":"Details"})})]}),m&&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(Lx,{location:h,lodging:u,place:p,placeActions:g})})})]},h.id)})})]})})]})}function Ax(t){return[{label:"Description",tone:fn(t.description)?"positive":"neutral",value:fn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:fn(t.primaryPhone)?"positive":"neutral",value:fn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:fn(t.websiteUri)?"positive":"neutral",value:fn(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 Rx({location:t}){const s=Ax(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(je,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Px({lodging:t}){return e.jsx(Ri,{...Ix(t)})}function Ix(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 Tx({place:t,mapsUri:s}){return e.jsx(Ri,{...Mx(t,s)})}function Mx(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 qx({actions:t}){return e.jsx(Ri,{...$x(t)})}function $x(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 Ri({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(je,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Lx({location:t,lodging:s,place:n,placeActions:a}){const r=s?Fx(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Ir,{title:"Owner profile · Business Information",children:[e.jsx(Vt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Vt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Vt,{label:"Description",value:fn(t.description)?t.description:"Not returned"}),e.jsx(Vt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Vt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Vt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Vt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Vt,{label:"Open status",value:Nc(t.openStatus)}),e.jsx(Vt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Ir,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Vt,{label:"Last checked",value:Lo(s.syncedAt)}),e.jsx(Vt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Vt,{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(Ir,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Vt,{label:"Places tier",value:n.tier}),e.jsx(Vt,{label:"Last checked",value:Lo(n.syncedAt)}),e.jsx(Vt,{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:[or(l.placeActionType),l.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[or(l.providerType),l.uri?` · ${Ox(l.uri)}`:""]})]},l.placeActionLinkName))})})]})]})}function Ir({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 Vt({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 ta(t,s,n){return t===s?"positive":t===0?n:"caution"}function Ex(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Dx(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function fn(t){return typeof t=="string"&&t.trim().length>0}function Nc(t){return t?or(t):"Not returned"}function or(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Ox(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Lo(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Fx(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Kx(n)).map(([s])=>or(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Kx(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Gx({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Ud.filter(y=>(a[y]??0)>0),l=Bd.filter(y=>(a[y]??0)>0),i=Object.keys(a).filter(y=>(a[y]??0)>0&&Vd(y)==="other").sort((y,x)=>(a[x]??0)-(a[y]??0)),c=Object.keys(a).filter(y=>(a[y]??0)===0).sort(),d=n.map(y=>{const x={date:y.date};for(const[b,N]of Object.entries(y.metrics))x[b]=N;return x}),h=n.find(y=>y.pending)?.date,u=n.length>0?n[n.length-1].date:void 0,p=d.length>0,g=s.dataThroughDate?`Data through ${At(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,m=[...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"}),g&&e.jsx("span",{className:"text-[11px] text-muted",children:g})]}),!p||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(Eo,{data:d,metrics:r,kind:"line",firstPending:h,lastDate:u}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:m.map(y=>e.jsxs("span",{className:"text-sm text-secondary",children:[sr(y)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[y]??0).toLocaleString()})]},y))})]})]}),p&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Eo,{data:d,metrics:l,kind:"area",firstPending:h,lastDate:u})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(y=>sr(y)).join(", ")]})]})}function Eo({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(xa,{stroke:ha,vertical:!1}),e.jsx(sn,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:ms},tickFormatter:Nn,minTickGap:24}),e.jsx(nn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...ns,labelFormatter:At,formatter:(l,i)=>[typeof l=="number"?l.toLocaleString():String(l??0),sr(String(i??""))]}),e.jsx(rr,{wrapperStyle:{fontSize:11,color:hs.text},formatter:l=>sr(l)}),a&&r&&e.jsx(Xr,{x1:a,x2:r,fill:hs.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:hs.textDim,fontSize:10}}),s.map((l,i)=>n==="line"?e.jsx(Ds,{type:"monotone",dataKey:l,stroke:it[i%it.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx(Ys,{type:"monotone",dataKey:l,stackId:"reach",stroke:it[i%it.length],fill:it[i%it.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},l))]})})})}function _x(t){return kh(Bt(String(t)))}function Ux(t){return ba(Bt(String(t)))}function Tr({children:t,label:s="More info",placement:n="top",className:a}){const r=o.useId(),[l,i]=o.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":l?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:e.jsx(Eh,{className:"h-3.5 w-3.5","aria-hidden":!0})}),l&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Oa=Ls;function In(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Mr(t){return t.toLocaleString()}function Bx(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 Vx(t){const s=t.filter(n=>n.kind===Zs["backlink-extract"]&&!El(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Qx(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 zx({projectName:t}){const s=Os(),[n,a]=o.useState(null),[r,l]=o.useState(null),[i,c]=o.useState([]),[d,h]=o.useState(null),[u,p]=o.useState(null),[g,m]=o.useState(null),[y,x]=o.useState(Date.now()),[b,N]=o.useState(0),[C,M]=o.useState(!0),[k,f]=o.useState(!1),[v,S]=o.useState(null),q=o.useCallback(async()=>{M(!0),S(null);try{const[U,se,D,E,P]=await Promise.all([Qd().catch(()=>null),zd(t,{excludeCrawlers:!0}).catch(()=>null),Hd(t,{limit:Oa,offset:b,excludeCrawlers:!0}).catch(re=>{if(re instanceof Gn&&re.code==="NOT_FOUND")return null;throw re}),Wd(t).catch(()=>[]),Yd(t).catch(()=>[])]);h(U),a(se),l(D),c(E);const Y=Vx(P);p(Y)}catch(U){S(U instanceof Error?U.message:"Failed to load backlinks")}finally{M(!1)}},[t,b]);o.useEffect(()=>{q()},[q]),o.useEffect(()=>{if(!u)return;const U=u.id;let se=!1;const D=async()=>{try{const P=await Yr(U);if(se)return;El(P.status)?(p(null),m(P),await q()):p(Y=>Y?.id===P.id?{...Y,...P}:Y)}catch{}},E=window.setInterval(()=>{D()},3e3);return()=>{se=!0,window.clearInterval(E)}},[u,q]),o.useEffect(()=>{if(!u)return;const U=window.setInterval(()=>x(Date.now()),1e3);return()=>window.clearInterval(U)},[u]),o.useEffect(()=>{if(!g||g.status==="failed")return;const U=window.setTimeout(()=>m(null),1e4);return()=>window.clearTimeout(U)},[g]);async function I(){f(!0),S(null);try{const U=await Xd(t);p(U)}catch(U){U instanceof Gn&&U.code==="MISSING_DEPENDENCY"?S("DuckDB is not installed. Visit the Backlinks admin page to install it."):S(U instanceof Error?U.message:"Failed to trigger extract")}finally{f(!1)}}const w=o.useMemo(()=>i.slice().sort((U,se)=>U.queriedAt.localeCompare(se.queriedAt)).map(U=>({date:U.queriedAt,linkingDomains:U.totalLinkingDomains})),[i]),V=r?.rows??[],F=r?.total??0,W=n?.excludedLinkingDomains??0,B=Math.floor(b/Oa)+1;return o.useEffect(()=>{b>0&&b>=F&&N(0)},[b,F]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),v&&e.jsx(ve,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:v})}),u&&e.jsx(ve,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Mh,{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(je,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Qx(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."})]})]})}),g&&!u&&e.jsx(ve,{className:`surface-card p-4 mb-4 ${g.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[g.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(qh,{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 ${g.status==="failed"?"text-negative":"text-positive"}`,children:g.status==="failed"?"Extract failed":"Extract complete"}),g.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Jd(g.error)}):g.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),Q()]});function Q(){return C?e.jsx(ve,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):te()}function te(){const U=n!==null&&n.totalLinkingDomains>0,se=g?.status==="failed",D=n!==null&&n.totalLinkingDomains===0&&!se,E=d?.status==="ready",P=d?.status==="failed",Y=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return U?O(e.jsxs(e.Fragment,{children:[!le()&&!s&&e.jsxs(e.Fragment,{children:[e.jsxs(T,{type:"button",variant:"outline",size:"sm",disabled:k||u!==null,onClick:Xe(I),children:[e.jsx(Lh,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":k?"Queuing…":"Re-run extract"]}),e.jsx(Tr,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!le()&&!s&&e.jsx(T,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"Open admin"})})]})):e.jsx(ve,{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($h,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!d&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!le()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(T,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"Set up backlinks"})})})]}),Y&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",d.status,d.phaseDetail?` — ${d.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!le()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(T,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"View sync status"})})})]}),P&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:d.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!le()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(T,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"Go to Backlinks admin"})})})]}),E&&!Y&&!D&&!se&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:d.release})," is ready. Run an extract for this project."]}),!le()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(T,{type:"button",size:"sm",disabled:k||u!==null,onClick:Xe(I),children:[e.jsx(ar,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":k?"Queuing…":"Run extract"]}),e.jsx(Tr,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),se&&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."}),!le()&&!s&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(T,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"Go to Backlinks admin"})})})]}),D&&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."]}),!le()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(T,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(T,{type:"button",variant:"outline",size:"sm",disabled:k||u!==null,onClick:Xe(I),children:[e.jsx(ar,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":k?"Queuing…":"Re-run extract"]}),e.jsxs(Tr,{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 O(U){if(!n)return null;const se="Linking hosts",D="linking hosts",E="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:Mr(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 ",D]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Mr(n.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",D," 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:et(Number(n.top10HostsShare))})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",D," 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"})," · ",E," ",e.jsx("code",{className:"text-secondary",children:n.release})," · queried ",Bx(n.queriedAt),W>0&&e.jsxs(e.Fragment,{children:[" · ",W," excluded domain",W===1?"":"s"]})]}),w.length>=2&&e.jsxs(ve,{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(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:w,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:it[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:it[0],stopOpacity:0})]})}),e.jsx(sn,{dataKey:"date",tick:Ut,stroke:ms,tickFormatter:_x}),e.jsx(nn,{tick:Ut,stroke:ms,allowDecimals:!1}),e.jsx(an,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:Ux}),e.jsx(Ys,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:it[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(ve,{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:se})]})}),e.jsxs("tbody",{children:[V.map(P=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:P.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Mr(P.numHosts)})]},P.linkingDomain)),V.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:W>0&&F===0?`Every referring domain in this ${E} was a crawler/proxy host (${W} hidden).`:`No referring domains in this ${E}.`})})]})]})}),e.jsx(Fs,{page:B,pageSize:Oa,visibleRows:V.length,totalRows:F,onPageChange:P=>N((P-1)*Oa)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:U})]})}}const Hx=["non-brand","branded","unclassified"],Do={"non-brand":"Non-brand",branded:"Branded",unclassified:"Unclassified"};function Wx(t,s){return s<=0?"neutral":t/s*100>=70?"positive":"caution"}function Yx(t,s){const n=[...new Set(t.byQuery.flatMap(i=>i.providers.map(c=>c.provider)))].sort(),a=new Map,r=i=>{const c=s(i)??"unclassified";let d=a.get(c);return d||(d={key:c,queries:0,unanswered:0,engines:n.map(h=>({provider:h,answered:0,mentioned:0,cited:0})),answers:0,competitorCited:0,competitorGaps:[],citedAndNamed:0,citedNotNamed:0,namedNotCited:0,neither:0},a.set(c,d)),d},l=new Map;for(const i of t.byQuery){const c=r(i.query);if(i.providers.length===0){c.unanswered++;continue}c.queries++;for(const u of i.providers){l.set(`${i.queryId}::${u.provider}`,i.query);const p=c.engines.find(g=>g.provider===u.provider);p.answered++,u.mentioned&&p.mentioned++,u.cited&&p.cited++,c.answers++}const d=i.providers.some(u=>u.cited),h=i.providers.some(u=>u.mentioned);d&&h?c.citedAndNamed++:d?c.citedNotNamed++:h?c.namedNotCited++:c.neither++}for(const i of t.competitorGaps){const c=l.get(`${i.queryId}::${i.provider}`);if(c===void 0)continue;const d=r(c);d.competitorCited++,d.competitorGaps.push({query:c,provider:i.provider,competitors:i.citingCompetitors})}return Hx.map(i=>a.get(i)).filter(i=>i!==void 0&&i.queries>0)}function Jx(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 Xx={engine:"engine no longer configured",query:"query no longer tracked"},Oo={"non-brand":"non-brand queries",branded:"branded queries",unclassified:"unclassified queries"},Zx="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 Tn(t,s,n){return t===1?s:n}function eg({projectName:t,classify:s,hasCompetitors:n,providerScores:a=[]}){const r=o.useId(),[l,i]=o.useState("non-brand"),c=$e({...Zd({client:H,path:{name:t}}),staleTime:wi}),d=c.data??null,h=d?.status==="ready"?Yx(d,s):[],u=h.find(x=>x.key===l)??h.at(0);let p;c.isError?p=e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Could not load engine results: ",Ct(c.error)]}),e.jsx(T,{type:"button",size:"sm",variant:"outline",onClick:()=>{c.refetch()},children:"Retry"})]}):d?d.status==="no-data"?p=e.jsx("p",{className:"text-sm text-secondary",children:d.reason==="no-queries"?"Add queries to start tracking AI citations.":us()?_n:"Engine results appear after the first AI Visibility sweep."}):u||(p=e.jsx("p",{className:"text-sm text-secondary",children:"No engine answers yet."})):p=e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine results…"});const g=[];if(u&&d?.status==="ready"){const x=Tn(u.queries,"query","queries");g.push(e.jsxs(e.Fragment,{children:["Cited and named: ",e.jsxs("strong",{children:[u.citedAndNamed," of ",u.queries]})," ",x]})),g.push(e.jsxs(e.Fragment,{children:["Cited but not named: ",e.jsxs("strong",{children:[u.citedNotNamed," of ",u.queries]})," ",x]})),g.push(e.jsxs(e.Fragment,{children:["Named but not cited: ",e.jsxs("strong",{children:[u.namedNotCited," of ",u.queries]})," ",x]})),g.push(e.jsxs(e.Fragment,{children:["Not cited or named: ",e.jsxs("strong",{children:[u.neither," of ",u.queries]})," ",x]}));for(const M of u.engines)M.answered<u.queries&&g.push(e.jsxs(e.Fragment,{children:[rt(M.provider),": answered ",e.jsxs("strong",{children:[M.answered," of ",u.queries]})," ",x]}));u.unanswered>0&&g.push(e.jsxs(e.Fragment,{children:["No answers yet: ",e.jsx("strong",{children:u.unanswered})," ",Tn(u.unanswered,"query","queries")]}));const{providersCiting:b,providersMentioning:N,providersConfigured:C}=d.summary;g.push(e.jsxs(e.Fragment,{children:["All queries: cited by ",e.jsxs("strong",{children:[b," of ",C]})," ",Tn(C,"engine","engines"),", named by ",e.jsxs("strong",{children:[N," of ",C]})]}));for(const M of a)g.push(e.jsxs(e.Fragment,{children:[rt(M.provider),M.model?` (${M.model})`:""," citation rate:"," ",e.jsx("strong",{children:et(M.score,Qn.percent)}),", ",e.jsxs("strong",{children:[M.cited," of ",M.total]})," ",Tn(M.total,"answer","answers"),", all queries"]}));for(const M of u.competitorGaps)g.push(`"${M.query}" (${rt(M.provider)}): ${M.competitors.join(", ")} cited instead of you`);for(const M of Jx(d))g.push(`"${M.query}" (${rt(M.provider)}): ${M.competitors.join(", ")} cited instead of you, not counted (${Xx[M.reason]})`)}const m=d?.status==="ready"?d.summary.latestRunAt:null,y=(x,b)=>u?.key==="non-brand"?ma[Wx(x,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(Be,{text:Zx})]}),m||u?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[m?e.jsxs("p",{className:"av-card-meta",children:["Latest run ",ur(m)]}):null,h.length>1?e.jsx(da,{label:"Query type",className:"flex-wrap",options:h.map(x=>({value:x.key,label:Do[x.key]})),value:u.key,onChange:i}):u?e.jsx("span",{className:"mention-share-class",children:Do[u.key]}):null]}):null]}),e.jsx("div",{className:"av-card-body",children:p??(u&&e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":`By engine, ${Oo[u.key]}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsxs("th",{scope:"col",children:["Of ",u.queries," ",Tn(u.queries,"query","queries")]}),u.engines.map(x=>e.jsx("th",{scope:"col",children:rt(x.provider)},x.provider))]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Mentioned"}),u.engines.map(x=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(x.mentioned,x.answered)}`,children:x.mentioned})},x.provider))]}),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Cited"}),u.engines.map(x=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(x.cited,x.answered)}`,children:x.cited})},x.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," ",Tn(u.answers,"answer","answers")]}),e.jsxs("span",{className:"sr-only",children:[" · ",Oo[u.key]]})]}):e.jsx("span",{className:"text-[13px] text-secondary",children:"No competitors tracked"})]})]}))}),e.jsx(va,{items:g})]})}const tg={[Ms.queued]:{word:"queued",tone:"text-secondary"},[Ms.running]:{word:"running",tone:"text-info-300"},[Ms.completed]:{word:"completed",tone:"text-secondary"},[Ms.partial]:{word:"partial",tone:"text-caution-400"},[Ms.failed]:{word:"failed",tone:"text-negative-400"},[Ms.cancelled]:{word:"cancelled",tone:"text-secondary"}};function sg({runs:t,collapsed:s=!1}){const n=o.useId(),{openRun:a}=vi(),r=new Set(t.map(c=>c.location??"")).size>1,l=t.some(c=>c.kind!==Zs["answer-visibility"]),i=t.map(c=>`${c.startedAt}: ${c.summary}.${c.statusDetail?` ${c.statusDetail}`:""}`);return e.jsx("section",{className:"overview-brief","aria-labelledby":n,children:e.jsxs("details",{className:"av-history",open:!s||void 0,children:[e.jsxs("summary",{className:"av-card-head",children:[e.jsx("h2",{id:n,className:"av-card-title",children:"Past sweeps"}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t.length>0?e.jsxs("span",{className:"av-card-meta",children:[t.length," recent"]}):null,e.jsx(Un,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"av-card-body",children:t.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No sweeps yet."}):e.jsxs("table",{className:"av-grid av-grid-dense av-grid-sweeps","aria-labelledby":n,children:[e.jsx("thead",{className:"sr-only",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Started"}),l?e.jsx("th",{scope:"col",children:"Type"}):null,e.jsx("th",{scope:"col",children:"Trigger"}),r?e.jsx("th",{scope:"col",children:"Location"}):null,e.jsx("th",{scope:"col",children:"Duration"}),e.jsx("th",{scope:"col",children:"Status"})]})}),e.jsx("tbody",{children:t.map(c=>{const d=tg[c.status],h=c.status===Ms.partial||c.status===Ms.failed;return e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label tabular-nums",children:e.jsx("button",{type:"button",className:"av-link",onClick:()=>a(c.id),"aria-label":`View the ${c.startedAt} sweep`,children:c.startedAt})}),l?e.jsx("td",{className:"text-[13px] text-secondary",children:c.kindLabel}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.triggerLabel}),r?e.jsx("td",{className:"text-[13px] text-secondary",children:c.location??"No location"}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.duration}),e.jsxs("td",{children:[e.jsx("span",{className:`av-status ${d.tone}`,children:d.word}),h&&c.statusDetail?e.jsx("span",{className:"ml-2 text-[13px] text-secondary",children:c.statusDetail}):null]})]},c.id)})})]})}),e.jsx(va,{items:i})]})})}const ng=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],Fo="Measured answers",ag="Close answers",Is={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},rg={"non-brand":"non-brand queries",branded:"branded queries",unknown:"unclassified queries"},ds={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."},sa={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.",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."},ig="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.",lr="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 og(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function wc(t){return t.reason==="identity-ambiguous"?Xl.ambiguous:t.reason==="not-applicable"?"Not applicable":"Not measured"}function wn({value:t}){if(t.rate===null)return e.jsx("span",{className:"text-sm text-secondary",children:wc(t)});const s=ki(t);return e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:et(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator]}),s?e.jsx("span",{className:"text-sm tabular-nums text-secondary",children:s}):null]})}function Ko({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 qr(t,s){if(!t||t.state==="unavailable")return null;const n=t[s];if(n.state==="unavailable")switch(n.reason){case yr["previous-unavailable"]:return{text:ds.previousUnavailable,tone:"text-secondary"};case yr["current-unavailable"]:case yr["not-applicable"]:return null}const{direction:a,magnitude:r}=Ol(n.delta);switch(a){case"up":return{text:ds.up(r),tone:"text-positive"};case"down":return{text:ds.down(r),tone:"text-negative"};case"none":return{text:ds.none,tone:"text-secondary"}}}function Go(t,s){const n=Bt(t);return s!==null&&oo(n)===oo(Bt(s))?Ph(n):ba(n)}function lg(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 cg(t,s){if(!t)return null;if(t.state==="unavailable"){const n=t.previousRun?Go(t.previousRun.createdAt,s):null;switch(t.reason){case un["no-selected-run"]:return null;case un["no-previous-run"]:return ds.noPreviousRun;case un["definition-changed"]:return ds.definitionChanged(n);case un["model-changed"]:return ds.modelChanged(n);case un["legacy-unknown"]:return ds.legacyUnknown;case un["partial-run"]:return ds.partialRun;case un["scoped-run"]:return ds.scopedRun}}return ds.comparedWith(Go(t.previousRun.createdAt,s))}function dg(t,s){const n=`${t.queryCount} ${t.queryCount===1?"query":"queries"} · ${t.answerCount} ${t.answerCount===1?"answer":"answers"}`;return s===null?n:`${n} · ${s}`}function $r({label:t,help:s,value:n,unit:a,classNoun:r,change:l}){const i=e.jsx("span",{className:"sr-only",children:` · ${r}`}),c=ki(n);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(Be,{text:s})]}),n.rate===null?e.jsxs("dd",{className:"text-lg text-secondary",children:[wc(n),i]}):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:et(n.rate)}),i,l?e.jsx("span",{className:`text-sm ${l.tone}`,children:l.text}):null]}),e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:`${n.numerator} of ${n.denominator} ${a}`}),c?e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:c}):null]})]})}const ug={otherQueries:"Other queries"},Fa={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 mg(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(" · ")||ug.otherQueries}return a.sort((r,l)=>r.marketLabel.localeCompare(l.marketLabel)||r.query.localeCompare(l.query))}function _o({value:t,singleAnswer:s}){if(s&&t.denominator===1&&t.unattributed===void 0&&(t.rate===0||t.rate===1)){const n=t.rate===1;return e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm ${n?"text-positive":"text-secondary"}`,children:[n?e.jsx(Oh,{size:16,"aria-hidden":"true"}):e.jsx(Fh,{size:16,"aria-hidden":"true"}),n?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(wn,{value:t}),t.reason==="evidence-incomplete"?e.jsx(Be,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function Uo({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 hg({group:t,queryClass:s,advanced:n,targetLabels:a,marketHeading:r,onViewAnswers:l}){const i=t.rows[0],c=p=>JSON.stringify([...p.targetKeys].sort()),d=t.rows.every(p=>c(p)===c(i)),h=t.rows.every(p=>p.location===i.location),u=p=>p===null?"No location requested":`Requested search location: ${p}`;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(Rl,{showLabel:!0,queryId:i.queryId,sourceSnapshotIds:t.rows.flatMap(p=>p.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&&d?e.jsx(Uo,{targetKeys:i.targetKeys,labels:a}):null,h?e.jsx("span",{children:u(i.location)}):null]})]})}),t.rows.map(p=>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:rt(p.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:p.model??"Model not recorded"}),n&&!d?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(Uo,{targetKeys:p.targetKeys,labels:a})}):null,h?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:u(p.location)}),e.jsx(Pl,{showLabel:!0,showSubjects:n,queryId:p.queryId,sourceSnapshotIds:p.sourceSnapshotIds??[],queryClass:s==="unknown"?null:s,provider:p.provider,model:p.model,location:p.location})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(_o,{value:p.mentionCoverage,singleAnswer:p.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(_o,{value:p.citationCoverage,singleAnswer:p.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(T,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${p.query} · ${p.provider}`,onClick:g=>l(p,g.currentTarget),children:[p.answerCount===1?"View answer":"View answers",e.jsx(ec,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([p.provider,p.model,p.location])))]})}const Bo=[{key:"mentioned",label:"Mentioned",color:it[1],dashed:!1},{key:"cited",label:"Cited",color:zn.positive,dashed:!0}],Vo="var(--chart-tooltip-bg)";function pg({population:t}){const s=o.useId(),[n,a]=o.useState({mentioned:!0,cited:!0}),r=Bo.filter(g=>n[g.key]).map(g=>g.key),l=g=>a(m=>{const y={...m,[g]:!m[g]};return y.mentioned||y.cited?y:m});let i=0;const c=t.trend.map((g,m)=>(m>0&&g.continuity.state!=="comparable"&&(i+=1),{createdAt:Date.parse(g.createdAt),[`mentioned-${i}`]:g.mentionCoverage.rate,[`cited-${i}`]:g.citationCoverage.rate})),d=Array.from({length:i+1},(g,m)=>m),h=new Set(t.trend.slice(1).map(g=>g.continuity.state)),u=[...c.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(g=>g.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[]];if(c.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const p=t.trend.some(g=>g.mentionCoverage.rate!==null||g.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[p?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"}),Bo.map(g=>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[g.key],disabled:n[g.key]&&r.length===1,onChange:()=>l(g.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:g.color,strokeWidth:"2",strokeDasharray:g.dashed?"6 4":void 0}),e.jsx("circle",{cx:"12",cy:"5",r:"3",fill:g.dashed?Vo:g.color,stroke:g.color,strokeWidth:"2"})]}),g.label]},g.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":`${Is[t.queryClass]} mention and citation trend`,children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:c,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(xa,{stroke:ha,vertical:!1}),e.jsx(sn,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Ut,tickLine:!1,axisLine:{stroke:ms},tickFormatter:g=>new Date(Number(g)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(nn,{domain:[0,1],tick:Ut,tickLine:!1,axisLine:!1,width:48,tickFormatter:g=>et(Number(g))}),e.jsx(an,{...ns,formatter:g=>typeof g=="number"?et(g):"Not measured",labelFormatter:g=>new Date(Number(g)).toLocaleDateString()}),d.map(g=>e.jsxs(o.Fragment,{children:[n.mentioned?e.jsx(Ds,{type:"linear",dataKey:`mentioned-${g}`,name:"Mentioned",stroke:it[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:it[1]}}):null,n.cited?e.jsx(Ds,{type:"linear",dataKey:`cited-${g}`,name:"Cited",stroke:zn.positive,strokeWidth:2,strokeDasharray:"6 4",connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:Vo,strokeDasharray:"none"}}):null]},g))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:p?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${Is[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(g=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(g.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(wn,{value:g.mentionCoverage})}),e.jsx("td",{children:e.jsx(wn,{value:g.citationCoverage})}),e.jsx("td",{children:g.continuity.state.replaceAll("-"," ")})]},g.runId))})]})})]})}function di(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function Pi(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=di(a,s)??di(t,s),c=t.populations.find(h=>h.queryClass===i?.queryClass);if(c)return c;const d=["non-brand","branded","unknown"].map(h=>t.populations.find(u=>u.queryClass===h));return d.find(h=>h&&(h.summary.queryCount>0||h.trend.some(u=>u.queryCount>0)))??d.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"},xg={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},gg="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 fg(t,s){return t&&s?kt.dateRange(t.slice(0,4)===s.slice(0,4)?Rh(t):At(t),At(s)):t?kt.dateFrom(At(t)):s?kt.dateThrough(At(s)):null}function yg(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=fg(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(ba(Bt(r.createdAt))):kt.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function Ka(t,s,n){return s===""||t.some(a=>a.value===s)?t:[...t,{value:s,label:n}]}function bg({report:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}){const[l,i]=o.useState(!1),c=o.useRef(null),d=o.useId(),h=`${d}-filters`,{filterOptions:u,selection:p}=t,g=p.measurement,m=Pi(t,s.queryKey,s.answer),y=s.queryClass==="all"?m.queryClass:s.queryClass,x=yg(s,t),b=s.measurementScope==="property"?s.measurementScopeKey:void 0,N=b?r?.({id:b,label:Zr(t.scopeOptions,s)?.label??b}):null,C=s.provider??"",M=s.model??"",k=s.location??"",f=s.measurementRunId??"",v=()=>c.current?.focus(),S=(I,w,V,F,W)=>e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1",children:[e.jsx("label",{htmlFor:`${d}-${w}`,className:"text-sm font-medium text-heading",children:I}),W?e.jsx(Be,{text:W}):null]}),e.jsx("select",{id:`${d}-${w}`,className:lr,value:V,onChange:B=>n({[w]:B.target.value||void 0,measurementQueryKey:void 0}),children:F.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]}),q=(I,w,V,F)=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("label",{htmlFor:`${d}-${w}`,className:"mb-1 block text-sm font-medium text-heading",children:I}),e.jsx("input",{id:`${d}-${w}`,type:"date",className:lr,value:V?.slice(0,10)??"",onChange:W=>n({[w]:W.target.value?`${W.target.value}${F}`: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:gg,value:y,onChange:I=>n({queryClass:I.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(je,{tone:g.state==="measured"?"positive":"neutral",children:g.state==="measured"?"Complete":g.state==="partial"?"Partial":"Not measured"}),g.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:ba(Bt(g.completedAt))}):null]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[e.jsx(T,{ref:c,type:"button",variant:"outline",className:"min-h-11","aria-expanded":l,"aria-controls":h,onClick:()=>i(I=>!I),children:kt.filters(x.length)}),x.map(I=>e.jsxs(T,{type:"button",variant:"outline",className:"visibility-filter-token min-h-11 rounded-md text-sm","aria-label":kt.removeFilter(I.label),onClick:()=>{n(I.patch),v()},children:[e.jsx("span",{className:"min-w-0 truncate",children:I.label}),e.jsx(Dh,{size:16,className:"shrink-0","aria-hidden":"true"})]},I.key)),N,a?e.jsx(T,{type:"button",variant:"outline",className:"min-h-11",onClick:a,children:kt.manageQueries}):null]})]}),e.jsxs("div",{id:h,role:"group","aria-label":kt.panel,hidden:!l,className:"border-b border-default",onKeyDown:I=>{I.key==="Escape"&&(I.target instanceof HTMLElement&&I.target.getAttribute("aria-expanded")==="true"||(i(!1),v()))},children:[e.jsxs("div",{className:"visibility-report-filters",children:[S("Answer engine","measurementProvider",C,Ka([{value:"",label:"All engines"},...u.providers.map(I=>({value:I,label:I}))],C,C)),S("Requested search location","measurementLocation",k,Ka([{value:"",label:"All requested locations"},...u.locations.flatMap(I=>I.kind==="exact"?[{value:I.value,label:I.value}]:I.kind==="none"?[{value:"none",label:kt.noLocation}]:[])],k,k==="none"?kt.noLocation:k)),S("AI model","measurementModel",M,Ka([{value:"",label:"All models"},...Array.from(new Set(u.models.filter(I=>!s.provider||I.provider===s.provider).map(I=>I.model))).map(I=>({value:I,label:I}))],M,M),"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),q("Start date (UTC)","measurementFrom",s.from,"T00:00:00.000Z"),q("End date (UTC)","measurementTo",s.to,"T23:59:59.999Z"),S("Results from","measurementRunId",f,Ka([{value:"",label:"Latest saved sweep"},...[...m.trend].reverse().map(I=>({value:I.runId,label:new Date(I.createdAt).toLocaleString()}))],f,"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(T,{type:"button",variant:"ghost",className:"min-h-11",disabled:x.length===0,onClick:()=>{n({...xg}),v()},children:kt.clearFilters})})]})]})}function vg({report:t,isRefreshing:s=!1,onSelectionChange:n,onPage:a,onSearch:r,search:l="",queryKey:i,answerSelection:c,evidenceReport:d,isEvidenceLoading:h=!1,evidenceError:u,onRetryEvidence:p,onEvidencePage:g}){const m=o.useRef(null),y=o.useRef(void 0),x=o.useRef(null),b=Pi(t,i,c,d),N=d??t,C=N.populations.filter(w=>[...w.queries.items,...w.evidence.items].some(V=>V.queryKey===i)),M=c?[c.queryClass]:(C.length?C:h?[]:[b]).map(w=>w.queryClass),k=i?JSON.stringify([c??i,M]):void 0;o.useEffect(()=>{if(!k){s||(y.current=void 0);return}if(y.current===k)return;const w=m.current?.querySelectorAll(`[aria-label="${Fo}"]`);if(w?.length){for(const V of w){const F=V.closest("details[data-query-results]");F&&(F.open=!0)}w[0].focus({preventScroll:!0}),w[0].scrollIntoView?.({block:"start"}),y.current=k}},[k,s]);const{selection:f}=t,v=og(f.scope),S=new Map(t.scopeOptions.filter(w=>w.kind==="property").map(w=>[w.id,w.label])),q=w=>{const V=N.populations.find(F=>F.queryClass===w.queryClass)?.evidence;return{items:V?.items.filter(F=>F.queryKey===i&&(!c||F.provider===c.provider&&F.model===c.model&&F.location===c.location&&(c.runId===null||F.runId===c.runId)))??[],nextCursor:V?.nextCursor}},I=()=>{y.current=void 0;const w=x.current;w!==null&&w.row.queryKey===i&&(!c||w.row.provider===c.provider&&w.row.model===c.model&&w.row.location===c.location)&&w?.element.isConnected?w.element.focus():m.current?.querySelector(`details[data-query-results="${b.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})};return e.jsxs("section",{ref:m,className:"visibility-report","aria-label":"AI visibility results",children:[f.provenance.kind==="legacy-simple"&&f.queryClass!=="unknown"&&f.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(T,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,[b].map(w=>{const V=mg(w.queries.items,f.scope.kind==="property"&&!f.market&&w.queryClass==="non-brand"?new Map(t.scopeOptions.filter(O=>O.kind==="market").map(O=>[O.id,O.label])):void 0),F=q(w),W=F.items[0]?.query??w.queries.items.find(O=>O.queryKey===i)?.query,B=f.mode==="advanced"&&f.scope.kind!=="property",Q=rg[w.queryClass],te=cg(w.comparison,lg(f,w));return e.jsxs("section",{"aria-label":Is[w.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:Is[w.queryClass]}),e.jsx(Be,{text:w.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":w.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:dg(w.summary,te)}),e.jsx(Be,{text:ds.explanation})]})]}),e.jsxs("dl",{className:"report-headline mt-3","data-columns":B?3:2,"aria-label":`${Is[w.queryClass]} headline results`,children:[e.jsx($r,{label:B?"Answers mentioning a property":"Mentioned answers",help:f.mode==="advanced"?sa.advancedMention:sa.simpleMention,value:w.summary.mentionCoverage,unit:"answers",classNoun:Q,change:qr(w.comparison,"mentionCoverage")}),e.jsx($r,{label:B?"Answers citing a property":"Cited answers",help:f.mode==="advanced"?sa.advancedCitation:sa.simpleCitation,value:w.summary.citationCoverage,unit:"answers",classNoun:Q,change:qr(w.comparison,"citationCoverage")}),B?e.jsx($r,{label:"Properties mentioned",help:sa.propertyReach,value:w.summary.propertyReach,unit:"properties",classNoun:Q,change:qr(w.comparison,"propertyReach")}):null]}),e.jsx(Al,{queryClass:f.queryClass}),e.jsx(pg,{population:w}),B&&(w.breakdown.groups.length>0||w.breakdown.properties.length>0)?e.jsx(jg,{population:w,scope:f.scope,scopeOptions:t.scopeOptions,marketKey:f.market?.id,onSelectionChange:n},`${f.scope.kind}:${f.scope.id}`):null,f.mode==="advanced"?e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Is[w.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:[w.summary.outcomes.total," ",w.summary.outcomes.total===1?"property":"properties"]})]}),e.jsxs("div",{className:"visibility-disclosure-panel flex flex-wrap items-start justify-between gap-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(([O,U])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:w.summary.outcomes[O]}),e.jsx("span",{className:"text-sm text-secondary",children:U})]},O))}),e.jsx(Be,{text:ig})]})]}):null,e.jsxs("details",{className:"visibility-disclosure","data-query-results":w.queryClass,"aria-label":`${Is[w.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:[w.queries.total," ",w.queries.total===1?"result":"results"," · ",v]})]}),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 ${Is[w.queryClass]}`,placeholder:"Search queries",className:`${lr} max-w-sm`,value:l,onChange:O=>r(O.target.value)}):null,e.jsx(Be,{text:f.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":`${Is[w.queryClass]} engine results`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Answer engine"}),e.jsx("th",{scope:"col",children:"Mentioned"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),V.map((O,U)=>e.jsx(hg,{group:O,queryClass:w.queryClass,marketHeading:O.marketLabel!==V[U-1]?.marketLabel?O.marketLabel:void 0,advanced:f.mode==="advanced",targetLabels:S,onViewAnswers:(se,D)=>{x.current={row:se,element:D},n({measurementQueryKey:se.queryKey,measurementAnswer:JSON.stringify({queryKey:se.queryKey,queryClass:w.queryClass,provider:se.provider,model:se.model,location:se.location,runId:f.run.id,revision:f.revision})})}},O.queryKey))]})}),w.queries.items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:"No measured queries match this selection."}):e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:[V.length," ",V.length===1?"query":"queries"," · ",w.queries.items.length," ",w.queries.items.length===1?"engine result":"engine results"," shown of ",w.queries.total," results"]}),w.queries.nextCursor&&a?e.jsx(T,{variant:"outline",onClick:()=>a(w.queries.nextCursor),children:"Next queries"}):null,i&&M.includes(w.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":Fo,"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:W??"Answers"}),e.jsx(T,{variant:"ghost",className:"min-h-11",onClick:I,children:ag})]}),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]}),p?e.jsx(T,{variant:"outline",onClick:p,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[F.items.map(O=>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:O.provider}),O.model?e.jsx("span",{className:"text-[13px] text-secondary",children:O.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:O.location===null?kt.noLocation:kt.location(O.location)}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(O.createdAt).toLocaleDateString()}),e.jsx(je,{tone:"neutral",children:O.mentioned===null?O.mentionUnavailableReason==="identity-ambiguous"?Xl.ambiguous:"Mention not checked":O.mentioned?"Mentioned":"Not mentioned"}),e.jsx(je,{tone:"neutral",children:O.cited===null?"Citation not checked":O.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Ci,{headingLevel:4,copyable:!!O.answerText?.trim(),children:O.answerText??"Answer text unavailable."})}),O.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:[wh," (",O.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:O.sources.map(U=>e.jsx("li",{className:"min-w-0",children:e.jsx(ji,{url:U})},U))})]}):null]},O.answerId)),q(w).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:q(w).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,q(w).nextCursor&&g?e.jsx(T,{variant:"outline",onClick:()=>g(q(w).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Is[w.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:w.competitorAvailability.state==="unavailable"?"Not available":`${w.competitors.length} measured`})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[w.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):w.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:w.competitors.map(O=>e.jsxs("tr",{children:[e.jsx("td",{children:O.domain}),e.jsx("td",{children:e.jsx(wn,{value:O.mentionCoverage})}),e.jsx("td",{children:e.jsx(wn,{value:O.citationCoverage})})]},O.domain))})]})}),w.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:w.observedCompetitors.map(O=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:O.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[O.answerCount," ",O.answerCount===1?"answer":"answers"]})]},O.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},w.queryClass)})]})}function jg({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const l=new Map(n.filter(p=>p.kind==="group").map(p=>[p.id,p])),i=[...l.values()].some(p=>p.parentGroupIds?.length),c=t.breakdown.groups.filter(p=>{const g=l.get(p.id)?.parentGroupIds??[];return s.kind==="project"?g.length===0:s.kind==="group"&&i?g.includes(s.id):!0}),[d,h]=o.useState(()=>s.kind==="project"&&c.length>0?"groups":"properties"),u=jn({rows:d==="groups"?c:t.breakdown.properties,getSearchText:p=>p.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(p=>e.jsx(T,{variant:d===p?"secondary":"ghost",onClick:()=>{h(p),u.setPage(1)},children:p==="groups"?"Groups":"Properties"},p))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:u.query,onChange:p=>u.setQuery(p.target.value),className:`${lr} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:d==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:u.rows.map(p=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("button",{className:"min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>r({measurementScope:d==="groups"?"group":"property",measurementScopeKey:p.id,measurementMarketKey:a}),children:p.label})}),e.jsx("td",{children:p.queryCount}),e.jsxs("td",{children:[e.jsx(wn,{value:p.mentionCoverage}),e.jsx(Ko,{value:p.mentionCoverage})]}),e.jsxs("td",{children:[e.jsx(wn,{value:p.citationCoverage}),e.jsx(Ko,{value:p.citationCoverage})]})]},p.id))})]})}),u.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",d," match this search."]}):null,e.jsx(Fs,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:d,onPageChange:u.setPage})]})}function Sc(t,s,{enabled:n}){return $e({...Xa({client:H,path:{name:t},query:Jr(s)}),enabled:n,staleTime:Dl,retry:!1,placeholderData:yi})}function Cc(t,s){return s&&t.selection.mode==="simple"&&t.selection.measurement.state==="not-measured"}function Ng({projectName:t,selection:s,onSelectionChange:n,fallback:a,showUnmeasuredFallback:r=!1}){const[l,i]=o.useState(),[c,d]=o.useState(""),[h,u]=o.useState(),p=ps(),g=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]),m=$e({...Xa({client:H,path:{name:t},query:{...Jr(s),cursor:l,search:c||void 0}}),staleTime:Dl,retry:!1,placeholderData:yi}),y={...g,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??m.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??m.data?.selection.revision??s.revision,limit:50},x=JSON.stringify(y),b=$e({...Xa({client:H,path:{name:t},query:{...y,cursor:h?.selection===x?h.cursor:void 0}}),enabled:!!s.queryKey&&!!m.data&&!m.isPlaceholderData,retry:!1});if(o.useEffect(()=>{if(s.queryClass!=="all"||!m.data||m.isPlaceholderData||m.isFetching||m.isError||m.data.selection.availability.state==="unsupported"||m.data.populations.length===0||s.queryKey&&!s.answer&&!di(m.data,s.queryKey)&&!b.data)return;const N=Pi(m.data,s.queryKey,s.answer,b.data);if(!l&&!c){const{queryKey:C}=Xa({client:H,path:{name:t},query:Jr({...s,queryClass:N.queryClass})});p.setQueryData(C,{...m.data,selection:{...m.data.selection,queryClass:N.queryClass},populations:[N]},{updatedAt:m.dataUpdatedAt})}n({queryClass:N.queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}},{replace:!0})},[s.queryClass,s.queryKey,s.answer,m.data,m.dataUpdatedAt,m.isPlaceholderData,m.isFetching,m.isError,b.data,n,p,t,g,l,c]),m.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:a});if(m.data&&Cc(m.data,r))return e.jsx(e.Fragment,{children:a});if(m.error){const N=Kl(Gl(m.error)),C=N?.reason===su["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:C?Fa.retiredMarket:N?Fa.retiredScope:nr(m.error)}),C?e.jsx(T,{variant:"outline",onClick:()=>{i(void 0),n({measurementMarketKey:void 0})},children:Fa.showAllMarkets}):N?e.jsx(T,{variant:"outline",onClick:()=>{i(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:Fa.showWholeSite}):e.jsx(T,{variant:"outline",onClick:()=>{i(void 0),m.refetch()},children:"Retry"})]})}return m.data?e.jsx("div",{"aria-busy":m.isFetching,children:e.jsx(vg,{report:m.data,isRefreshing:m.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:b.data,isEvidenceLoading:b.isFetching||!!s.queryKey&&b.isPending,evidenceError:b.error?nr(b.error):void 0,onRetryEvidence:()=>{b.refetch()},onEvidencePage:b.isFetching?void 0:N=>u({selection:x,cursor:N}),search:c,onSearch:N=>{d(N),i(void 0)},onPage:m.isFetching?void 0:i,onSelectionChange:N=>{(!("measurementQueryKey"in N)||Object.keys(N).some(C=>C!=="measurementQueryKey"&&C!=="measurementAnswer"))&&i(void 0),u(void 0),n(N)}})}):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 wg({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,fallback:l,showUnmeasuredFallback:i=!1}){const c=Sc(t,s,{enabled:!0}),d=c.error?void 0:c.data,h=!c.isPlaceholderData&&d?.selection.availability.state==="available"?d.selection.run.id:null;return tu(h,d?.selection.revision),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsx(Fl,{})}),d&&d.selection.availability.state==="available"&&!Cc(d,i)?e.jsx(bg,{report:d,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}):null,e.jsx(Ng,{projectName:t,selection:s,onSelectionChange:n,fallback:l,showUnmeasuredFallback:i},`${t}:${JSON.stringify({...s,queryKey:void 0,answer:void 0})}`)]})}const Sg=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Cg=[{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."}],Ii=it[2],kg=it[4],Ag="var(--chart-tooltip-bg)",Rg={up:"text-positive-400",down:"text-negative-400",none:"text-muted"};function kc({direction:t,magnitude:s}){switch(t){case"up":return`up ${s} points`;case"down":return`down ${s} points`;case"none":return"no change"}}function Pg(t){return t.direction==="none"?"no change over the period":`${kc(t)} over the period`}function Ig(t){return t===ja||t===Na||t===Ks}function Ac(t){return t===ja?"Cited":t===Na?"Mentioned":t===Ks?"Mention share":rt(t)}function ra(t,s){return t===ja?zn.positive:t===Na?it[1]:t===Ks?Ii:Ah(fa(t),s)}function Ti(t){return t==="non-brand"?"non-brand answers":"all answers"}function ui(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function Mi(t,s){return t==="mentionShare"?`Mention share in ${Ti(s)}`:ui(t)}function Tg(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 Rc(t){return t==="cited"?"citationRate":"mentionRate"}function qi(t,s){return s==="cited"?t.cited:t.mentionedCount}function Pc(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 Mg(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 qg(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Ic(t){const s=lc(t);return s===null?[]:Object.entries(s).sort(([n],[a])=>fa(n).localeCompare(fa(a))).map(([n,a])=>`${rt(n)}: ${ya(a)}`)}function Tc(t,s){return new Date(t).toDateString()===new Date(s).toDateString()}function Qo(t){return`${t} ${t===1?"query":"queries"}`}function $i(t){const{added:s,removed:n}=t;return[...s.length>0?[`${Qo(s.length)} added`]:[],...n.length>0?[`${s.length>0?n.length:Qo(n.length)} removed`]:[]].join(", ")}function Mc(t,s){const n=$s(t),a=wa(t),r=hc(t,s);if(!n||!a||!r)return null;const l=Gp(r.moves),i=Tc(n.start,n.end),c=d=>ur(d,i?n.start:null);return n.sweepCount===2?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes the ",e.jsx("strong",{children:c(n.start)})," sweep and the ",e.jsx("strong",{children:c(n.end)})," sweep, with ",l," between them"]}):r.moves.added.length+r.moves.removed.length>0?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes sweeps with ",l," between them"]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point pools ",e.jsx("strong",{children:n.sweepCount})," sweeps, with ",l," between the first and last"]})}function $g(t,s,n){const a=Mc(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?", ":"",$i(r)," ",e.jsx("strong",{children:ga(Bt(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 zo(t){return t.replace(/ /g," ")}function cr({state:t,from:s=!1}){return e.jsx("span",{className:s?"av-model av-model-from":"av-model",children:ya(t)})}function Lg(t,s){return t.reroute?"Same preset, answered with a different model.":ir(t.provider,t.to)?t.served?`Preset picks its own model. Answered with ${ya(t.served.to)} (was ${ya(t.served.from)}).`:s&&s.length>0?`Preset picks its own model. Answered with ${s.join(", ")}.`:"Preset picks its own model.":null}function Eg({buckets:t,queryChanges:s,modelRows:n,served:a,pointerNotices:r,truncated:l,incompleteHistory:i,queryName:c,sweepTimes:d}){const h=t.at(-1),u=f=>ga(f),p=new Map;for(const[f,v]of r){const S=n.find(q=>q.provider===f&&!q.reroute&&q.to.status==="known"&&v.modelIds.includes(q.to.model));S&&p.set(f,S)}const g=[];s.length>0&&g.push({key:"queries",label:"Queries",rows:s.map(f=>({key:`queries-${f.at}`,at:f.at,onOrBefore:!1,from:null,to:e.jsx("span",{className:"text-strong",children:$i(f)}),toHelp:null}))});const m=[...new Set(n.map(f=>f.provider))].sort((f,v)=>rt(f).localeCompare(rt(v)));for(const f of m){const S=a[f]?.latestServedModelIds??null,q=n.filter(I=>I.provider===f);g.push({key:f,label:rt(f),rows:q.map((I,w)=>{const V=p.get(f)===I?r.get(f).text:null,F=[Lg(I,w===0?S:null),V].filter(Boolean).join(" ");return{key:`${f}-${I.at}-${I.reroute?"served":"set"}`,at:I.at,onOrBefore:I.onOrBefore,from:e.jsx(cr,{state:I.from,from:!0}),to:e.jsx(cr,{state:I.to}),toHelp:F||null}})})}const y=g.reduce((f,v)=>f+v.rows.length,0),x=[];for(const f of s)f.added.length>0&&x.push(e.jsxs(e.Fragment,{children:["Added ",e.jsx("strong",{children:u(f.at)}),": ",f.added.map(c).join(", ")]})),f.removed.length>0&&x.push(e.jsxs(e.Fragment,{children:["Removed ",e.jsx("strong",{children:u(f.at)}),": ",f.removed.map(c).join(", ")]}));const b=h?wa(h):null;for(const[f,v]of Object.entries(h?lc(h)??{}:{}).sort(([S],[q])=>S.localeCompare(q)))v.status==="mixed"&&b&&x.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:b})," point mixes ",rt(f)," models: ",wp(v)]}));const N=new Map;for(const f of n.filter(v=>v.onOrBefore)){const v=f.anchorAt?u(f.anchorAt):"";N.set(v,[...new Set([...N.get(v)??[],rt(f.provider)])])}for(const[f,v]of N)x.push(f?e.jsxs(e.Fragment,{children:["Changed before this date range, after the ",e.jsx("strong",{children:f})," sweep: ",ua(v)]}):`Changed before this date range: ${ua(v)}`);for(const f of l)x.push(`${rt(f.provider)}: most recent ${f.shown} of ${f.total} changes`);for(const f of i)x.push(`${rt(f)}: may be missing older changes`);for(const[f,v]of r)p.has(f)||x.push(e.jsxs("span",{className:"inline-flex items-center gap-1",children:[rt(f),": no model updates on record",e.jsx(Be,{text:v.text})]}));if(y===0&&x.length===0)return null;for(const[f,v]of Object.entries(a).sort(([S],[q])=>rt(S).localeCompare(rt(q)))){const S=v.latestServedModelIds??[],q=S.length>0?S.join(", "):ya(v.latestObservation.state);x.push(e.jsxs(e.Fragment,{children:[rt(f)," last answered with ",e.jsx("strong",{children:q})," on ",e.jsx("strong",{children:u(Bt(v.latestObservation.observedAt))})]}))}const C=g.flatMap(f=>f.rows.map(v=>v.at));let M="First sweep on the new model or query set.";if(C.length>0){const f=u(C.reduce((V,F)=>Date.parse(F)>Date.parse(V)?F:V)),v=[...new Set(C.filter(V=>u(V)===f))].sort(),S=v.map(V=>ur(V,V));M+=` ${f} = the ${ua(S)} ${S.length===1?"sweep":"sweeps"}.`;const q=n.flatMap(V=>V.anchorAt?[V.anchorAt]:[]),I=q.length>0?q.reduce((V,F)=>Date.parse(F)>Date.parse(V)?F:V):null,w=Dp(v[0],d,t,I);w&&(M+=` Sweep before: ${u(w)}.`)}const k=Ep({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:k}),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(Be,{text:M})]})}),e.jsx("th",{scope:"col",children:"From"}),e.jsx("th",{scope:"col",children:"To"})]})}),g.map(f=>e.jsx("tbody",{children:f.rows.map((v,S)=>e.jsxs("tr",{children:[S===0?e.jsx("th",{scope:"row",className:"av-engine",children:f.label}):e.jsx("td",{className:"av-engine",children:e.jsx("span",{className:"sr-only",children:f.label})}),e.jsx("td",{className:"av-date",children:v.onOrBefore?`on or before ${zo(u(v.at))}`:zo(u(v.at))}),v.from===null?null:e.jsx("td",{children:v.from}),e.jsx("td",{colSpan:v.from===null?2:void 0,children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[v.to,v.toHelp?e.jsx(Be,{text:v.toHelp}):null]})})]},v.key))},f.key))]})}),e.jsx(va,{items:x})]}):e.jsx("ul",{className:"av-details-list",children:x.map((f,v)=>e.jsx("li",{children:f},v))})})]})}function Dg({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:rt(s)}),e.jsxs("span",{className:"text-secondary",children:["selected ",e.jsx(cr,{state:n.configured})," · answered ",e.jsx(cr,{state:n.served})]}),e.jsx("span",{className:"av-status text-caution-400",children:"substituted"})]},s))})}function Og({active:t,label:s,payload:n,metric:a,mode:r,buckets:l,basketChanges:i}){if(!t)return null;const c=qg(l,s);if(!c)return null;const d=$s(c),h=d!==null&&Tc(d.start,d.end)?d.start:null,u=uc(c,i),p=Ic(c),g=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-tooltip-label",children:Ai(c)}),u.map(x=>e.jsxs("p",{className:"trend-tooltip-detail trend-tooltip-note",children:[$i(x)," ",ur(x.at,h)]},x.at))]}),m=p.length>0&&e.jsx("p",{className:"trend-tooltip-detail trend-tooltip-models",children:p.map((x,b)=>e.jsxs(o.Fragment,{children:[b>0?"; ":"",e.jsx("span",{className:"whitespace-nowrap",children:x})]},b))});if(a==="mentionShare"){const x=c.mentionShare.projectMentionSnapshots,b=c.mentionShare.competitorMentionSnapshots,N=x+b;return e.jsxs("div",{className:"trend-tooltip",children:[g,e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:Ii},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Mi("mentionShare",c.mentionShare.scope)}),e.jsx("span",{className:"trend-tooltip-value",children:et(c.mentionShare.rate)})]}),e.jsx("p",{className:"trend-tooltip-detail",children:N>0?`You ${x} of ${N} tracked-brand mentions. Competitors ${b}.`:"No tracked-brand mentions in this point"}),m]})}const y=r==="byProvider"?(n??[]).filter(x=>x.dataKey!==void 0):[{dataKey:a==="cited"?ja:Na}];return e.jsxs("div",{className:"trend-tooltip",children:[g,y.map((x,b)=>{const N=String(x.dataKey??x.name??""),C=r==="byProvider"?Pc(c,N,a):null,M=C?.count??qi(c,a),k=C?.total??c.total,f=C?C.rate:c[Rc(a)],v=x.color??ra(N,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:v},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Ac(N)}),e.jsx("span",{className:"trend-tooltip-value",children:et(f)}),e.jsxs("span",{className:"trend-tooltip-count",children:[M," of ",k]})]})},`${N}-${b}`)}),m]})}function Fg({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:[Mi(s,r)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Point"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(l=>{let i;if(s==="mentionShare"){const d=l.mentionShare.projectMentionSnapshots,h=l.mentionShare.competitorMentionSnapshots,u=d+h,p=Ti(l.mentionShare.scope);i=u>0?`${et(l.mentionShare.rate)} mention share in ${p}, ${d} of ${u} tracked-brand mentions were you`:`mention share undefined in ${p}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(d=>{const h=Pc(l,d,s);return h?`${rt(d)} ${et(h.rate)} ${ui(s).toLowerCase()}, ${h.count} of ${h.total} answers`:`${rt(d)} no data`}).join("; "):i=`${et(l[Rc(s)])} ${ui(s).toLowerCase()}, ${qi(l,s)} of ${l.total} answers`;const c=Ic(l);return c.length>0&&(i+=`; models: ${c.join("; ")}`),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Ai(l)}),e.jsx("td",{children:i})]},l.startDate)})})]})})}function Kg({projectName:t,competitorDomains:s=[],analyticsRevision:n="none",queryTexts:a=[],classifyQuery:r,sweepTimes:l=[]}){const[i,c]=o.useState("all"),[d,h]=o.useState("mentioned"),[u,p]=o.useState("byProvider"),g=o.useId(),m=o.useMemo(()=>gp(s),[s]),y=$e({queryKey:["analytics-metrics",t,i,m,n],queryFn:()=>eu(t,i),staleTime:wi}),x=y.data??null,b=y.error,N=d==="mentionShare"?"overall":u,C=o.useMemo(()=>x?Rp(x,d,N):null,[x,d,N]),M=x?bp(x):null,k=o.useMemo(()=>Cp(M??{}),[M]),f=o.useMemo(()=>kp(M??{}),[M]),v=o.useMemo(()=>Object.entries(M??{}).filter(([,ee])=>ee.anchorUnavailable).map(([ee])=>ee).sort(),[M]),S=o.useMemo(()=>x?vp(x):{},[x]),q=o.useMemo(()=>x?Mp(jp(x)):[],[x]),I=o.useMemo(()=>x?dc(x):[],[x]),w=o.useMemo(()=>x?qp(x):[],[x]),V=o.useMemo(()=>Lp(M??{},S),[M,S]),F=o.useMemo(()=>x?Np(x):{},[x]),W=o.useMemo(()=>Ji(F,{engineName:rt}),[F]),B=o.useMemo(()=>{const ee=new Map;for(const[Re,De]of Object.entries(F).sort(([qe],[xe])=>qe.localeCompare(xe))){const qe=Ji({[Re]:De},{engineName:rt});qe?.kind==="no-known-change"&&ee.set(Re,{text:`${qe.text} ${qe.detail}`,modelIds:De.modelIds??[]})}return ee},[F]),Q=o.useMemo(()=>{const ee=new Map(a.map(Re=>[Kn(Re),Re]));return Re=>ee.get(Kn(Re))??Re},[a]),te=d!=="mentionShare"&&N==="byProvider",O=x?.buckets??[],U=O[O.length-1]?.mentionShare.scope??x?.mentionShareScope??"pooled",se=Mi(d,U),D=te?hs.textDim:d==="cited"?zn.positive:d==="mentionShare"?Ii:it[1],E=o.useMemo(()=>{const ee=new Map(O.map(Re=>[Re.startDate,xp(Re)]));return Re=>ee.get(String(Re))??""},[O]),P=d==="mentionShare"?O.filter(ee=>typeof ee.mentionShare.rate=="number"&&Number.isFinite(ee.mentionShare.rate)):O,Y=P.at(-1),ne=(x?Pp(x,d):[]).at(-1)??null,de=x?Ip(x,d):null,Ce=Kp(P,I),J=xo(Ce,d,U,r),oe=ne!==null&&de!==null?Ol(de.delta):null,Ne=oe!==null&&!J,X=s.length,ie=[];if(Y&&de!==null&&Ce&&!J&&ie.push($g(Ce,Y,I)),Y&&P.length===1){const ee=Mc(Y,I);ee&&!xo(hc(Y,I),d,U,r)&&ie.push(ee)}if(oe!==null&&P[0]){const ee=wa(P[0]);ee&&ie.push(e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:ee})," point"]}))}te&&ne!==null&&ie.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:et(ne)})," pools all answers; not an average of engines"]}));const G=[...new Set([...k.buckets.map(ee=>ee.bucketStartDate),...O.filter(ee=>uc(ee,I).length>0).map(ee=>ee.startDate)])].sort(),he=ne!==null&&Y&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:D},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:se}),e.jsx("span",{className:"visibility-trend-current-value",children:et(ne)}),oe!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${Ne?"text-muted":Rg[oe.direction]}`,children:[kc(oe),Ne?" (not the same queries)":""]}),e.jsxs("span",{className:"visibility-trend-current-detail",children:["· ",Mg(Y,d)]})]}),Le=e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(da,{options:Cg,value:d,onChange:h,label:"Metric",className:"visibility-trend-metric-control"}),d!=="mentionShare"&&e.jsx(da,{options:Sg,value:u,onChange:p,label:"Series"}),e.jsx(da,{options:ng,value:i,onChange:c,label:"Time window",className:"sm:ml-auto"})]});let be;if(b)be=e.jsx("p",{className:"text-sm text-negative-400",children:nr(b)});else if(y.isLoading&&!x)be=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(d==="mentionShare"&&X===0)be=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!x||!C)be=null;else{const{rows:ee,series:Re,hasData:De}=C;if(!De)be=e.jsx("p",{className:"text-sm text-secondary",children:d==="mentionShare"?`No answer-text brand mentions for you or tracked competitors in ${Ti(U)} in this window yet.`:us()?_n:"Run a sweep to start tracking citations and mentions over time."});else if(te&&Re.length===0)be=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 qe=`${se} rate across ${ee.length} ${ee.length===1?"sweep":"sweeps"}. Latest ${et(ne)}${oe!==null?`, ${Pg(oe)}${Ne?", not the same queries":""}`:""}.`;be=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:qe}),e.jsx(Fg,{buckets:O,metric:d,mode:N,series:Re,mentionShareScope:U}),te&&Re.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:Re.map((xe,K)=>{const Oe=Tp(x,xe,d);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:ra(xe,K)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:Ac(xe)}),Oe!==null&&e.jsx("span",{className:"trend-legend-value",children:et(Oe)})]},xe)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${se} trend chart over ${ee.length} ${ee.length===1?"point":"points"}`,children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:ee,margin:{top:8,right:20,bottom:0,left:0},children:[e.jsx(xa,{stroke:ha,vertical:!1}),e.jsx(sn,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:ms},tickFormatter:E,minTickGap:24}),e.jsx(nn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:xe=>et(xe,Qn.percent),tick:Ut,tickLine:!1,axisLine:!1,width:40}),e.jsx(an,{cursor:{stroke:ms,strokeWidth:1},content:e.jsx(Og,{metric:d,mode:N,buckets:O,basketChanges:I})}),G.map(xe=>e.jsx(zh,{x:xe,stroke:kg,strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`setup-change-${xe}`)),Re.map((xe,K)=>e.jsx(Ds,{type:"monotone",dataKey:xe,name:xe,stroke:ra(xe,K),strokeDasharray:xe===Ks?"5 4":void 0,strokeWidth:Ig(xe)?2.5:2,dot:xe===Ks?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:ra(xe,K),strokeWidth:1.5}:{r:2.5,fill:ra(xe,K),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Ag},connectNulls:xe!==Ks,isAnimationActive:!1},xe))]})})}),G.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(Be,{text:Tg(U)})]}),Y?e.jsx("p",{className:"av-card-meta",children:Ai(Y)}):null]}),e.jsxs("div",{className:"visibility-trend-body",children:[W?.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:W.text}),he,Le,be]}),e.jsx(va,{items:ie})]}),x&&!b?e.jsxs(e.Fragment,{children:[e.jsx(Eg,{buckets:O,queryChanges:w,modelRows:V,served:S,pointerNotices:B,truncated:f,incompleteHistory:v,queryName:Q,sweepTimes:l}),e.jsx(Dg,{substitutions:q})]}):null]})}const Ho=new Set([ca.queued,ca.running]),_t={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 Wo({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d=[],viewerResearchConfig:h=null}){const u=ps(),{account:p,canWrite:g}=Sn(),m=p?.role==="viewer"&&h!==null,y=!g,x=Os(),[b,N]=o.useState(""),[C,M]=o.useState(""),[k,f]=o.useState(null),[v,S]=o.useState([]),q=o.useRef(null),I=o.useRef(!1),[w,V]=o.useState(0),F=$e({...nu({client:H,path:{name:t}}),staleTime:6e4}),W=$e({...au({client:H}),enabled:!y&&!x,staleTime:6e4}),B={client:H,path:{name:t},query:{limit:20}},Q=kl({...ru(B),initialData:void 0,initialPageParam:B,getNextPageParam:G=>G.nextCursor?{path:B.path,query:{...B.query,cursor:G.nextCursor}}:void 0,refetchInterval:G=>G.state.data?.pages.some(he=>he.runs.some(Le=>Ho.has(Le.status)))?3e3:!1}),te=Q.isError&&!Q.isFetchNextPageError,O=Q.data?.pages.at(-1),U=te?[]:[...new Map((Q.data?.pages.flatMap(G=>G.runs)??[]).map(G=>[G.id,G])).values()],se=O?.access?.canRun??(g||m),D=O?.access?O.access.dailyRunLimit:m?h.viewerDailyRunLimit:null;o.useEffect(()=>{!k&&U[0]&&f(U[0].id)},[U,k]);const E=U.find(G=>G.id===k)??null,P=$e({...iu({client:H,path:{name:t,runId:k??""}}),enabled:!te&&!!k,refetchInterval:E&&Ho.has(E.status)?3e3:!1}),Y=te||P.isError?null:P.data??null,re=F.data?.locations??[],ne=o.useMemo(()=>{if(y)return(O?.providers??[]).map(he=>({...he,catalog:he}));const G=new Map((W.data?.providerCatalog??[]).map(he=>[he.name,he]));return(W.data?.providers??[]).filter(he=>he.configured&&G.get(he.name)?.mode==="api").map(he=>({...he,catalog:{...G.get(he.name),defaultModel:he.model||G.get(he.name).defaultModel}}))},[y,O?.providers,W.data]),de=!(y?Q.isPending:W.isPending)&&ne.length===0,Ce=ne.find(G=>G.name===b)??null;o.useEffect(()=>{if(!b&&F.data&&!F.isError&&!W.isError){const G=F.data.providers.find(he=>ne.some(Le=>Le.name===he));N(G??ne[0]?.name??"")}},[b,ne,F.data,F.isError,W.isError]);const J=Ce?.catalog.modelConfigurable??!1,oe=y?Ce?.catalog.defaultModel:(Ce?F.data?.providerModels[Ce.name]:"")||Ce?.catalog.defaultModel,Ne=(J?C.trim():"")||oe,X=Ce?[...new Map([{id:Ce.catalog.defaultModel,displayName:Ce.catalog.defaultModel},...C.trim()?[{id:C.trim(),displayName:C.trim()}]:[],...Ce.catalog.knownModels].map(G=>[G.id,G])).values()]:[],ie=Ot({...ou(),onSuccess:async G=>{q.current=null,V(he=>he+1),S(G.runs),f(G.runs[0]?.id??null),await Yg(u),Ee({title:"Research batch saved",detail:`${G.runs.length} ${G.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${G.runs.map(he=>he.id).join(":")}`,dedupeMode:"replace"})},onError:G=>{Ee({title:"Could not start research",detail:G instanceof Error?G.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{I.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[x?e.jsx(ve,{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(Gg,{projectName:t,canWrite:g,researchAllowed:se&&!te,limitedAccess:y,isEmbed:le(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d,locations:re,defaultLocation:F.data?.defaultLocation??null,providerOptions:ne,provider:b,onProviderChange:G=>{N(G),M("")},resolvedModel:Ne,visibilityModel:oe,configurableModel:J,model:C,onModelChange:M,modelOptions:X,settingsReady:y?!Q.isPending&&!te:!W.isPending&&!W.isError&&!W.isFetching,projectReady:!F.isPending&&!F.isError&&!F.isFetching,isPending:ie.isPending,errorMessage:ie.isError?"The request could not be confirmed.":void 0,onSubmit:(G,he)=>{!se||te||le()||I.current||(q.current?.fingerprint!==he&&(q.current={fingerprint:he,key:crypto.randomUUID()}),I.current=!0,ie.mutate({client:H,path:{name:t},body:{...G,idempotencyKey:q.current.key}}))}},`${t}:${w}`),D!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",D," destination runs per project per day."]}),!y&&W.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(T,{variant:"outline",onClick:()=>{W.refetch()},children:"Retry providers"})]}):null,F.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(T,{variant:"outline",onClick:()=>{F.refetch()},children:"Retry locations"})]}):null,!(y?te:W.isError)&&de&&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."}),v.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",v.map((G,he)=>e.jsxs("span",{children:[he>0?", ":"",e.jsxs("a",{href:`#research-run-${G.id}`,className:"text-link underline",onClick:()=>f(G.id),children:[G.scope?.label??"Whole site",G.location?`, ${G.location.label}`:", No location"]})]},G.id))]})]}),e.jsxs(ve,{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:_t.historyTitle})}),Q.isFetching&&e.jsx(je,{tone:"neutral",children:"Loading"})]}),te?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(T,{variant:"outline",onClick:()=>{Q.refetch()},children:"Retry history"})]}):Q.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):U.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:_t.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:U.map(G=>e.jsxs("tr",{className:k===G.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>f(G.id),children:zg(G.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:G.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:G.requestedModel??G.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:G.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:G.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[G.completedQueries+G.failedQueries,"/",G.totalQueries]}),e.jsx("td",{children:e.jsx(je,{tone:qc(G.status),children:G.status})})]},G.id))})]})}),Q.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:_t.historyMoreError}),Q.hasNextPage&&e.jsx(T,{className:"mt-3",variant:"outline",disabled:Q.isFetching,onClick:()=>{Q.fetchNextPage()},children:Q.isFetchingNextPage?_t.historyLoading:_t.historyMore})]})]}),!te&&P.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(T,{variant:"outline",onClick:()=>{P.refetch()},children:"Retry results"})]}):te?null:e.jsx(Vg,{detail:Y,isLoading:P.isFetching,onReviewForTracking:x?void 0:s})]})}const Ts="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",En="__none__";function Gg(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:l}=t,i=ps(),[c,d]=o.useState("once"),[h,u]=o.useState(""),[p,g]=o.useState(""),[m,y]=o.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[x,b]=o.useState(null),[N,C]=o.useState([]),[M,k]=o.useState(""),[f,v]=o.useState({}),[S,q]=o.useState(null),[I,w]=o.useState([]),[V,F]=o.useState(null),[W,B]=o.useState(!1),[Q,te]=o.useState(!1),[O,U]=o.useState(""),[se,D]=o.useState(""),E=o.useRef(null),P=o.useRef(!1),Y=o.useRef(null),re=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";o.useEffect(()=>{y(re),q(null)},[re]);const ne=t.scopeOptions.filter(A=>A.kind==="market"||A.kind==="property"),de=c==="markets"?"market":"property",Ce=ne.filter(A=>A.kind===de),J=A=>({kind:A.kind,key:A.id,label:A.label,planRevision:l??t.initialScope?.planRevision??0}),oe=A=>A===En?null:n.find(ke=>ke.label===A),Ne=x??t.defaultLocation??En,X=ne.find(A=>`${A.kind}:${A.id}`===m),ie=X?J(X):null,G=c==="once"?[{scope:ie,location:oe(Ne)}]:c==="locations"?N.map(A=>({scope:null,location:oe(A)})):N.map(A=>Ce.find(ke=>`${ke.kind}:${ke.id}`===A)).map(A=>A?{scope:J(A),location:oe(f[`${A.kind}:${A.id}`]??En)}:null),he=[...new Map([...I,...t.templates].map(A=>[A.id,A])).values()],Le=S?he.find(A=>A.id===S.id):null,be=S!==null&&Le?.version!==S.version,ee=c==="once"?h:p,Re=ee.split(/\r?\n/).filter(A=>A.trim()),De=Xi(Re),qe=[...new Set([...p.matchAll(/\{([^{}]+)\}/g)].map(A=>A[1]))],xe=/[{}]/.test(p.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),K=[];Re.length||K.push(c==="once"?"Enter at least one query.":"Enter at least one query pattern."),Re.some(A=>A.length>4e3)&&K.push("Keep each query under 4,001 characters."),c!=="once"&&xe&&K.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),G.length||K.push(c==="locations"?"Select at least one location.":"Select at least one destination."),G.some(A=>!A||A.location===void 0)&&K.push("A selected destination or location is no longer available. Update your selection.");const Oe=c==="once"&&m!=="project"||c==="markets"||c==="properties";Oe&&(t.scopePending||t.scopeError||!l||G.some(A=>!A?.scope))&&K.push("Load the current published markets and properties before running scoped research.");const R=(c==="once"?De.length:Re.length)*G.length;if(G.length>Ma&&K.push(`Select at most ${Ma} destinations.`),R>vr&&K.push(`${R} queries selected. Reduce the selection to ${vr} or fewer.`),be&&K.push("This saved pattern changed. Select its current version from Saved patterns."),c!=="once"&&!xe){for(const A of G)if(!(!A||A.location===void 0))try{br(S??{pattern:p,variables:qe},A.scope,A.location)}catch{K.push(`Choose a location for {location}, or use only variables available for ${c==="markets"?"markets":c==="properties"?"properties":"locations"}.`);break}}const ye=JSON.stringify({mode:c,source:ee,contexts:G,provider:a,resolvedModel:r,template:S,...Oe?{planRevision:l}:{}}),Ke=V!==null&&V.signature!==ye,ze=c==="once"?De.map((A,ke)=>({id:String(ke),query:A,scope:ie,location:G[0]?.location??null})):V?.rows??[],Je=Bg(ze),pe=[];c!=="once"&&V&&(Ke&&pe.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),ze.some(A=>!A.query.trim()||A.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(A.query))&&pe.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),ze.some(A=>A.location&&!n.some(ke=>JSON.stringify(ke)===JSON.stringify(A.location)))&&pe.push("A preview location changed. Regenerate the preview."),Je.some(A=>Xi(A.queries).length!==A.queries.length)&&pe.push("Remove duplicate queries within each destination and location."),Je.length>Ma&&pe.push(`The preview exceeds ${Ma} runs.`));const ht=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!K.length&&!pe.length&&(c==="once"||V!==null),Ve=()=>({runs:Je.map(A=>({queries:A.queries,provider:a,model:r,location:A.location,...A.scope?{scope:{kind:A.scope.kind,key:A.scope.key,expectedPlanRevision:A.scope.planRevision}}:{},...A.template?{template:A.template}:{}}))}),tt=()=>{if(B(!0),K.length)return;const A=G.flatMap((ke,ue)=>Re.map((He,Tt)=>({id:`${ue}:${Tt}`,scope:ke.scope,location:ke.location,...S?{template:{templateId:S.id,templateVersion:S.version,bindingLocation:ke.location}}:{},query:br({pattern:He,variables:[...new Set([...He.matchAll(/\{([^{}]+)\}/g)].map(Mt=>Mt[1]))]},ke.scope,ke.location).output})));F({signature:ye,rows:A})},Wt=A=>{d(A),C([]),q(null),k(""),B(!1)},dt=A=>{if(D(""),c==="once")try{u(br(A,ie,oe(Ne)).output)}catch{D("Select a matching market, property, or location before using this pattern.");return}else g(A.pattern);q(A)},st=A=>{const ke=Y.current,ue=ke?.selectionStart??p.length,He=ke?.selectionEnd??ue;g(`${p.slice(0,ue)}{${A}}${p.slice(He)}`),q(null),requestAnimationFrame(()=>{ke?.focus(),ke?.setSelectionRange(ue+A.length+2,ue+A.length+2)})},pt=Ot({...cu(),onSuccess:async A=>{const ke={id:A.id,version:A.updatedAt,label:A.name,pattern:A.pattern,variables:A.variables};w(ue=>[...ue.filter(He=>He.id!==A.id),ke]),q(ke),te(!1),U(""),D(""),E.current=null,await i.invalidateQueries({queryKey:lu({client:H,path:{name:s}})}),Ee({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>D("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{P.current=!1}}),St=()=>{if(!t.canWrite||t.isEmbed||P.current)return;const A=c==="once"?h:p,ke=c==="once"?[]:qe;if(!O.trim()||!A.trim()||A.length>4e3||c!=="once"&&xe){D("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const ue={name:O.trim(),pattern:A,variables:ke},He=JSON.stringify(ue);E.current?.fingerprint!==He&&(E.current={fingerprint:He,id:crypto.randomUUID()}),P.current=!0,pt.mutate({client:H,path:{name:s,templateId:E.current.id},body:ue})},Rt=[...new Set([...W||ee.trim()?K:[],...pe])],Ge=he.filter(A=>{const ke=c==="once"?Zi(ie,oe(Ne)):Zi(c==="markets"?{kind:"market",label:"Market"}:c==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return A.variables.every(ue=>ke[ue]!==void 0)});return e.jsxs(ve,{className:"surface-card min-w-0",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Test queries"}),e.jsx("p",{className:"mt-1 max-w-prose text-sm text-secondary",children:"See how an answer engine responds. Results are saved separately from tracked queries and AI Visibility metrics."})]})}),e.jsxs("fieldset",{"aria-label":"Research setup",className:"mt-5 min-w-0 space-y-5",disabled:t.isPending||pt.isPending,children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Run mode"}),e.jsxs("select",{className:Ts,value:c,disabled:t.isPending,onChange:A=>Wt(A.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!ne.some(A=>A.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!ne.some(A=>A.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),c==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(ne.length>0||m!=="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:Ts,value:m,onChange:A=>{y(A.target.value),q(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),m!=="project"&&!X&&e.jsx("option",{value:m,disabled:!0,children:"Selected destination unavailable"}),ne.map(A=>e.jsxs("option",{value:`${A.kind}:${A.id}`,children:[A.label," (",A.kind,")"]},`${A.kind}:${A.id}`))]})]}),e.jsx(mi,{label:"Answer engine location",value:Ne,locations:n,onChange:A=>{b(A),q(null)}})]}),c!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:c==="locations"?"Select locations":`Select ${c}`}),e.jsx("p",{className:"text-sm text-secondary",children:"Choose each destination explicitly. Each selected destination gets its own saved research run."}),e.jsx("input",{type:"search","aria-label":"Search destinations",className:Ts,placeholder:`Search ${c}`,value:M,onChange:A=>k(A.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(c==="locations"?n.map(A=>({key:A.label,label:A.label})):Ce.map(A=>({key:`${A.kind}:${A.id}`,label:A.label}))).filter(A=>A.label.toLocaleLowerCase().includes(M.toLocaleLowerCase())).map(A=>{const ke=N.includes(A.key);return e.jsxs("div",{className:"grid items-center gap-2 border-b border-default pb-2 sm:grid-cols-[minmax(0,1fr)_16rem]",children:[e.jsxs("label",{className:"flex min-h-11 items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:ke,onChange:()=>C(ue=>ke?ue.filter(He=>He!==A.key):[...ue,A.key])}),A.label]}),ke&&c!=="locations"&&e.jsx(mi,{label:`Answer engine location for ${A.label}`,value:f[A.key]??En,locations:n,onChange:ue=>v(He=>({...He,[A.key]:ue}))})]},A.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[N.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(T,{variant:"outline",onClick:t.onRetryScope,children:"Retry destinations"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block",htmlFor:"research-query-editor",children:e.jsx("span",{className:"text-sm font-medium text-heading",children:c==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:c==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${c==="markets"?"market":c==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:Y,className:`${Ts} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:ee,placeholder:c==="once"?_t.queryPlaceholder:c==="markets"?"Best apartments in {market}":c==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:A=>{c==="once"?u(A.target.value):(g(A.target.value),q(null))}}),c!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(T,{size:"sm",variant:"outline",onClick:()=>st(c==="markets"?"market":c==="properties"?"property":"location"),children:["Insert ",c==="markets"?"market":c==="properties"?"property":"location"," name"]}),e.jsx("span",{className:"self-center text-sm text-secondary",children:"One pattern per line."})]}),e.jsxs("p",{id:"research-query-count",className:"mt-2 text-sm text-secondary",children:[R," / ",vr," queries",c==="once"?"":` across ${G.length} destinations`]})]}),c!=="once"&&e.jsxs("details",{className:"border-t border-default pt-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading focus-visible:outline focus-visible:outline-2",children:["Saved patterns ",e.jsx("span",{className:"font-normal text-secondary",children:"(optional)"})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries."}),Ge.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:Ge.map(A=>e.jsx(T,{size:"sm",variant:"outline",onClick:()=>dt(A),children:A.label},A.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),S&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",S.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(T,{size:"sm",variant:"outline",onClick:()=>te(!Q),children:Q?"Cancel save":"Save as a pattern"}),Q&&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:Ts,value:O,maxLength:120,onChange:A=>U(A.target.value)})]}),e.jsx(T,{size:"sm",disabled:pt.isPending||!O.trim()||!ee.trim(),onClick:St,children:pt.isPending?"Saving…":"Save pattern"})]})]}),se&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:se})]})]}),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:Ts,value:a,onChange:A=>t.onProviderChange(A.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose an answer engine"}),t.providerOptions.map(A=>e.jsx("option",{value:A.name,children:A.displayName??A.name},A.name))]})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Model",t.limitedAccess?e.jsxs("select",{className:Ts,value:t.model,disabled:!a||!t.configurableModel,onChange:A=>t.onModelChange(A.target.value),children:[e.jsxs("option",{value:"",children:["Use AI Visibility model · ",t.visibilityModel]}),t.modelOptions.map(A=>e.jsx("option",{value:A.id,children:A.displayName},A.id))]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{"aria-label":"Model",className:Ts,list:"research-known-models",placeholder:r??"Choose an answer engine",value:t.model,disabled:!a||!t.configurableModel,onChange:A=>t.onModelChange(A.target.value)}),e.jsx("datalist",{id:"research-known-models",children:t.modelOptions.map(A=>e.jsx("option",{value:A.id,children:A.displayName},A.id))})]})]})]}),Rt.length>0&&e.jsx(Ug,{errors:Rt}),c!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(T,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:tt,children:[e.jsx(pa,{size:14}),V?_t.refreshPreview:"Preview queries"]}),V&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Queries to run"}),e.jsxs("p",{className:"text-sm text-secondary",children:[ze.length," query executions in ",Je.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(_g,{rows:ze,locations:n,onChange:(A,ke)=>F(ue=>ue&&{...ue,rows:ue.rows.map(He=>He.id===A?{...He,...ke}:He)})})]})]}),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(T,{size:"sm",disabled:!ht,onClick:()=>{if(ht){const A=Ve();t.onSubmit(A,JSON.stringify({projectName:s,...A}))}},children:[e.jsx(ar,{size:14}),t.isPending?"Starting…":_t.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[c==="once"?`${De.length} queries`:`${ze.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function mi({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:Ts,value:s,onChange:r=>a(r.target.value),children:[e.jsx("option",{value:En,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function _g({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:`${Ts} 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(mi,{label:`Location for query ${r+1}`,value:a.location?.label??En,locations:s,onChange:l=>n(a.id,{location:s.find(i=>i.label===l)??null})})]},a.id))})}function Ug({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 Bg(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 Vg({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(ve,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":_t.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 ${Hg(t.id)}`:_t.resultsEmpty})]}),t&&e.jsx(je,{tone:qc(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:_t.templateProvenance}),e.jsxs("dl",{className:"mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Saved pattern"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.template})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Names used"}),e.jsx("dd",{children:Object.entries(t.template.bindings).map(([i,c])=>`${i}: ${c}`).join(" · ")||"No variables"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Original resolved text"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.output})]})]}),e.jsx("p",{className:"mt-2",children:"The queries below are the final text sent to the answer engine, including any edits."}),e.jsxs("p",{className:"mt-2 font-mono text-xs",children:[t.template.templateId," · ",t.template.templateVersion]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:_t.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:_t.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(je,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?_t.brandedQuery:i.queryClass==="non-brand"?_t.discoveryQuery:_t.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(je,{tone:Wg(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(je,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===vn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===vn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(je,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===vn.failed?"negative":"caution",children:i.citationState===null?i.status===vn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(Qg,{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 Qg({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})]}),!le()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(Ye,{type:"button",size:"sm",onClick:()=>a({researchRunQueryId:t.id,scope:n}),children:"Review for tracking"}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Only this saved query text enters tracking review. Its answer remains research evidence."})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("div",{className:"mt-1",children:e.jsx(Ci,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===vn.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(ji,{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 zg(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 Hg(t){return t.length>8?t.slice(0,8):t}function qc(t){return t===ca.completed?"positive":t===ca.partial?"caution":t===ca.failed?"negative":"neutral"}function Wg(t){return t===vn.completed?"positive":t===vn.failed?"negative":"neutral"}async function Yg(t){await It(t,"researchRuns")}const hi=new Set(["queued","seeding","probing"]);function Jg({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:l={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d}){const{account:h}=Sn(),[u,p]=o.useState("tracked"),[g,m]=o.useState("find"),[y,x]=o.useState(null),b=h?.role==="viewer"?_l():null,N=sc(h?.role,b),M=nc(s??u,N),k=a??g,f=q=>{s===void 0&&p(q),n?.(q)},v=q=>{a===void 0&&m(q),r?.(q)},S=(q,I)=>{const w=I===void 0?{...l}:{...l,measurementScope:I?.kind??"project",measurementScopeKey:I?.key};x({...q,trackingSelection:w}),I!==void 0&&i?.({measurementScope:w.measurementScope,measurementScopeKey:w.measurementScopeKey}),f("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(dr,{active:M==="tracked",label:"Tracked",onClick:()=>f("tracked")}),N?e.jsx(dr,{active:M==="research",label:"Research",onClick:()=>f("research")}):null]}),e.jsx("div",{className:"mt-4",children:M==="tracked"?e.jsx(yf,{projectName:t,selection:l,onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d,pendingTrackingSource:y,onPendingTrackingSourceHandled:()=>x(null)}):e.jsx(Xg,{projectName:t,selection:l,mode:k,onModeChange:v,onReviewSavedSource:S,onSelectionChange:i,viewerResearchConfig:b})})]})}function dr({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 Xg({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:l}){const{canWrite:i}=Sn(),c=!i||n==="test",d=$e({...Si({client:H,path:{name:t}}),enabled:c,staleTime:6e4}),h=$e({...Ul({client:H,path:{name:t}}),enabled:c,staleTime:6e4}),u=o.useMemo(()=>{const m=d.data;if(!m)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const y=new Map(m.targets.map(b=>[b.stableKey,[]]));for(const b of m.groups)for(const N of b.targetKeys)y.get(N)?.push(b.stableKey);const x=new Map(m.markets.map(b=>[b.stableKey,new Set]));for(const b of m.markets)for(const N of b.usageEdges)for(const C of y.get(N.targetKey)??[])x.get(b.stableKey)?.add(C);return[{id:"project",label:"Whole site",kind:"project",targetCount:m.targets.length},...m.groups.map(b=>({id:b.stableKey,label:b.label,kind:"group",targetCount:b.targetKeys.length,...b.parentGroupKey?{parentGroupIds:[b.parentGroupKey]}:{}})),...m.markets.map(b=>{const N=[...x.get(b.stableKey)??[]];return{id:b.stableKey,label:b.label,kind:"market",targetCount:0,...N.length?{parentGroupIds:N}:{}}}),...m.targets.map(b=>({id:b.stableKey,label:b.label,kind:"property",targetCount:1,...y.get(b.stableKey)?.length?{parentGroupIds:y.get(b.stableKey)}:{}}))]},[d.data]),p=o.useMemo(()=>(h.data?.templates??[]).map(m=>({id:m.id,version:m.updatedAt,label:m.name,pattern:m.pattern,variables:m.variables})),[h.data]),g={projectName:t,scopeOptions:u,planRevision:d.data?.active?.revision??null,selectedScope:(()=>{const m=u.find(x=>x.kind===s.measurementScope&&x.id===s.measurementScopeKey),y=d.data?.active?.revision;return m&&y&&(m.kind==="market"||m.kind==="property")?{kind:m.kind,key:m.id,label:m.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:d.isPending||d.isFetching,scopeError:d.isError,onRetryScope:()=>{d.refetch()},templates:p};return i?e.jsxs("div",{children:[e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(dr,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(dr,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(bf,{projectName:t,onReviewDiscoveryProbe:m=>r({source:"discovery",discoveryProbeId:m})}):e.jsx(Wo,{...g,onReviewForTracking:({researchRunQueryId:m,scope:y})=>r({source:"research",researchRunQueryId:m},y??null)})})]}):e.jsx(Wo,{...g,viewerResearchConfig:l})}function Zg({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:c,preview:d,isPreviewing:h,isCommitting:u,onPreview:p,onCommit:g}){const[m,y]=o.useState(null),[x,b]=o.useState(()=>er(s)),[N,C]=o.useState(null),M=o.useRef(null),k=o.useRef(null),f=ac(t,s),v=o.useMemo(()=>nf(t.tracked,s,t.mode),[s,t.mode,t.tracked]),S=jn({rows:v,getSearchText:Q=>`${Q.queryText} ${Q.provenance?.source??"legacy"} ${Q.assignments.map(te=>te.queryClass??"unknown").join(" ")}`});o.useEffect(()=>{if(f)return;if(!a){k.current=null;return}const Q=`${a}:${Dr(s)}`;if(k.current===Q)return;const te=t.tracked.find(O=>O.queryId===a);te&&(k.current=Q,y({kind:"edit",row:te,audience:t.mode==="advanced"?Lr(s):void 0,scopeLabel:Er(s,t)}),b(Yo(te,s)),C(null))},[s,a,f,t]),o.useEffect(()=>{if(f||!l)return;const Q=er(l.trackingSelection??s);y({kind:"add"}),b(l.source==="research"?{...Q,source:"research",researchRunQueryId:l.researchRunQueryId}:{...Q,source:"discovery",discoveryProbeId:l.discoveryProbeId}),C(null),i()},[i,l,s,f]),o.useEffect(()=>{f&&(y(null),C(null),a!==void 0&&r?.(void 0))},[r,a,f]),o.useEffect(()=>{if(!m||m.kind==="remove")return;const Q=M.current;Q&&(Q.scrollIntoView?.({block:"start"}),Q.focus({preventScroll:!0}))},[m]);function q(Q="manual"){y({kind:"add"}),b({...er(s),source:Q}),C(null),r?.(void 0)}function I(Q){k.current=`${Q.queryId}:${Dr(s)}`,y({kind:"edit",row:Q,audience:t.mode==="advanced"?Lr(s):void 0,scopeLabel:Er(s,t)}),b(Yo(Q,s)),C(null),r?.(Q.queryId)}function w(Q){k.current=`${Q.queryId}:${Dr(s)}`,y({kind:"remove",row:Q,audience:t.mode==="advanced"?Lr(s):void 0,scopeLabel:Er(s,t)}),C(null),r?.(Q.queryId)}function V(){y(null),C(null),r?.(void 0)}const F=m?ef(m,x,t.mode):null,W=m!==null&&m.kind==="add"&&t.mode==="advanced"&&!Li(x),B=F!==null&&(!W||x.contexts.length>0)&&!h;return f?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(T,{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(af,{selection:s,onSelectionChange:n}):null,e.jsx(Xs,{value:S.query,onChange:S.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!le()&&e.jsxs(Ye,{type:"button",size:"sm",onClick:()=>q(),children:[e.jsx(Kh,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[S.totalRows.toLocaleString("en-US")," saved query ",S.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."}),S.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:S.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:S.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(of,{row:Q,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(cf,{row:Q})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:rf(Q)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(df,{row:Q,outsidePlan:t.mode==="advanced"&&Q.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!le()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${Q.queryText}`,onClick:()=>I(Q),children:[e.jsx(Gh,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${Q.queryText}`,onClick:()=>w(Q),children:[e.jsx(tc,{"aria-hidden":"true",size:13})," Remove"]})]})})]},Q.queryId))})]})}),e.jsx(Fs,{page:S.page,pageSize:S.pageSize,visibleRows:S.rows.length,totalRows:S.totalRows,itemLabel:"queries",onPageChange:S.setPage})]}),m&&!le()&&e.jsx(uf,{workspace:t,templates:c,action:m,draft:x,onDraftChange:Q=>{b(Q),C(null)},onClose:V,canReview:B,isPreviewing:h,editorHeadingRef:M,onReview:()=>{F&&(C(F),p(F))}}),d&&N&&m&&e.jsx(xf,{preview:d,workspace:t,isCommitting:u,onConfirm:()=>{g({...N,expectedWorkspaceVersion:d.workspaceVersion,previewToken:d.previewToken,reviewedAt:d.reviewedAt})}})]})}function er(t){return{source:"manual",text:"",templateId:"",templateVersion:"",template:"",researchRunQueryId:"",discoveryProbeId:"",wholeSite:t.measurementScope==="project"||!t.measurementScopeKey,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 Yo(t,s){return{...er(s),text:t.queryText,queryClass:"keep"}}function ef(t,s,n){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}:{},...n==="advanced"&&s.queryClass!=="keep"?{queryClass:s.queryClass==="auto"?null:s.queryClass}:{}}]}:null;const a=tf(s);if(!a||pi(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=sf(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!Li(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function tf(t){return t.source==="manual"?t.text.trim()?{source:"manual",text:t.text.trim()}:null:t.source==="template"?t.templateId&&t.templateVersion&&t.template?{source:"template",templateId:t.templateId,templateVersion:t.templateVersion,template:t.template}:null:t.source==="research"?t.researchRunQueryId?{source:"research",researchRunQueryId:t.researchRunQueryId}:null:t.discoveryProbeId?{source:"discovery",discoveryProbeId:t.discoveryProbeId}:null}function sf(t){if(t.wholeSite)return;const s={...t.targetKeys.length>0?{targetKeys:t.targetKeys}:{},...t.groupKeys.length>0?{groupKeys:t.groupKeys}:{},...t.marketKeys.length>0?{marketKeys:t.marketKeys}:{}};return Object.keys(s).length>0?s:void 0}function Li(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function pi(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function Lr(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 Er(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 Ei(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 nf(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=>Ei(r,s)))}function af({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 Dr(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function rf(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 $c(t,s,n){const a=new Map(s.targets.map(x=>[x.stableKey,x.label])),r=new Map(s.groups.map(x=>[x.stableKey,x.label])),l=new Map(s.markets.map(x=>[x.stableKey,x.label])),i=new Set(t.assignments.map(x=>x.targetKey));if(i.size===0)return"Whole site";const c=n?t.assignments.filter(x=>Ei(x,n)):t.assignments,d=new Set(c.map(x=>x.targetKey));if(n?.measurementScope==="group"){const x=d.size,b=Math.max(0,i.size-x);return[`${x} ${x===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 x of c)x.groupKeys.forEach(b=>h.add(b)),x.marketKeys.forEach(b=>u.add(b));const g=n?.measurementScope==="property"&&i.has(n.measurementScopeKey??"")?i.size===1?["This property only"]:["This property",`Shared with ${i.size-1} other ${i.size===2?"property":"properties"}`]:d.size===1?[a.get([...d][0])??[...d][0]]:[`${d.size} properties`],m=h.size===1?r.get([...h][0])??[...h][0]:null,y=u.size===1?l.get([...u][0])??[...u][0]:null;return m&&y&&m===y?g.push(`${m} (group and market)`):(m?g.push(`Group: ${m}`):h.size>1&&g.push(`${h.size} groups`),y?g.push(`Market: ${y}`):u.size>1&&g.push(`${u.size} markets`)),g.join(" · ")}function of({row:t,workspace:s,selection:n}){const a=lf(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:$c(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 lf(t,s,n){const a=new Map(s.targets.map(d=>[d.stableKey,d.label])),r=new Map(s.groups.map(d=>[d.stableKey,d.label])),l=new Map(s.markets.map(d=>[d.stableKey,d.label])),c=t.assignments.filter(d=>Ei(d,n)).map(d=>{const h=a.get(d.targetKey)??d.targetKey??"Whole site",u=n.measurementScope==="group"&&n.measurementScopeKey?d.groupKeys.filter(g=>g===n.measurementScopeKey).map(g=>r.get(g)??g):d.groupKeys.map(g=>r.get(g)??g),p=n.measurementScope==="market"&&n.measurementScopeKey?d.marketKeys.filter(g=>g===n.measurementScopeKey).map(g=>l.get(g)??g):d.marketKeys.map(g=>l.get(g)??g);return[h,u.length?`Groups: ${u.join(", ")}`:null,p.length?`Markets: ${p.join(", ")}`:null].filter(g=>g!==null).join(" · ")});return[...new Set(c)].length?[...new Set(c)]:["Whole site"]}function cf({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(je,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function df({row:t,outsidePlan:s=!1}){return s?e.jsx(je,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(je,{tone:"positive",children:"Measured"}):e.jsx(je,{tone:"caution",children:"Awaiting sweep"})}function uf({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:l,canReview:i,isPreviewing:c,editorHeadingRef:d,onReview:h}){const u=s.length>0;return n.kind==="remove"?e.jsxs(ve,{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(Or,{canReview:i,isPreviewing:c,onCancel:l,onReview:h})]}):n.kind==="edit"?e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Edit query"}),e.jsx(T,{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:p=>r({...a,text:p.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:p=>r({...a,queryClass:p.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(Or,{canReview:i,isPreviewing:c,onCancel:l,onReview:h})]}):e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Add query"}),e.jsx(T,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-[minmax(250px,0.8fr)_minmax(0,1.2fr)]",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:p=>r({...a,text:p.target.value})})]}):null,a.source==="template"?e.jsx(mf,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(Jo,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(p=>({id:p.researchRunQueryId,label:p.queryText,detail:p.researchRunId})),onChange:p=>r({...a,researchRunQueryId:p})}):null,a.source==="discovery"?e.jsx(Jo,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(p=>({id:p.discoveryProbeId,label:p.queryText,detail:p.discoverySessionId})),onChange:p=>r({...a,discoveryProbeId:p})}):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:p=>r({...a,source:p.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."})]}),e.jsx(pf,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!Li(a)?e.jsx("div",{className:"mt-4",children:e.jsx(hf,{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:p=>r({...a,queryClass:p.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(Or,{canReview:i,isPreviewing:c,onCancel:l,onReview:h})]})}function mf({templates:t,draft:s,onDraftChange:n}){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":pi(s)?"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:s.templateId,onChange:a=>{const r=t.find(l=>l.id===a.target.value);n({...s,templateId:r?.id??"",templateVersion:r?.updatedAt??"",template:r?.pattern??""})},children:[e.jsx("option",{value:"",children:"Choose a template"}),t.map(a=>e.jsx("option",{value:a.id,children:a.name},a.id))]}),s.template?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-muted",children:s.template}):null]}),pi(s)?e.jsx("p",{id:"tracking-template-market-required",role:"status",className:"mt-2 text-sm leading-5 text-caution",children:"Choose a Market under Apply to for this template. A location alone does not select a market."}):null]})}function Jo({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 Di(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function ia(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 Lc(t){return[...new Map(t.map(s=>[ia(s),s])).values()]}function Oi(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 hf({workspace:t,draft:s,onDraftChange:n}){const a=o.useMemo(()=>Lc([...t.defaultContexts.map(Di),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?ia(s.contexts[0]):s.contexts.length>1?"__existing__":"";return e.jsxs("label",{className:"block",htmlFor:"tracking-query-context",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location and engines"}),e.jsxs("select",{id:"tracking-query-context","aria-label":"Location and engines",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:r,onChange:l=>{const i=a.find(d=>ia(d)===l.target.value),c=l.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:c})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(l=>e.jsx("option",{value:ia(l),children:Oi(l)},ia(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 pf({workspace:t,draft:s,onDraftChange:n}){const[a,r]=o.useState(""),[l,i]=o.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),c=o.useMemo(()=>[...t.targets.map(m=>({kind:"target",key:m.stableKey,label:m.label,detail:"Property"})),...t.groups.map(m=>({kind:"group",key:m.stableKey,label:m.label,detail:"Group"})),...t.markets.map(m=>({kind:"market",key:m.stableKey,label:m.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),d=a.trim().toLocaleLowerCase(),h=d?c.filter(m=>`${m.label} ${m.detail}`.toLocaleLowerCase().includes(d)):c,u=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function p(m,y,x){const b=m==="target"?"targetKeys":m==="group"?"groupKeys":"marketKeys",N=s[b];n({...s,wholeSite:!1,[b]:x?[...N,y]:N.filter(C=>C!==y)})}function g(m,y){return(m==="target"?s.targetKeys:m==="group"?s.groupKeys:s.marketKeys).includes(y)}if(!l){const m=t.targets.find(y=>y.stableKey===s.targetKeys[0]);return e.jsxs("fieldset",{className:"self-start rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-sm text-strong",children:["Property: ",m?.label??s.targetKeys[0]]}),e.jsx(T,{type:"button",variant:"ghost",size:"sm","aria-label":"Change tracking destination",onClick:()=>i(!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."}),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:m=>{n({...s,wholeSite:m.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),"Whole site"]}),!s.wholeSite&&!u?e.jsx("p",{role:"status",className:"mt-2 text-sm text-caution",children:"Choose Whole site or at least one property, 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(Xs,{value:a,onChange:r,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:h.length===0?e.jsx("p",{className:"px-1 py-2 text-sm text-muted",children:"No assignment matches that search."}):h.map(m=>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":`${m.label}, ${m.detail}`,checked:g(m.kind,m.key),onChange:y=>p(m.kind,m.key,y.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:m.label}),e.jsx("span",{className:"text-xs text-muted",children:m.detail})]},`${m.kind}:${m.key}`))})]})}function Or({canReview:t,isPreviewing:s,onCancel:n,onReview:a}){return e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[e.jsx(Ye,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(T,{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 xf({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=o.useRef(null);o.useEffect(()=>{const c=r.current;c&&(typeof c.scrollIntoView=="function"&&c.scrollIntoView({block:"start"}),c.focus({preventScroll:!0}))},[t]);const l=!t.diff.noOp,i=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(c=>c.rows.length>0);return e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{ref:r,tabIndex:-1,children:l?"Confirm tracked query changes":"No tracking changes"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:l?"Changes apply to future sweeps. Earlier results stay unchanged.":"This request leaves tracking unchanged."})]}),e.jsx(je,{tone:l?"caution":"neutral",children:l?"Ready to confirm":"No-op"})]}),i.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:i.map(c=>e.jsx(Xo,{label:c.label,rows:c.rows,workspace:s,tracked:t.tracked},c.label))}):null,t.diff.unchanged.length>0?e.jsxs("details",{className:"mt-4 border-t border-default pt-2 text-sm text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3",children:[t.diff.unchanged.length," unchanged ",t.diff.unchanged.length===1?"query":"queries"]}),e.jsx(Xo,{label:"Unchanged",rows:t.diff.unchanged,workspace:s,tracked:t.tracked})]}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Next sweep workload"}),e.jsxs("p",{className:"leading-6",children:["Next sweep: ",t.workload.nextSweepProviderCalls," provider requests (+",t.workload.addedProviderCalls,", −",t.workload.removedProviderCalls,")."]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:e.jsx(Ye,{type:"button",size:"sm",disabled:!l||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function Xo({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`:ff(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(gf,{row:a.find(l=>l.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function gf({row:t,workspace:s}){if(!t?.assignments.length)return null;const n=new Set(t.assignments.map(a=>a.targetKey)).size;return e.jsxs("details",{className:"mt-2 text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:["Classifications · ",n," ",n===1?"property":"properties"]}),e.jsx("ul",{className:"mt-1 max-h-40 space-y-1 overflow-y-auto",children:t.assignments.map((a,r)=>{const l=s.targets.find(d=>d.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",c=a.contexts.map(d=>Oi(Di(d))).join("; ");return e.jsx("li",{children:[l,i,c].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function ff(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=Lc(a.assignments.flatMap(i=>i.contexts).map(Di)),l=r.length===1?Oi(r[0]):r.length>1?`${r.length} contexts`:null;return[$c(a,n),l].filter(i=>i!==null).join(" · ")}function yf({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i}){const c=ps(),[d,h]=o.useState(null),u=$e({...Si({client:H,path:{name:t}})}),p=$e({...Ul({client:H,path:{name:t}}),staleTime:6e4}),g=Ot({...uu(),onSuccess:y=>h(y),onError:async y=>{h(null),await c.invalidateQueries({queryKey:du({client:H,path:{name:t}})}),Ee({title:"Could not review tracking changes",detail:y instanceof Error?y.message:"Update the draft and review it again.",tone:"negative"})}}),m=Ot({...mu(),onSuccess:async y=>{h(null),r?.(void 0),await eo(c,t),Ee({title:y.committed?"Tracked queries updated":"No tracked-query change",detail:y.active?`Measurement revision ${y.active.revision}.`:"No measurement revision is published yet.",tone:y.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async y=>{h(null),await eo(c,t),Ee({title:"Could not confirm tracking changes",detail:y instanceof Error?y.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return u.isLoading?e.jsx(ve,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):u.isError||!u.data?e.jsxs(ve,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{u.refetch()},children:"Try again"})]}):e.jsx(Zg,{workspace:u.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:p.data?.templates??[],preview:d,isPreviewing:g.isPending,isCommitting:m.isPending,onPreview:y=>{h(null),g.mutate({client:H,path:{name:t},body:{...y,expectedWorkspaceVersion:u.data.workspaceVersion}})},onCommit:y=>m.mutate({client:H,path:{name:t},body:y})})}function bf({projectName:t,onReviewDiscoveryProbe:s}){const n=ps(),[a,r]=o.useState(null),[l,i]=o.useState(""),[c,d]=o.useState("100"),h=$e({...hu({client:H,path:{name:t},query:{limit:"10"}}),refetchInterval:C=>C.state.data?.some(k=>hi.has(k.status))?3e3:!1}),u=h.data??[];o.useEffect(()=>{!a&&u[0]&&r(u[0].id)},[a,u]);const p=u.find(C=>C.id===a)??null,g=$e({...pu({client:H,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:p&&hi.has(p.status)?3e3:!1}),m=g.data??null,y=Ot({mutationFn:()=>{const C={},M=l.trim();M&&(C.icpDescription=M);const k=Number.parseInt(c,10);return Number.isFinite(k)&&k>0&&(C.maxProbes=k),xu(t,C)},onSuccess:async C=>{r(C.sessionId),i(""),await wf(n,t,C.sessionId),Ee({title:"Discovery started",detail:`Run ${Fr(C.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${C.sessionId}`,dedupeMode:"replace"})},onError:C=>{Ee({title:"Discovery failed to start",detail:C instanceof Error?C.message:"Could not start discovery.",tone:"negative"})}}),x=m??p,b=o.useMemo(()=>(m?.probes??[]).slice(0,30),[m?.probes]);async function N(){try{const C=await h.refetch();if(C.error)throw C.error;const M=C.data?.length??0;Ee({title:"Discovery sessions refreshed",detail:`${M} recent session${M===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(C){Ee({title:"Discovery refresh failed",detail:C instanceof Error?C.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:le()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(T,{type:"button",variant:"outline",size:"sm",disabled:h.isFetching,onClick:()=>{N()},children:[e.jsx(pa,{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(ve,{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(je,{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:C=>i(C.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:c,onChange:C=>d(C.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."})]}),!le()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:y.isPending,onClick:()=>y.mutate(),children:[e.jsx(ar,{size:14}),y.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(ve,{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(je,{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(C=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===C.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(C.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:Fr(C.id)}),e.jsx(je,{tone:Zo(C.status),children:C.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",C.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",C.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",C.wastedCount??0]})]})]},C.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ve,{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:x?Fr(x.id):"No run selected"})]}),x&&e.jsx(je,{tone:Zo(x.status),children:x.status})]}),x?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ga,{label:"Questions tested",value:x.probeCount??0}),e.jsx(Ga,{label:"Cited queries",value:x.citedCount??0,tone:"positive"}),e.jsx(Ga,{label:"Worth tracking",value:x.aspirationalCount??0,tone:"caution"}),e.jsx(Ga,{label:"Skip",value:x.wastedCount??0,tone:"negative"})]}),x.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:x.error}),x.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:x.warning}),x.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:x.icpDescription})]}),x.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:x.competitorMap.slice(0,8).map(C=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[C.domain," ",e.jsx("span",{className:"text-muted",children:C.hits})]},C.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),x?.status==="completed"&&e.jsxs(ve,{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(ve,{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"})]}),g.isFetching&&e.jsx(je,{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(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:C.query}),e.jsx("td",{children:e.jsx(je,{tone:vf(C.bucket),children:Nf(C.bucket)})}),e.jsx("td",{className:"text-secondary",children:C.citedDomains.length>0?C.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!le()&&s&&(C.bucket==="cited"||C.bucket==="aspirational")&&e.jsx(Ye,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(C.id),children:"Review for tracking"})})]},C.id))})]})})]})]})]})]})}function Ga({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 Zo(t){return t==="completed"?"positive":t==="failed"?"negative":hi.has(t)?"caution":"neutral"}function vf(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const jf={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Nf(t){return t?jf[t]:"Not classified"}function Fr(t){return t.length>8?t.slice(0,8):t}async function wf(t,s,n){await Promise.all([It(t,"discovery"),t.invalidateQueries({queryKey:gu({client:H})})])}function Sf({projectName:t}){const[s,n]=o.useState("changes"),[a,r]=o.useState(null),[l,i]=o.useState(null),c=$e({...fu({client:H,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=$e({...yu({client:H,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(d.data??[]).filter(b=>(b.status==="completed"||b.status==="partial")&&b.trigger!=="probe").reverse(),u=l??h[0]?.id??"",p=a??h.find(b=>b.id!==u)?.id??"",g=!!(p&&u&&p!==u),m=$e({...bu({client:H,path:{name:t},query:{run1:p,run2:u}}),enabled:s==="compare"&&g}),y=c.data??[],x=m.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,N])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===b,className:`filter-chip ${s===b?"filter-chip-active":""}`,onClick:()=>n(b),children:N},b))}),s==="changes"?e.jsx(Hh,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),c.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!c.isLoading&&y.length===0?e.jsxs(ve,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:us()?_n:"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:et(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:et(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:p,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))})]})]}),d.isLoading||m.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!d.isLoading&&h.length<2?e.jsxs(ve,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:us()?_n:"Run another answer visibility sweep before comparing historical evidence."})]}):null,m.data&&x.length===0?e.jsxs(ve,{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,x.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:x.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:b.query??"Archived query"}),e.jsx("td",{children:e.jsxs(je,{tone:b.changed?"caution":"neutral",children:[b.run1State??"none"," → ",b.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(je,{tone:b.visibilityChanged?"caution":"neutral",children:[b.run1MentionState??"none"," → ",b.run2MentionState??"none"]})})]},b.queryId??b.query??"unknown"))})]})}):null]}):null]})}const el={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},Cf={contract:null,assessment:null,googleAds:el,gtm:el,snapshots:[]};function kf(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":If(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Af(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 Rf(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 Pf(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 Ec(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"&&Tf(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 If(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Tf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Dc(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 Mf(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 qf(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 hn(t){return t.length<=12?t:`…${t.slice(-10)}`}function $f(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 Lf(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 Kr={"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 tl(t){return t.outcome==="pass"?{label:Kr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Kr[t.code],tone:"negative",outcome:"Fail"}:{label:Kr[t.code],tone:"caution",outcome:"Unknown"}}function Ef(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Df(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 Of(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function sl({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const l=Dc(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(je,{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 ${Ht(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const Ff="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.",Kf="Available once Google Ads and Tag Manager are connected.",Gf="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 _f({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:l}){const i=t.googleAds.state==="connected",c=t.gtm.state==="connected",d=t.googleAds.state==="unavailable",h=t.gtm.state==="unavailable",u=d||h||t.gtm.state==="unavailable",p={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},g=!i&&!c,m=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:d?p:Rf(t)},{title:"Tag Manager",state:t.gtm.state,ready:c,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?p:Pf(t)}],y=i&&c&&!u?Ec(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(Be,{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."})]}),g?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:Gf}):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(Be,{text:Ff})]}),y&&s?e.jsx(Ye,{type:"button",disabled:r,onClick:()=>s(y.id),children:r?"Working…":y.label}):e.jsx("p",{className:"text-sm text-secondary",children:Kf})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:m.map(x=>{const b=x.ready?{label:"Ready",tone:"positive"}:Dc(x.state),N=x.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:x.title}),e.jsx(je,{tone:b.tone,children:b.label}),x.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:x.summary}):null,N&&s?N.id==="retry-connection-status"?e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(N.id),children:r?"Working…":N.label}):e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(N.id),children:r?"Working…":N.label}):null,x.summary&&x.onChange?e.jsx(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":x.changeLabel,disabled:r,onClick:x.onChange,children:"Change"}):null]},x.title)})}),l?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:l}):null]})]})}function Uf({workspace:t=Cf,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:l=null,onSelectContract:i,contractError:c=null,onRetryContracts:d,onRetryEvidence:h,onChangeGoogleAdsSelection:u,onChangeGtmSelection:p,onAddContract:g}){const m=kf(t),y=Af(m),x=Ec(t),b=t.assessment?.findings??[],N=b.filter(f=>f.outcome!=="pass"),C=b.filter(f=>f.outcome==="pass"),M=N.some(f=>f.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&c===null?e.jsx(_f,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:u,onChangeGtmSelection:p,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(je,{tone:y.tone,children:y.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Ht(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(f=>e.jsxs("li",{className:"break-words",children:[Of(f)," ",f.kind,", captured ",Ht(f.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",f.id,")"]})]},f.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?x.id==="review-findings"||x.id==="review-runtime-verification"||x.id==="retry-connection-status"||x.id==="select-contract"||x.id==="retry-integrity"||x.id==="waiting-for-integrity"?e.jsx(T,{type:"button",disabled:n||x.id==="waiting-for-integrity",onClick:()=>s(x.id),children:n?"Working…":x.label}):e.jsx(Ye,{type:"button",disabled:n,onClick:()=>s(x.id),children:n?"Working…":x.label}):x.id==="review-findings"?e.jsx(T,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):m==="runtime-unverified"?e.jsx(T,{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:x.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&&g?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:g,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:f=>i?.(f.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(f=>e.jsx("option",{value:f.id,children:f.name},f.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:$f(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:Lf(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:hn(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:hn(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:hn(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:hn(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),c?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:c}),d?e.jsx(T,{type:"button",variant:"outline",onClick:d,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),N.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(je,{tone:M,children:[N.length," ",N.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:N.map(f=>{const v=tl(f);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:v.label}),e.jsx(je,{tone:v.tone,children:v.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",f.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",f.code]}),f.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",f.evidenceIds.join(", ")]}):null]},`${f.code}:${f.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(Be,{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(f=>{const v=Mf(f.key,m);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 ${v==="positive"?"bg-positive-fill":v==="caution"?"bg-caution-fill":v==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:f.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:f.detail}),e.jsx(je,{tone:v,children:qf(f.key,m)})]},f.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:p}:{},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(T,{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(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:f.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:f.kind}),e.jsx("td",{className:"text-secondary",children:Ht(f.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:hn(f.id)})]},f.id))})]})})]}):null,C.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[C.length," ",C.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:C.map(f=>{const v=tl(f);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:v.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",f.code]}),f.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",f.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(je,{tone:v.tone,children:v.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:f.subject})]},`${f.code}:${f.subject}`)})})]})})]}):null,m==="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 ",Ef(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:hn(t.contract.gtm.tagId)})," fires with ",Df(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:hn(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const pn=3e4,nl={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Gt="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",cs="text-sm font-medium text-secondary";function al(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:Ct(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function _a(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function Bf(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 Vf(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Qf(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:Vf(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 zf(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:_a(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:_a(t.triggerIds),variableIds:_a(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:_a(t.productionHosts)}}}function rl(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 Ua(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 Ba(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Va({id:t,label:s,value:n,onChange:a,children:r,disabled:l=!1}){return e.jsxs("label",{htmlFor:t,className:cs,children:[s,e.jsx("select",{id:t,className:Gt,value:n,onChange:i=>a(i.target.value),disabled:l,children:r})]})}function Mn({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 il({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1),[c,d]=o.useState(null),h=o.useRef(null),u=o.useRef(null),p=o.useRef(!1);o.useEffect(()=>{const x=p.current;p.current=a,a?u.current?.focus():x&&h.current?.querySelector("button")?.focus()},[a]);function g(){d(null),r(!0)}function m(){d(null),r(!1)}async function y(){i(!0),d(null);try{await n()}catch(x){d(Ct(x)),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(T,{ref:u,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:l,onClick:m,children:"Keep connected"}),e.jsx(Ye,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||l,onClick:()=>{y()},children:l?"Disconnecting…":`Disconnect ${t}`})]}),c?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:c}):null]}):e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:g,children:["Disconnect ",t]})})}function ol({id:t,label:s,options:n,synced:a,loading:r,failed:l,onRetry:i,emptyHint:c,value:d,onChange:h}){const u=n.some(x=>x.id===d),[p,g]=o.useState(!1),m=p||d!==""&&!u&&n.length>0,y=e.jsx("label",{htmlFor:t,className:cs,children:s});return r?e.jsxs("div",{children:[y,e.jsx("select",{id:t,className:Gt,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):l?e.jsxs("div",{children:[y,e.jsx("input",{id:t,required:!0,className:Gt,value:d,onChange:x=>h(x.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:Gt,value:d,onChange:x=>h(x.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":c})]}):e.jsxs("div",{children:[y,m?e.jsx("input",{id:t,required:!0,className:Gt,value:d,onChange:x=>h(x.target.value)}):e.jsxs("select",{id:t,required:!0,className:Gt,value:d,onChange:x=>h(x.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(x=>e.jsxs("option",{value:x.id,children:[x.name,x.detail?` (${x.detail})`:"",x.active?"":" — inactive"]},x.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{g(!m),h("")},children:m?"Choose from synced list":"Enter an ID manually"})]})}function Hf({projectId:t,projectName:s}){const n=Sn(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),[h,u]=o.useState(""),[p,g]=o.useState(null),[m,y]=o.useState(!1),[x,b]=o.useState(!1),[N,C]=o.useState(""),[M,k]=o.useState(""),[f,v]=o.useState(""),[S,q]=o.useState(""),[I,w]=o.useState(""),[V,F]=o.useState(!1),[W,B]=o.useState(nl),[Q,te]=o.useState(null),O=o.useRef(null),U=$e({...vu({client:H,path:{name:s}}),staleTime:pn}),se=$e({...ju({client:H,path:{name:s}}),staleTime:pn}),D=$e({...Nu({client:H,path:{name:s}}),staleTime:pn}),E=$e({...wu({client:H,path:{name:s}}),staleTime:pn}),P=E.data,Y=$e({...Su({client:H,path:{name:s},query:{limit:5}}),staleTime:pn}),re=$e({...Cu({client:H,path:{name:s},query:{limit:5}}),staleTime:pn}),ne=D.data??[],Ce=(Q?ne.find(L=>L.id===Q)??null:null)??(ne.length===1?ne[0]??null:null),J=ne.length>1&&!Ce,oe=$e({...ku({client:H,path:{name:s,contractId:Ce?.id??""}}),enabled:!!Ce,staleTime:pn}),Ne=$e({...Au({client:H,path:{name:s}}),enabled:p==="google-ads"&&U.data?.connected===!0,staleTime:0}),X=$e({...Ru({client:H,path:{name:s}}),enabled:p==="gtm"&&se.data?.connected===!0,staleTime:0}),ie=$e({...Pu({client:H,path:{name:s,accountId:f}}),enabled:p==="gtm"&&!!f,staleTime:0}),G=$e({...Iu({client:H,path:{name:s,accountId:f,containerId:S}}),enabled:p==="gtm"&&!!f&&!!S,staleTime:0}),he=Ot(Tu({client:H})),Le=Ot(Mu({client:H})),be=Ot(qu({client:H})),ee=Ot($u({client:H})),Re=Ot(Lu({client:H})),De=Ot(Eu({client:H})),qe=Ot(Du({client:H})),xe=Ot(Ou({client:H})),K=Ot(Fu({client:H}));o.useEffect(()=>{if(p!=="google-ads"||m||!U.isSuccess)return;const L=U.data.connection?.selection;C(L?.customerId??""),k(L?.loginCustomerId??""),y(!0)},[m,U.data,U.isSuccess,p]),o.useEffect(()=>{if(p!=="gtm"||x||!se.isSuccess)return;const L=se.data.selection;v(L?.accountId??""),q(L?.containerId??""),w(L?.workspaceId??""),b(!0)},[x,se.data,se.isSuccess,p]),o.useEffect(()=>{!Q||!D.data||D.data.some(L=>L.id===Q)||te(null)},[D.data,Q]);const Oe=o.useMemo(()=>{const L=Y.data?.snapshots??[],we=re.data?.snapshots??[],lt=[...L.map(bt=>({id:bt.id,provider:"google-ads",kind:bt.kind,capturedAt:bt.capturedAt})),...we.map(bt=>({id:bt.id,provider:"gtm",kind:bt.kind,capturedAt:bt.capturedAt}))].sort((bt,rs)=>rs.capturedAt.localeCompare(bt.capturedAt)).slice(0,5),Lt=[],Xt=oe.data?.googleAdsSnapshot,Qe=oe.data?.gtmSnapshot;return Xt&&Lt.push({id:Xt.id,provider:"google-ads",kind:Xt.kind,capturedAt:Xt.capturedAt}),Qe&&Lt.push({id:Qe.id,provider:"gtm",kind:Qe.kind,capturedAt:Qe.capturedAt}),{contract:oe.data?.assessment.contract??Ce,assessment:oe.data?.assessment??null,contractSelectionRequired:J,assessmentState:Ce?oe.isError?"unavailable":oe.isLoading?"loading":void 0:void 0,assessmentError:oe.isError?Ct(oe.error):null,googleAds:Bf(U.data,al(Y.data?.total??0,Y.isLoading,Y.isError,Y.error),U.isError),gtm:Qf(se.data,al(re.data?.total??0,re.isLoading,re.isError,re.error),se.isError),snapshots:lt,assessmentEvidenceSnapshots:Lt}},[Ce,J,Y.data,Y.error,Y.isError,Y.isLoading,U.data,U.isError,re.data,re.error,re.isError,re.isLoading,se.data,se.isError,oe.data,oe.error,oe.isError,oe.isLoading]),R=o.useSyncExternalStore(Ll,tr,tr),ye=Object.values(R.runs).some(L=>L.projectId===t&&(L.kind===Zs["google-ads-sync"]||L.kind===Zs["gtm-sync"])),Ke=he.isPending||Le.isPending||be.isPending||ee.isPending||Re.isPending||De.isPending||qe.isPending||xe.isPending||K.isPending||ye;async function ze(){await Promise.all([U.refetch(),se.refetch(),D.refetch(),Y.refetch(),re.refetch(),E.refetch(),Ce?oe.refetch():Promise.resolve()])}async function Je(L){await ze();for(let we=0;we<10&&!L();we+=1)await new Promise(lt=>setTimeout(lt,1500)),await ze()}function pe(){const L=document.activeElement;O.current=L instanceof HTMLElement?L:null}function ht(L){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(L);return}globalThis.setTimeout(L,0)}function Ve(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function tt(L){if(!L)return;!L.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!L.hasAttribute("tabindex")&&(L.tabIndex=-1),L.focus({preventScroll:!0})}function Wt(L,we=L){const lt=document.getElementById(L);lt instanceof HTMLDetailsElement&&(lt.open=!0);const Lt=lt?.scrollIntoView;typeof Lt=="function"&&Lt.call(lt,{behavior:Ve()?"auto":"smooth",block:"start"}),tt(document.getElementById(we)??lt)}function dt(L,we){pe(),ht(()=>Wt(L,we))}function st(){const L=O.current;O.current=null,L&&ht(()=>{L.isConnected&&L.focus({preventScroll:!0})})}function pt(){r(null),d(!1),st()}function St(){r(null),g(null),st()}function Rt(){r(null),F(!1),st()}function Ge(){r(null),g(null),d(!0),dt("google-ads-connect-panel","google-ads-connect-title")}function A(){r(null),C(""),k(""),y(!1),g("google-ads"),d(!1),dt("google-ads-selection-panel","google-ads-selection-title")}function ke(){r(null),v(""),q(""),w(""),b(!1),g("gtm"),d(!1),dt("gtm-selection-panel","gtm-selection-title")}function ue(){r(null),F(!0),dt("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function He(L,we){$l({id:L.id,projectId:L.projectId,kind:L.kind,projectLabel:s,sourceAction:we}),Ee({title:we==="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:${L.id}`,dedupeMode:"replace"})}async function Tt(){As(n),r(null);try{const L=await he.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});u(""),d(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),rl(L.authorizationUrl,()=>{ze(),i(null),st()})}catch(L){r(Ct(L))}}async function Mt(){As(n),r(null);try{const L=await Le.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."),rl(L.authorizationUrl,()=>{ze(),i(null),st()})}catch(L){r(Ct(L))}}async function ot(){if(As(n),!N){r("Select a Google Ads customer before saving.");return}r(null);try{await be.mutateAsync({path:{name:s},body:{customerId:N,...M.trim()?{loginCustomerId:M.trim()}:{}}}),g(null),st(),await Je(()=>U.data?.selectedCustomer!=null)}catch(L){r(Ct(L))}}async function Z(){if(As(n),!f||!S){r("Select a Tag Manager account and container before saving.");return}r(null);try{await ee.mutateAsync({path:{name:s},body:{accountId:f,containerId:S,...I?{workspaceId:I}:{}}}),g(null),st(),await Je(()=>se.data?.status==="connected")}catch(L){r(Ct(L))}}async function Fe(){As(n),r(null),await qe.mutateAsync({path:{name:s}}),g(null),d(!1),C(""),k(""),y(!1),i(null),await ze(),Ee({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),O.current=null,ht(()=>tt(document.getElementById("conversion-integrity-title")))}async function Ie(){As(n),r(null),await xe.mutateAsync({path:{name:s}}),g(null),v(""),q(""),w(""),b(!1),i(null),await ze(),Ee({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),O.current=null,ht(()=>tt(document.getElementById("conversion-integrity-title")))}async function Pe(){As(n),r(null);try{const L=await Re.mutateAsync({path:{name:s}});He(L,"google-ads-sync")}catch(L){r(Ct(L))}}async function qt(){As(n),r(null);try{const L=await De.mutateAsync({path:{name:s}});He(L,"gtm-sync")}catch(L){r(Ct(L))}}async function vt(){As(n),r(null);try{const L=await Promise.allSettled([Re.mutateAsync({path:{name:s}}),De.mutateAsync({path:{name:s}})]),[we,lt]=L;we.status==="fulfilled"&&He(we.value,"google-ads-sync"),lt.status==="fulfilled"&&He(lt.value,"gtm-sync");const Lt=L.find(Xt=>Xt.status==="rejected");if(Lt?.status==="rejected")throw Lt.reason}catch(L){r(Ct(L))}}async function Yt(){As(n);const L=U.data?.connection?.selection.customerId,we=se.data?.selection;if(!L||!we?.accountId||!we.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const lt=await K.mutateAsync({path:{name:s},body:zf(W,L,{accountId:we.accountId,containerId:we.containerId})});B(nl),F(!1),st(),(await D.refetch()).data?.some(Xt=>Xt.id===lt.id)&&te(lt.id)}catch(lt){r(Ct(lt))}}function nt(L){switch(L){case"connect-google-ads":Ge();return;case"connect-gtm":pe(),Mt();return;case"select-google-ads":A();return;case"select-gtm":ke();return;case"sync-google-ads":Pe();return;case"sync-gtm":qt();return;case"sync-static-evidence":vt();return;case"declare-contract":ue();return;case"review-findings":dt("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":dt("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":ze();return;case"select-contract":dt("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":oe.refetch();return;case"waiting-for-integrity":return}}const $t=Ne.data?.customers??[],Zt=X.data?.accounts??[],vs=ie.data?.containers??[],js=G.data?.workspaces??[],Ns=!!N&&!$t.some(L=>L.customerId===N),Gs=!!f&&!Zt.some(L=>L.id===f),ft=!!S&&!vs.some(L=>L.id===S),xs=!!I&&!js.some(L=>L.id===I),Ze=Ns&&Ne.isSuccess&&Ne.data.truncated===!1,Ft=Gs&&X.isSuccess&&X.data.truncated===!1,es=ft&&ie.isSuccess&&ie.data.truncated===!1,as=xs&&G.isSuccess&&G.data.truncated===!1,gs=Ft||es||as,jt=Ft?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":es?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":as?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,Pt=Ba(Ze,Ne.data,Ne.isError),ts=Ba(Ft,X.data,X.isError),Kt=Ba(es,ie.data,ie.isError),_s=Ba(as,G.data,G.isError),Nt=Ne.isError?Ct(Ne.error):null,Jt=X.isError?Ct(X.error):ie.isError?Ct(ie.error):G.isError?Ct(G.error):null,xt=p==="google-ads"?Nt:p==="gtm"?Jt:null,_=Ua("customer",Ne.data,$t.length),ae=Ua("account",X.data,Zt.length),Ae=Ua("container",ie.data,vs.length),me=Ua("draft workspace",G.data,js.length),Te=X.isError||ie.isError||G.isError&&!!I,_e=c||p!==null||V;function mt(){Ne.refetch()}function yt(){if(X.isError){X.refetch();return}if(ie.isError){ie.refetch();return}G.isError&&G.refetch()}return U.isLoading||se.isLoading||D.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(L=>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"})]},L))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):D.isError&&!D.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(D.error)]}),e.jsx(T,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{D.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Uf,{workspace:Oe,onPrimaryAction:nt,actionPending:Ke,actionError:_e?null:a,contracts:ne,selectedContractId:Ce?.id??null,onSelectContract:L=>te(L||null),contractError:D.isError?Ct(D.error):null,onRetryContracts:()=>{D.refetch()},onRetryEvidence:()=>{Promise.all([Y.refetch(),re.refetch()])},onChangeGoogleAdsSelection:A,onChangeGtmSelection:ke,onAddContract:()=>nt("declare-contract")}),l?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:l}):null,c?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:Xe(async L=>{L.preventDefault(),await Tt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:cs,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:L=>u(L.target.value),className:Gt,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:he.isPending,children:he.isPending?"Starting…":"Continue to Google"}),e.jsx(T,{type:"button",variant:"outline",onClick:pt,children:"Cancel"})]})]})]}):null,p==="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"})]})}),xt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:xt}),e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:mt,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Ze?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(Va,{id:"google-ads-customer",label:"Customer account",value:N,onChange:L=>{y(!0),C(L);const we=$t.find(lt=>lt.customerId===L);k(we?.parentCustomerId??"")},disabled:Ne.isLoading,children:[e.jsx("option",{value:"",children:Ne.isLoading?"Loading accessible customers…":"Select a customer"}),Ns?e.jsxs("option",{value:N,disabled:Ze,children:["Saved customer ",N," (",Pt,")"]}):null,$t.map(L=>e.jsx("option",{value:L.customerId,children:L.descriptiveName??`Customer ${L.customerId}`},L.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:cs,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Gt,value:M,onChange:L=>{y(!0),k(L.target.value)},placeholder:"Use only when a manager context is required"})]})]}),_?e.jsx("p",{role:"status",className:`mt-3 text-sm ${Ne.data?.truncated?"text-caution":"text-secondary"}`,children:_}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:be.isPending||Ne.isLoading||Ne.isError||Ze||!N,onClick:Xe(ot),children:be.isPending?"Saving…":"Save customer selection"}),e.jsx(T,{type:"button",variant:"outline",onClick:St,children:"Cancel"})]}),U.data?.connected?e.jsx(il,{providerLabel:"Google Ads",disabled:Ke,onDisconnect:Fe}):null]}):null,p==="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"})]})}),xt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:xt}),e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:yt,children:X.isError?"Retry account list":ie.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,jt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:jt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Va,{id:"gtm-account",label:"Account",value:f,onChange:L=>{b(!0),L!==f&&(q(""),w("")),v(L)},disabled:X.isLoading,children:[e.jsx("option",{value:"",children:X.isLoading?"Loading accounts…":"Select an account"}),Gs?e.jsxs("option",{value:f,disabled:Ft,children:["Saved account ",f," (",ts,")"]}):null,Zt.map(L=>e.jsx("option",{value:L.id,children:L.name},L.id))]}),e.jsxs(Va,{id:"gtm-container",label:"Container",value:S,onChange:L=>{b(!0),L!==S&&w(""),q(L)},disabled:!f||ie.isLoading,children:[e.jsx("option",{value:"",children:ie.isLoading?"Loading containers…":"Select a container"}),ft?e.jsxs("option",{value:S,disabled:es,children:["Saved container ",S," (",Kt,")"]}):null,vs.map(L=>e.jsx("option",{value:L.id,children:L.name},L.id))]}),e.jsxs(Va,{id:"gtm-workspace",label:"Draft workspace (optional)",value:I,onChange:L=>{b(!0),w(L)},disabled:!S||G.isLoading,children:[e.jsx("option",{value:"",children:G.isLoading?"Loading workspaces…":"No draft workspace"}),xs?e.jsxs("option",{value:I,disabled:as,children:["Saved draft workspace ",I," (",_s,")"]}):null,js.map(L=>e.jsx("option",{value:L.id,children:L.name},L.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[ae?e.jsx("p",{role:"status",className:X.data?.truncated?"text-caution":"text-secondary",children:ae}):null,Ae?e.jsx("p",{role:"status",className:ie.data?.truncated?"text-caution":"text-secondary",children:Ae}):null,me?e.jsx("p",{role:"status",className:G.data?.truncated?"text-caution":"text-secondary",children:me}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:ee.isPending||X.isLoading||ie.isLoading||G.isLoading&&!!I||Te||gs||!f||!S,onClick:Xe(Z),children:ee.isPending?"Saving…":"Save container selection"}),e.jsx(T,{type:"button",variant:"outline",onClick:St,children:"Cancel"})]}),se.data?.connected?e.jsx(il,{providerLabel:"Tag Manager",disabled:Ke,onDisconnect:Ie}):null]}):null,V?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:Xe(async L=>{L.preventDefault(),await Yt()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:cs,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Gt,value:W.name,onChange:L=>B(we=>({...we,name:L.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:cs,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Gt,value:W.eventName,onChange:L=>B(we=>({...we,eventName:L.target.value})),placeholder:"booking_complete"})]}),e.jsx(ol,{id:"contract-conversion-action",label:"Google Ads conversion action",options:P?.googleAds.conversionActions??[],synced:P?.googleAds.syncedAt!=null,loading:E.isLoading,failed:E.isError,onRetry:()=>{E.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:W.conversionActionId,onChange:L=>B(we=>({...we,conversionActionId:L}))}),e.jsx(ol,{id:"contract-gtm-tag",label:"Tag Manager tag",options:P?.gtm.tags??[],synced:P?.gtm.syncedAt!=null,loading:E.isLoading,failed:E.isError,onRetry:()=>{E.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:W.tagId,onChange:L=>B(we=>({...we,tagId:L}))})]}),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:cs,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Gt,value:W.conversionId,onChange:L=>B(we=>({...we,conversionId:L.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:cs,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Gt,value:W.conversionLabel,onChange:L=>B(we=>({...we,conversionLabel:L.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:cs,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Gt,value:W.triggerIds,onChange:L=>B(we=>({...we,triggerIds:L.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:cs,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Gt,value:W.variableIds,onChange:L=>B(we=>({...we,variableIds:L.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:cs,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Gt,value:W.campaignIds,onChange:L=>B(we=>({...we,campaignIds:L.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:cs,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Gt,value:W.productionHosts,onChange:L=>B(we=>({...we,productionHosts:L.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(Mn,{id:"contract-primary-action",checked:W.requirePrimaryAction,onChange:L=>B(we=>({...we,requirePrimaryAction:L})),children:"Google Ads action is primary"}),e.jsx(Mn,{id:"contract-biddable-goal",checked:W.requireBiddableGoal,onChange:L=>B(we=>({...we,requireBiddableGoal:L})),children:"Google Ads goal is biddable"}),e.jsx(Mn,{id:"contract-runtime-verification",checked:W.verificationRequired,onChange:L=>B(we=>({...we,verificationRequired:L})),children:"Runtime proof is required"}),e.jsx(Mn,{id:"contract-transaction-id",checked:W.requireTransactionId,onChange:L=>B(we=>({...we,requireTransactionId:L})),children:"Transaction ID is required"}),e.jsx(Mn,{id:"contract-value",checked:W.requireValue,onChange:L=>B(we=>({...we,requireValue:L})),children:"Conversion value is required"}),e.jsx(Mn,{id:"contract-currency",checked:W.requireCurrency,onChange:L=>B(we=>({...we,requireCurrency:L})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:K.isPending,children:K.isPending?"Saving…":"Save conversion contract"}),e.jsx(T,{type:"button",variant:"outline",onClick:Rt,children:"Cancel"})]})]})]}):null]})}const Wf=6e4,Yf=["7d","14d","30d"],Fi="not available",Jf='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%.',Xf="No Google Ads snapshot stored yet",Zf="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.",ey="No closed days yet",ty="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.",sy={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},Hs=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),Gr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),ny=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function qn(t,s){return t===null||!Number.isFinite(t)?Fi:s===null?ny.format(t/1e6):Yh(t,s)}function _r(t){return t===null||!Number.isFinite(t)?Fi:et(t)}function ay(t,s){return t===null||!Number.isFinite(t)?`${Fi} vs prior ${s}d`:t===0?`no change vs prior ${s}d`:`${t>0?"↑":"↓"} ${et(Math.abs(t))} vs prior ${s}d`}function ry(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function iy(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function oy(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 ly({projectName:t}){const[s,n]=o.useState("14d"),[a,r]=o.useState(()=>new Set(["costMicros","conversions"])),l=$e({...Ku({client:H,path:{name:t},query:{window:s}}),staleTime:Wf}),i=l.data,c=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Be,{text:Jf})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[At(i.startDate)," to ",At(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(mr,{windows:Yf,value:s,onChange:n,label:"Google Ads time period"})]});if(l.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[c,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(f=>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"})]},f))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(l.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",Ct(l.error)]}),e.jsx(T,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{l.refetch()},children:"Retry performance"})]});const{totals:d,daily:h,campaigns:u,comparison:p,comparisonUnavailableReason:g,source:m}=i;if(!m){const f=g==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:f?ey:Xf}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:f?ty:Zf})]})]})}const y=m.currencyCode,x=m.campaignsInInventory>0&&m.campaignsQueried<m.campaignsInInventory?{queried:m.campaignsQueried,inInventory:m.campaignsInInventory}:null,b=d.costMicros>0&&d.conversions===0,N=[{key:"spend",comparable:!0,label:"Spend",value:qn(d.costMicros,y),change:p?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:Gr.format(d.conversions),change:p?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:b?"no conversions":qn(d.costPerConversionMicros,y),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:_r(d.conversionRate),change:p?.change.conversionRate??null,direction:"up-good",seriesKey:null}],C=[{key:"clicks",label:"Clicks",value:Hs.format(d.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:Hs.format(d.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:_r(d.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:qn(d.cpcMicros,y),seriesKey:null}],M={costMicros:{label:"Spend",color:it[1],axisId:"spend",formatValue:f=>qn(f,y)},conversions:{label:"Conversions",color:it[0],axisId:"conversions",formatValue:f=>Gr.format(f)},clicks:{label:"Clicks",color:it[2],axisId:"clicks",formatValue:f=>Hs.format(f)},impressions:{label:"Impressions",color:it[3],axisId:"impressions",formatValue:f=>Hs.format(f)}},k=[...a].map(f=>({dataKey:f,...M[f]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,x!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",Hs.format(x.queried)," of"," ",Hs.format(x.inInventory)," campaigns, so they are a subset of the account."]}):null,m.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,!p&&g==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:sy["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:N.map(f=>{const v=f.seriesKey!==null&&a.has(f.seriesKey),S=v&&a.size===1,q=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[f.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?M[f.seriesKey].color:"var(--color-mono-600)"}}):null,f.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:f.value}),p&&f.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${oy(f.change,f.direction)}`,children:ay(f.change,p.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:f.comparable?`no prior ${s} period stored`:" "})]});return f.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:q},f.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:S,onClick:()=>r(I=>{const w=new Set(I);return w.has(f.seriesKey)?w.delete(f.seriesKey):w.add(f.seriesKey),w.size===0?I:w}),className:`rounded-md border px-3 py-2 text-left transition-colors ${v?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${S?"cursor-default":""}`,children:q},f.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:C.map(f=>{const v=f.seriesKey!==null&&a.has(f.seriesKey),S=v&&a.size===1,q=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[f.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?M[f.seriesKey].color:"var(--color-mono-600)"}}):null,f.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:f.value})]});return f.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:q},f.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:S,onClick:()=>r(I=>{const w=new Set(I);return w.has(f.seriesKey)?w.delete(f.seriesKey):w.add(f.seriesKey),w.size===0?I:w}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${S?"cursor-default":"hover:bg-surface-hover"}`,children:q},f.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Zl,{data:h,xKey:"date",series:k,xTickFormatter:Nn,labelFormatter:At}),e.jsx("ul",{className:"sr-only",children:h.map(f=>e.jsxs("li",{children:[At(f.date),":"," ",k.map(v=>`${v.label} ${M[v.dataKey].formatValue(f[v.dataKey])}`).join(", "),f.origin==="filled"?", no delivery reported":""]},f.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(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:f.name??f.campaignId,children:f.name??e.jsx("span",{className:"font-mono text-secondary",children:f.campaignId})}),e.jsx("td",{children:e.jsx(je,{tone:ry(f.status),children:iy(f.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Hs.format(f.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Hs.format(f.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:qn(f.totals.costMicros,y)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Gr.format(f.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:_r(f.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:f.totals.costMicros>0&&f.totals.conversions===0?e.jsx(je,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:qn(f.totals.costPerConversionMicros,y)})})]},f.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",ba(Bt(m.capturedAt))," · ","customer ",m.customerId," · ","latest closed day ",At(m.asOfDate),m.openDate?e.jsxs(e.Fragment,{children:[" · ",At(m.openDate)," still open, excluded"]}):null,m.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",m.timeZone]}):null]})]})]})}const Ur=20,Es=50,cy=50,dy=50;function Ki(t){return t==="viewer"}function Gi(t){return t?.status==="unavailable"}function Oc(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Fc(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 Qa(t,s,n){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 uy(t,s,n){if(t.kind==="all")return`all ${n} ${n===1?"Property":"Properties"}`;if(t.kind==="specific")return n===1?"1 Property":`${n} Properties`;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 Br(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 ll(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function cl(t){return t==="matched"?"Matched":t==="duplicate"?"Duplicate":t==="ambiguous"?"Ambiguous":t==="proposed"?"Property needs review":t==="excluded"?"Property excluded":t==="invalid"?"Invalid row":"Not matched"}function za(t){return t.status==="duplicate"&&t.duplicateOfRow?`Duplicates row ${t.duplicateOfRow}.`:t.status==="matched"?null:t.reason==="group-label-ambiguous"?`More than one group matches “${t.group}”. Rename duplicate groups, then preview again.`:t.status==="ambiguous"?"More than one Property matches this row. Add an exact URL to choose one.":t.status==="unmatched"?"No included Property matches this row.":t.reason==="group-key-conflict"?`The group name “${t.group}” conflicts with an existing setup identity. Rename the group, then preview again.`:t.status==="invalid"?"Check the Property, group, and optional URL fields.":t.status==="proposed"?"Review this proposed Property before importing it.":t.status==="excluded"?"Include this Property before importing it.":t.reason??null}function xi(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Vr(t){return xi(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function gi({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[l,i]=o.useState(""),[c,d]=o.useState(!1),h=l.trim().toLocaleLowerCase(),u=h?t.filter(y=>y.label.toLocaleLowerCase().includes(h)):t,p=c?u:u.slice(0,cy),g=p.length<u.length;function m(){const y=new Set([...s,...p.map(x=>x.id)]);n(t.filter(x=>y.has(x.id)).map(x=>x.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(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p.length===0,onClick:m,children:"Select all shown"}),e.jsx(T,{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 ",p.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:p.map(y=>{const x=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:x,type:"checkbox",onChange:b=>n(Oc(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)})}),g?e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function _i(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(je,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Ui({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(je,{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 my({value:t}){const[s,n]=o.useState(0),[a,r]=o.useState(0),[l,i]=o.useState(null),c=t.preview,d=c?.counts.needsAttention??0,h=c?.rows.filter(S=>S.status==="matched")??[],u=c?.rows??[],p=u.filter(S=>S.status!=="matched"),g=Math.max(1,Math.ceil(u.length/Es)),m=Math.min(s,g-1),y=u.slice(m*Es,(m+1)*Es),x=Math.max(1,Math.ceil(p.length/Es)),b=Math.min(a,x-1),N=p.slice(b*Es,(b+1)*Es),C=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,M=h.length>0&&!t.isApplying,k=c!==null&&l===c.previewChecksum,f=p.length>0&&b===x-1;o.useEffect(()=>{n(0),r(0),i(null)},[c?.previewChecksum]);async function v(S){if(S)try{t.onCsvChange(await S.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:S=>{v(S.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:S=>t.onCsvChange(S.currentTarget.value),placeholder:`property,group,url
3
- Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!C,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),c?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[c.counts.matchedRows," matched · ",c.counts.groupsReady," group",c.counts.groupsReady===1?"":"s"," ready",d>0?` · ${d} need${d===1?"s":""} attention`:""]}),c.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:c.groupChanges.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.label}),e.jsx("td",{className:"text-secondary",children:S.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:S.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[S.addedTargetKeys.length,S.unchangedTargetKeys.length>0?` · ${S.unchangedTargetKeys.length} already members`:""]})]},S.groupKey))})]})}):null,c.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",c.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:y.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(je,{tone:ll(S.status),children:cl(S.status)}),za(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:za(S)}):null]})]},S.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",m+1," of ",g," · ",c.rows.length," rows"]}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:m===0,onClick:()=>n(S=>Math.max(0,S-1)),children:"Previous 50 rows"}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:m===g-1,onClick:()=>n(S=>Math.min(g-1,S+1)),children:"Next 50 rows"})]})]}):null,d>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",d," row",d===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:N.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(je,{tone:ll(S.status),children:cl(S.status)}),za(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:za(S)}):null]})]},S.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 ",x]}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===0,onClick:()=>r(S=>Math.max(0,S-1)),children:"Previous 50 exceptions"}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===x-1,onClick:()=>r(S=>Math.min(x-1,S+1)),children:"Review next 50 exceptions"})]}),e.jsxs("label",{className:"mt-3 flex min-h-11 max-w-xl items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:k,disabled:t.isApplying||!f,onChange:S=>i(S.currentTarget.checked?c.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",d," row",d===1?"":"s"," will be skipped."]}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!M||!k,onClick:()=>{t.onApply(h.map(S=>S.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(T,{type:"button",className:"mt-3 min-h-11",disabled:!M,onClick:()=>{t.onApply(h.map(S=>S.dataRow))},children:t.isApplying?"Creating groups…":`Create ${c.counts.groupsReady} group${c.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const hy="—";function py({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:l=!1,isBusy:i=!1,canContinue:c=!0,onSelectedQueryIdsChange:d,onApplySelectedQueries:h,onClearQueryAssignments:u,onRemoveQuery:p,onCreateQueries:g,onCreateAndPairQuestions:m,isCreatingQueries:y=!1,createQueriesError:x=null,onManageProjectQueries:b,groups:N,audience:C,onAudienceChange:M,assignmentImpact:k=null,isPreviewingAssignmentImpact:f=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:S,assignmentNotice:q=null,onReplaceAssignments:I,isReplacingAssignments:w=!1,onBack:V,onContinue:F}){const[W,B]=o.useState(""),[Q,te]=o.useState(!1),[O,U]=o.useState(!1),[se,D]=o.useState(""),[E,P]=o.useState(""),[Y,re]=o.useState(null);if(Gi(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Ui,{message:s.message})});const ne=Ki(t),de=C,Ce=M,J=Qa(de,n,N),oe=J.length,Ne=oe>0&&r.length>0&&!l&&!i&&!f&&k!==null&&v===null,X=u??p,ie=W.trim().toLocaleLowerCase(),G=ie?a.filter(R=>Vr(R).toLocaleLowerCase().includes(ie)):a,he=G.filter(R=>(R.propertyIds?.length??0)===0),Le=O?he:G,be=Q?Le:Le.slice(0,dy),ee=be.filter(R=>!xi(R)),Re=[...new Set(se.split(`
4
- `).map(R=>R.trim()).filter(Boolean))],De=[...E.matchAll(/\{([a-z][\w-]*)\}/gi)].map(R=>R[1]),qe=n.filter(R=>J.includes(R.id)),xe=De.length===0||E.trim()===""?[]:qe.map(R=>({propertyId:R.id,text:De.reduce((ye,Ke)=>ye.replaceAll(`{${Ke}}`,R.label),E.trim())})),K=[...new Set(xe.map(R=>R.text))];function Oe(){const R=new Set([...r,...ee.map(ye=>ye.id)]);d(a.filter(ye=>R.has(ye.id)).map(ye=>ye.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 Properties."})]})}),ne?e.jsx(_i,{}):null,ne?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:de.kind==="all"?"all":de.kind==="specific"?"specific":`group:${de.groupIds[0]??""}`,onChange:R=>{const ye=R.currentTarget.value;ye==="all"?Ce({kind:"all"}):ye==="specific"?Ce({kind:"specific",propertyIds:[]}):ye.startsWith("group:")&&Ce({kind:"groups",groupIds:[ye.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.jsxs("option",{value:"all",children:["All Properties · ",n.length]}),N.length>0?e.jsx("optgroup",{label:"Groups",children:N.map(R=>{const ye=Qa({kind:"groups",groupIds:[R.id]},n,N).length;return e.jsx("option",{value:`group:${R.id}`,disabled:ye===0,children:Br(R,n)},R.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),de.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:de.groupIds.map(R=>{const ye=N.find(Ke=>Ke.id===R);return ye?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:[Br(ye,n),e.jsx("button",{type:"button","aria-label":`Remove ${ye.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 Ke=de.groupIds.filter(ze=>ze!==ye.id);Ce(Ke.length>0?{kind:"groups",groupIds:Ke}:{kind:"all"})},children:"×"})]},ye.id):null})}),N.some(R=>!de.groupIds.includes(R.id)&&Qa({kind:"groups",groupIds:[R.id]},n,N).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:R=>{R.currentTarget.value&&Ce({kind:"groups",groupIds:[...de.groupIds,R.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"}),N.filter(R=>!de.groupIds.includes(R.id)).map(R=>{const ye=Qa({kind:"groups",groupIds:[R.id]},n,N).length;return e.jsx("option",{value:R.id,disabled:ye===0,children:Br(R,n)},R.id)})]})]}):null,oe===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,de.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(gi,{legend:"Specific Properties",properties:n,selectedPropertyIds:de.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:R=>{Ce({kind:"specific",propertyIds:R})}})}):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."})]}),ne||!g?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:se,onChange:R=>D(R.currentTarget.value),placeholder:`best apartments in dallas
5
- luxury apartments atlanta
6
- pet friendly apartments austin`}),x?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:x}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Re.length===0||y||i,onClick:()=>{Promise.resolve(g(Re)).then(()=>D(""),()=>{})},children:y?"Adding…":`Add ${Re.length||""} ${Re.length===1?"query":"queries"}`.replace(" "," ")}),b?e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:b,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:E,onChange:R=>P(R.target.value),placeholder:"apartments near {property}"}),E.trim()===""?null:De.length===0?e.jsxs("p",{className:"mt-2 text-sm text-caution",children:["Add ","{property}"," to the pattern, or use the box above for a single query."]}):qe.length===0?e.jsx("p",{className:"mt-2 text-sm text-caution",children:"Select at least one Property to write queries for."}):e.jsxs("div",{className:"mt-2 rounded-md border border-base bg-bg-elevated p-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:[K.length," ",K.length===1?"query":"queries",", one per selected Property:"]}),e.jsx("ul",{className:"mt-1 mb-0 list-none space-y-0.5 p-0",children:K.slice(0,3).map(R=>e.jsx("li",{className:"text-sm text-strong",children:R},R))}),K.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",K.length-3," more"]}):null]}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:xe.length===0||y||i||!m,onClick:()=>{m&&Promise.resolve(m(xe)).then(()=>P(""),()=>{})},children:y?"Adding…":`Add ${xe.length||""} ${xe.length===1?"query":"queries"}`.replace(" "," ")}),xe.length>0?e.jsxs("p",{className:"mt-2 mb-0 text-sm text-secondary",children:["Each query is measured on the one Property it names, so this adds"," ",xe.length," assignment",xe.length===1?"":"s","."]}):null]})]})]}),ne?null:e.jsx("div",{className:"space-y-3 border-y border-default py-4",children:a.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:ee.length===0,onClick:Oe,children:"Select all shown queries"}),e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>d([]),children:"Clear query selection"}),e.jsx(T,{type:"button",size:"sm",className:"min-h-11",disabled:!Ne,onClick:()=>{h({queryIds:r,propertyIds:J,...de.kind==="groups"?{groupIds:de.groupIds}:{}})},children:l?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${uy(de,N,oe)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[f?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,k?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",k.assignmentCount," Property assignment",k.assignmentCount===1?"":"s"," · ",k.addedAssignments," new, ",k.alreadyPresentAssignments," already assigned"," · ",k.fullRunProviderCalls," provider request",k.fullRunProviderCalls===1?"":"s"," per full run"," · ",k.addedProviderCalls," new",de.kind==="groups"?` · ${k.resolvedPropertyCount} unique ${k.resolvedPropertyCount===1?"Property":"Properties"}${k.overlapCount>0?`, ${k.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):v?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:v}),S?e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:S,children:"Retry impact"}):null,V?e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:V,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",oe," Properties = ",r.length*oe," assignments"]})]}),q?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:q}):null]})}),a.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search queries"}),e.jsx("input",{type:"search",value:W,onChange:R=>{B(R.currentTarget.value),te(!1)},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400",placeholder:"Query text"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:["Showing ",be.length," of ",Le.length," queries,"," ",G.length-he.length," of ",G.length," applied"]}),ne||he.length===0?null:e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{U(R=>!R),te(!1)},children:O?"Show all queries":`Show the ${he.length} not applied`})]})]}):null,be.length>0?e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[ne?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),ne?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:be.map(R=>{const ye=xi(R),Ke=Vr(R),ze=r.includes(R.id),Je=(R.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[ne?null:ye?e.jsx("td",{"aria-hidden":"true"}):e.jsx("td",{className:"p-0",children:e.jsx("label",{className:"flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{"aria-label":`Select query ${Ke}`,checked:ze,type:"checkbox",onChange:pe=>d(Oc(r,R.id,pe.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:Ke})}),e.jsx("td",{className:"text-secondary",children:Fc(R.propertyIds??[],n)}),ne?null:e.jsx("td",{className:"text-right",children:Je?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[I?e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||w,onClick:()=>re({queryId:R.id,propertyIds:[...R.propertyIds??[]]}),"aria-label":`Replace query assignments for ${Ke}`,children:"Replace assignments"}):null,e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{X(R.id)},"aria-label":`Clear query assignments for ${Ke}`,children:"Clear assignments"})]}):null})]},R.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,ne||!Y?null:(()=>{const R=a.find(ze=>ze.id===Y.queryId),ye=R?Vr(R):"this query",Ke=Y.propertyIds.filter(ze=>n.some(Je=>Je.id===ze));return e.jsxs("section",{"aria-labelledby":"advanced-measurement-replace-assignments-title",className:"border-y border-default py-4",children:[e.jsx("h4",{id:"advanced-measurement-replace-assignments-title",className:"text-sm font-medium text-heading",children:"Replace assigned Properties"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:["This replaces every Property assigned to “",ye,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(gi,{legend:"Properties for this query",properties:n,selectedPropertyIds:Ke,onSelectedPropertyIdsChange:ze=>re(Je=>Je&&{...Je,propertyIds:[...ze]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:w||i,onClick:()=>re(null),children:"Keep current assignments"}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ke.length===0||w||i||!I,onClick:()=>{I&&Promise.resolve(I({queryId:Y.queryId,propertyIds:Ke}))},children:w?"Replacing assignments…":`Replace with ${Ke.length} ${Ke.length===1?"Property":"Properties"}`})]})]})})(),be.length<Le.length?e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>te(!0),children:"Show all queries"}):null,ne?null:e.jsxs(e.Fragment,{children:[c?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${V?"justify-between":"justify-end"}`,children:[V?e.jsx(T,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:V,children:"Back"}):null,e.jsx(T,{type:"button",variant:Ne?"outline":"default",className:"min-h-11",disabled:!c||i,onClick:F,children:"Continue"})]})]})]})}function xy({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:l=!1,onGroupDraftChange:i,onSaveGroup:c,onEditGroup:d,onRemoveGroup:h,onClearGroupDraft:u,membershipImport:p,onBack:g,onContinue:m}){if(Gi(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(Ui,{message:s.message})});const y=Ki(t),x=r.name.trim().length>0&&r.propertyIds.length>0&&!l,b=n.filter(k=>r.propertyIds.includes(k.id)).length,N=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,C=!y&&(d!==void 0||h!==void 0);function M(){if(u){u();return}i({name:"",propertyIds:[],competitorDomains:""})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-groups-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-groups-title",children:"Groups"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Use groups to assign queries by market and compare competitors."})]})}),y?e.jsx(_i,{}):null,y||!p?null:e.jsx(my,{value:p}),y?null:e.jsxs("div",{className:"space-y-4 border-y border-default py-4",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Group name"}),e.jsx("input",{"aria-label":"Group name",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.name,onChange:k=>i({...r,name:k.currentTarget.value}),placeholder:"Waterfront venues"})]}),e.jsxs("details",{children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:[b," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(gi,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:k=>i({...r,propertyIds:k})})})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Competitor domains"}),e.jsx("input",{"aria-label":"Competitor domains",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.competitorDomains,onChange:k=>i({...r,competitorDomains:k.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!x,onClick:()=>{c(r)},children:l?"Saving group…":"Save group"}),e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!N,onClick:M,children:"Clear form"}),e.jsx("p",{className:"text-sm text-secondary",children:"Competitor domains are used only in this group's competitor report. Membership changes affect future assignments only."})]}),N?e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Save this group or clear the form before continuing."}):null]}),e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Competitors"}),C?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(k=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:k.name}),e.jsx("td",{className:"text-secondary",children:Fc(k.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:k.competitors.length>0?k.competitors.join(", "):"None"}),C?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[d?e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${k.name}`,onClick:()=>d(k),children:"Edit"}):null,h?e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${k.name}`,onClick:()=>{h(k.id)},children:"Remove"}):null]})}):null]},k.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,y?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${g?"justify-between":"justify-end"}`,children:[g?e.jsx(T,{type:"button",variant:"outline",className:"min-h-11",onClick:g,children:"Back"}):null,e.jsx(T,{type:"button",className:"min-h-11",disabled:N,onClick:m,children:a.length===0&&!N?"Continue without groups":"Continue"})]})]})}function gy({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:l,onReviewChanges:i,isReviewing:c=!1,canReviewChanges:d=!0,reviewedChanges:h,reviewChangesError:u,canPublish:p,isPublishing:g=!1,onPublish:m}){const[y,x]=o.useState(Ur),[b,N]=o.useState(Ur),[C,M]=o.useState(Ur);if(Gi(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(Ui,{message:s.message})});const k=Ki(t),f=r?.items??[],v=r?.coverageItems??[],S=f.slice(0,y),q=v.slice(0,b),I=a.slice(0,C),w=i!==void 0,V=h!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),k?e.jsx(_i,{}):null,r?e.jsx("section",{"aria-labelledby":"advanced-measurement-sitemap-review-title",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:e.jsxs("div",{className:"max-w-2xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{id:"advanced-measurement-sitemap-review-title",className:"text-sm font-medium text-heading",children:"Sitemap changes need review"}),r.exceptionCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.exceptionCount," sitemap ",r.exceptionCount===1?"entry needs":"entries need"," review."]}):null,r.coverageReviewCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.coverageReviewCount," ",r.coverageReviewCount===1?"Property has":"Properties have"," URL coverage changes."]}):null]}),r.exceptionCount>0?e.jsxs("details",{className:"border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["URLs not added to Properties (",r.exceptionCount,")"]}),f.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:S.map(F=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:F.url}),e.jsx("p",{className:"mt-1 text-secondary",children:F.reason})]},`${F.url}-${F.reason}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected sitemap URLs before confirming."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",S.length," of ",f.length]}),S.length<f.length?e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>x(F=>F+Es),children:"Show next 50 URLs"}):null]})]}):null,k?e.jsx("p",{className:"text-sm text-secondary",children:"An editor must finish this review before publishing."}):e.jsxs(e.Fragment,{children:[r.coverageReviewCount>0?e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"For changed Property URLs"}),e.jsxs("p",{className:"text-sm text-secondary",children:["This choice applies to all ",r.coverageReviewCount," changed ",r.coverageReviewCount===1?"Property":"Properties","."]}),e.jsxs("details",{className:"border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review Property URL changes (",r.coverageReviewCount,")"]}),q.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[q.map(F=>e.jsxs("section",{"aria-label":`${F.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:F.property}),e.jsxs("div",{className:"mt-2 grid gap-3 text-sm md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Saved URLs"}),e.jsx("ul",{className:"mt-1 space-y-1",children:F.savedUrls.map(W=>e.jsx("li",{className:"break-all text-secondary",children:W},W))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),F.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:F.currentSitemapUrls.map(W=>e.jsx("li",{className:"break-all text-secondary",children:W},W))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},F.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",q.length," of ",v.length]}),q.length<v.length?e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>N(F=>F+Es),children:"Show next 50 URL changes"}):null]})]}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected Properties before confirming."})]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="keep-existing",onChange:()=>r.onCoverageResolutionChange("keep-existing")}),"Keep existing Property URLs"]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="replace-with-imported",onChange:()=>r.onCoverageResolutionChange("replace-with-imported")}),"Use current sitemap URLs"]})]}):null,e.jsx(T,{type:"button",className:"min-h-11",onClick:()=>{r.onResolve()},children:"Confirm sitemap changes"})]})]})}):null,e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Groups"}),e.jsx("th",{children:"Assignments"}),e.jsx("th",{children:"Provider requests / run"})]})}),e.jsx("tbody",{children:e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-heading",children:n.properties}),e.jsx("td",{className:"tabular-nums text-heading",children:n.queries}),e.jsx("td",{className:"tabular-nums text-heading",children:n.groups}),e.jsx("td",{className:"tabular-nums text-heading",children:n.assignments??"—"}),e.jsx("td",{className:"tabular-nums text-heading",children:n.providerCalls??hy})]})})]})}),n.providerCalls===void 0?e.jsx("p",{className:"supporting-copy",children:"Review changes to see how many provider requests one run will make."}):null,n.assignments!==void 0&&n.assignments>n.queries?e.jsxs("p",{className:"supporting-copy",children:[n.queries," ",n.queries===1?"query":"queries"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a query aimed at a market is measured on every Property in it."]}):null,h?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:h.title}),h.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:h.items.map((F,W)=>e.jsx("li",{children:F},`${F}-${W}`))}):null]}):null,e.jsxs("section",{"aria-labelledby":"advanced-measurement-flagged-exceptions-title",className:"space-y-3",children:[e.jsx("h4",{id:"advanced-measurement-flagged-exceptions-title",className:"text-sm font-medium text-heading",children:"Flagged exceptions"}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No flagged exceptions."}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"divide-y divide-default border-y border-default",children:I.map(F=>e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-heading",children:F.title}),F.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:F.detail}):null]}),e.jsx(je,{tone:F.tone??"caution",children:"Needs attention"})]},F.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",I.length," of ",a.length]}),I.length<a.length?e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>M(F=>F+Es),children:"Show next 50 exceptions"}):null]})]})]}),k?null:e.jsxs(e.Fragment,{children:[w&&u?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:u}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${l?"justify-between":"justify-end"}`,children:[l?e.jsx(T,{type:"button",variant:"outline",className:"min-h-11",onClick:l,children:"Back"}):null,i!==void 0&&!V?e.jsx(T,{type:"button",className:"min-h-11",disabled:c||!d,onClick:()=>{i()},children:c?"Reviewing changes…":"Review changes"}):e.jsx(T,{type:"button",className:"min-h-11",disabled:!p||g,onClick:()=>{m()},children:g?"Publishing setup…":"Publish setup"})]})]})]})}const fy={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function yy(t){return t.trim().toLocaleLowerCase()}function by(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function vy({property:t}){const s=t.urls??[t.url];return s.length<=1?e.jsx("span",{children:s[0]??"No URL"}):e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-xs font-medium text-primary",children:[s.length," URLs"]}),e.jsx("ul",{className:"mt-2 space-y-1",children:s.map(n=>e.jsx("li",{className:"break-all font-mono text-xs text-secondary",children:n},n))})]})}function jy({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const l=!t||r==="reviewing",i=l||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function c(d,h){n({...s,[d]:h})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":r==="reviewing",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-import-heading",className:"text-lg font-semibold text-heading",children:"Import Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review sitemap entries before choosing the Properties to measure."})]}),t?null:e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm text-secondary",children:[e.jsx(je,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:d=>{d.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:l,onChange:d=>c("sitemapUrl",d.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:l,onChange:d=>c("examplePropertyUrl",d.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:l,onChange:d=>c("preferredHost",d.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:l,onChange:d=>c("propertyPathPattern",d.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:l,onChange:d=>c("additionalHost",d.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:l,onChange:d=>c("additionalPathPattern",d.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:l,onChange:d=>c("excludedPaths",d.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(T,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function Ny({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:l,onSelectedPropertyIdsChange:i,onContinue:c,isContinuing:d=!1,onRetryProperties:h,onReturnToImport:u,maxVisibleProperties:p,onShowAllProperties:g}){const m=yy(a),y=s.filter(I=>by(I,m)),x=Math.max(1,p??y.length),b=y.slice(0,x),N=new Set(l),C=s.filter(I=>N.has(I.id)).map(I=>I.id),M=b.length<y.length;function k(I){const w=new Set(I);i(s.filter(V=>w.has(V.id)).map(V=>V.id))}function f(I,w){if(!t||d)return;const V=new Set(C);w?V.add(I):V.delete(I),k(V)}function v(){!t||d||k([...C,...b.map(I=>I.id)])}function S(){!t||d||i([])}function q(){!t||d||C.length===0||c(C)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||d,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):null,n==="ready"&&s.length>0?e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:a,disabled:d,onChange:I=>r(I.target.value),className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),t?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:d,onClick:v,children:"Select all shown"}),e.jsx(T,{type:"button",variant:"ghost",size:"sm",disabled:d||C.length===0,onClick:S,children:"Clear selection"})]}):null]}),y.length===0?e.jsxs("div",{className:"mt-4 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties match this search."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Clear the search or review the sitemap again."}),e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",b.length," of ",y.length," Properties"]}),e.jsxs("p",{children:[C.length," of ",s.length," selected"]})]}),e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"w-full min-w-150 text-left text-sm","aria-label":"Properties to review",children:[e.jsx("thead",{className:"bg-surface-subtle text-xs font-medium uppercase tracking-wide text-secondary",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-3 py-2",children:"Property"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"URL"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"State"}),t?e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Include"}):null]})}),e.jsx("tbody",{children:b.map(I=>{const w=fy[I.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:I.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(vy,{property:I})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(je,{tone:w.tone,children:w.label})}),t?e.jsx("td",{className:"p-0 text-right",children:e.jsx("label",{className:"ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{type:"checkbox","aria-label":`Select ${I.name}`,checked:C.includes(I.id),disabled:d,onChange:V=>f(I.id,V.target.checked),className:"size-6 accent-accent"})})}):null]},I.id)})})]})}),M&&g?e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:d,onClick:g,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(T,{type:"button",variant:"ghost",disabled:d,onClick:u,children:"Back"}),e.jsx(T,{type:"button",disabled:d||C.length===0,onClick:q,children:d?"Saving Properties…":"Continue"})]}):null]}):null]})}function wy(t){return t.activeStep==="import"?e.jsx(jy,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(Ny,{...t})}const Sy=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function Cy({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:l}){const i=o.useRef(null),c=o.useRef(null),d=o.useRef(null),h=o.useRef(null),u=o.useRef(!1),[p,g]=o.useState(!1);return o.useEffect(()=>{s||g(!1)},[s]),o.useEffect(()=>{const m=u.current;u.current=p,p?d.current?.focus():m&&h.current?.focus()},[p]),o.useEffect(()=>{const m=i.current;if(i.current=t,m===null||m===t)return;const y=c.current?.querySelector('h1, h2, h3, [role="heading"]');y&&(y.tabIndex=-1,y.focus())},[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 w-full sm:flex-1",children:[e.jsx("h2",{children:"Advanced measurement setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties and queries you want to measure."})]}),s?e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end",children:[e.jsx(je,{tone:"caution",children:"Unpublished changes"}),n&&a?p?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",role:"group","aria-label":"Confirm discard",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Discard all unpublished changes?"}),e.jsx(T,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>g(!1),children:"Keep editing"}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(T,{ref:h,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>g(!0),children:"Discard changes"}):null]}):null]}),e.jsx("div",{role:"group","aria-label":"Advanced measurement setup progress",className:"overflow-x-auto border-b border-default",children:e.jsx("ol",{className:"flex min-w-max gap-6",children:Sy.map(m=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===m.id?"step":void 0,onClick:()=>r(m.id),className:`block min-h-11 border-b-2 bg-transparent px-1 py-3 text-left text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${t===m.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:m.label}):e.jsx("span",{"aria-current":t===m.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===m.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:m.label})},m.id))})}),e.jsx("div",{ref:c,children:l})]})}function ky(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(wy,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(py,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(xy,{...t.groups,access:s}):"review"in t?e.jsx(gy,{...t.review,access:s}):null}function Ha(t){return e.jsx(Cy,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:ky(t)})}function Kc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Qt(t){return{"If-Match":t,"Idempotency-Key":Kc()}}function xn(t){return t instanceof Gn&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function ls(t,s){return t instanceof Gn?s:(t instanceof Error?t.message.trim():"")||s}function Ay(t){const s="Could not calculate assignment impact.";if(!(t instanceof Gn)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const Ry={loadSetup:t=>wt(()=>lm({client:H,path:{name:t}})),loadDraft:t=>wt(()=>om({client:H,path:{name:t}})),createDraft:(t,s)=>wt(()=>im({client:H,path:{name:t},headers:{"Idempotency-Key":Kc()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>wt(()=>rm({client:H,path:{name:t},headers:Qt(s),body:n})),applySitemapSelection:(t,s,n,a)=>wt(()=>am({client:H,path:{name:t},headers:Qt(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>wt(()=>nm({client:H,path:{name:t},body:s})),applyAssignments:(t,s,n)=>wt(()=>sm({client:H,path:{name:t},headers:Qt(s),body:n})),replaceAssignments:(t,s,n)=>wt(()=>tm({client:H,path:{name:t},headers:Qt(s),body:n})),applyPairedAssignments:(t,s,n)=>wt(()=>em({client:H,path:{name:t},headers:Qt(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>wt(()=>Zu({client:H,path:{name:t},headers:Qt(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>wt(()=>Xu({client:H,path:{name:t},headers:Qt(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>wt(()=>Ju({client:H,path:{name:t},headers:Qt(s),body:{target:n}})),upsertGroup:(t,s,n)=>wt(()=>Yu({client:H,path:{name:t},headers:Qt(s),body:{group:n}})),removeGroup:(t,s,n)=>wt(()=>Wu({client:H,path:{name:t},headers:Qt(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>wt(()=>Hu({client:H,path:{name:t},headers:Qt(s),body:n})),removeCompetitor:(t,s,n,a)=>wt(()=>zu({client:H,path:{name:t},headers:Qt(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>wt(()=>Qu({client:H,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>wt(()=>Vu({client:H,path:{name:t},headers:Qt(s),body:n})),compilePreview:t=>wt(()=>Bu({client:H,path:{name:t}})),diffPreview:t=>wt(()=>Uu({client:H,path:{name:t}})),publish:(t,s,n)=>wt(()=>_u({client:H,path:{name:t},headers:Qt(s),body:n})),discard:(t,s)=>wt(()=>Gu({client:H,path:{name:t},headers:Qt(s)}))},dl={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},na={name:"",propertyIds:[],competitorDomains:""},ul=50;function oa(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Py(t){const s=t.trim();if(!s)throw new Error("Add a sitemap URL.");let n;try{n=new URL(s.includes("://")?s:`https://${s}`)}catch{throw new Error("Sitemap URL must be a valid web address.")}return(n.pathname===""||n.pathname==="/")&&(n.pathname="/sitemap.xml"),n.toString()}function ml(t){const s=t.propertyPathPattern.trim();if(s){const r=(s.startsWith("/")?s:`/${s}`).split("/").slice(1);if(r.filter(i=>i==="*"||i==="{slug}").length!==1||r.some(i=>i.includes("*")&&i!=="*"))throw new Error("Property URL pattern must contain exactly one * or {slug} segment.");return`/${r.map(i=>i==="*"?"{slug}":i).join("/")}`}const n=t.examplePropertyUrl.trim();if(!n)throw new Error("Add one example Property page so Canonry can identify the matching URLs.");try{const a=new URL(n).pathname.split("/").filter(Boolean);if(a.length===0)throw new Error;return a[a.length-1]="{slug}",`/${a.join("/")}`}catch{throw new Error("Example Property page must be a valid web address.")}}function Iy(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,c=i.startsWith("*"),d=i.endsWith("*"),h=i.slice(c?1:0,d?-1:void 0).trim();if(!h)throw new Error("Ignored URL patterns must include text besides *.");const u=c&&d?"contains":c?"suffix":d?"prefix":"exact",p=`${u}:${h}`;n.has(p)||(n.add(p),s.push({kind:u,value:h}))}return s}function Ty(t){const s=Py(t.sitemapUrl),n=t.examplePropertyUrl.trim()?oa(t.examplePropertyUrl):null,a=oa(t.preferredHost)??n??oa(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=oa(t.additionalHost),l=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(l!==i||l&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const c=Iy(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:ml(t)},...r?{aliases:[{host:r,pathTemplate:ml({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...c.length>0?{excludedSlugPatterns:c}:{}}}}function My(t){return!t||t.authoring.targets.length===0?"import":t.authoring.targets.some(s=>s.status==="proposed")?"properties":t.authoring.assignments.length===0?"groups":t.baseActiveRevision===null?"review":"properties"}function qy(t,s){return!t||t.authoring.targets.length===0?"import":!t.authoring.targets.some(n=>n.status!=="excluded")||t.authoring.targets.some(n=>n.status==="proposed")?"properties":t.authoring.assignments.length===0&&s==="review"?"groups":s}function hl(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function $y(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Qr(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function fi(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function pl(t){return oa(t)}function Gc(t,s){if(s[0]!=="targets")return;const n=s[1];if(typeof n=="number")return t?.targets[n];if(typeof n=="string")return t?.targets.find(a=>a.stableKey===n)}function _c(t,s){if(s[0]!=="groups")return;const n=s[1];if(typeof n=="number")return t?.groups[n];if(typeof n=="string")return t?.groups.find(a=>a.stableKey===n)}function Uc(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Bc(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Ly(t,s){const n=Gc(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="urlMatchers"&&typeof r=="number"){const l=n.urlMatchers[r];return l?`${n.label} — ${l}`:n.label}if(a==="aliases"&&typeof r=="number"){const l=n.aliases[r];return l?`${n.label} — ${l}`:n.label}return n.label}function Ey(t,s){const n=_c(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="competitors"&&typeof r=="number"){const l=n.competitors.at(r)?.domain;return l?`${n.label} — ${l}`:n.label}if(a==="targetKeys"&&typeof r=="number"){const l=Bc(t.authoring,n.targetKeys[r]);return`${n.label} — ${l}`}return n.label}function Dy(t,s){const n=Uc(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${Bc(t.authoring,n.targetKey)} — ${a}`}function Oy(t,s){return s.path[0]==="identities"?"Project domain":Ly(t,s)??Ey(t,s)??Dy(t,s)}function xl(t,s,n){const a=Uc(t.authoring,s.path);if(!a)return;const r={...t.authoring?.defaultContext,...a.contextOverride},l=s.path.at(-1);if(n==="models"&&typeof l=="string")return r.models?.[l];if(n==="locations"&&typeof l=="number")return r.locations?.[l]}function Fy(t,s){const n=Oy(s,t);switch(t.ruleId){case"invalid-project-identity":return{title:"Fix the project domain",detail:"The project domain is not valid. Update it in project settings, then review again.",tone:"negative",affected:n};case"target-limit-exceeded":return{title:"Reduce Properties",detail:"This setup exceeds the Properties publishing limit. Remove some Properties, then review again.",tone:"negative"};case"duplicate-target-key":return{title:"Resolve duplicate Properties",detail:"Two Properties use the same setup identifier. Rename or recreate one, then review again.",tone:"negative",affected:n};case"no-included-targets":return{title:"Include a Property",detail:"Include at least one Property before publishing.",tone:"negative"};case"target-url-matcher-invalid":return{title:"Fix a Property URL",detail:"Use a valid web address, site-wide address, or URL pattern for this Property.",tone:"negative",affected:n};case"target-url-matcher-unowned":return{title:"Use a project domain",detail:"This Property URL must use the project domain or one of its subdomains.",tone:"negative",affected:n};case"target-url-matcher-ambiguous":return{title:"Separate Property URL coverage",detail:"This URL is assigned to more than one Property at the same specificity. Update one of the URLs.",tone:"negative",affected:n};case"target-alias-ambiguous":return{title:"Use distinct Property names",detail:"This name or alias matches another Property. Make each Property name and alias distinct.",tone:"negative",affected:n};case"execution-context-no-provider":return{title:"Choose a provider",detail:"Choose at least one provider before publishing.",tone:"negative",affected:n};case"invalid-provider-model":return{title:"Fix provider settings",detail:"Choose the provider that runs this model, or remove the model setting.",tone:"negative",affected:[n,xl(s,t,"models")].filter(Boolean).join(" — ")||void 0};case"invalid-location":return{title:"Fix a location",detail:"Choose a location configured for this project, or remove it from the query.",tone:"negative",affected:[n,xl(s,t,"locations")].filter(Boolean).join(" — ")||void 0};case"target-without-aliases":return{title:"Add Property aliases",detail:"Add a name or alias to measure mentions.",tone:"caution",affected:n};case"duplicate-group-key":return{title:"Resolve duplicate groups",detail:"Two groups use the same setup identifier. Rename one group, then review again.",tone:"negative",affected:n};case"group-unknown-target":return{title:"Fix group Properties",detail:"This group contains a Property that is no longer in setup. Remove it or add the Property back.",tone:"negative",affected:n};case"group-excluded-target":return{title:"Include or remove a grouped Property",detail:"This group contains an excluded Property. Include it or remove it from the group.",tone:"negative",affected:n};case"competitor-invalid-domain":return{title:"Fix a competitor domain",detail:"Enter a valid competitor domain.",tone:"negative",affected:n};case"competitor-matches-project":return{title:"Remove a project domain",detail:"A competitor cannot use the project domain.",tone:"negative",affected:n};case"competitor-duplicate":return{title:"Remove a duplicate competitor",detail:"List each competitor domain only once in a group.",tone:"negative",affected:n};case"duplicate-assignment":return{title:"Remove a duplicate query",detail:"Assign each query to a Property only once.",tone:"negative",affected:n};case"assignment-unknown-target":return{title:"Fix a query assignment",detail:"This query is assigned to a Property that is no longer in setup. Remove the assignment or add the Property back.",tone:"negative",affected:n};case"assignment-excluded-target":return{title:"Include or unassign a Property",detail:"This query is assigned to an excluded Property. Include it or remove the assignment.",tone:"negative",affected:n};case"assignment-unknown-query":return{title:"Remove an unavailable query",detail:"This assignment refers to a tracked query that is no longer available. Remove it or add the query back to the project.",tone:"negative",affected:n};case"assignment-unclassified":return{title:"Classify a query",detail:"Choose Branded or Non-brand for this query before publishing.",tone:"negative",affected:n};case"query-limit-exceeded":return{title:"Reduce queries",detail:"This setup exceeds the distinct-query publishing limit. Remove some query assignments, then review again.",tone:"negative"};case"target-without-assignments":return{title:"Assign queries",detail:"Assign at least one query to measure a Property.",tone:"caution",affected:n};case"invalid-compiled-plan":return{title:"Fix setup details",detail:"A setup value could not be validated. Review the affected item, then review again.",tone:"negative",affected:n};case"compiled-plan-too-large":return{title:"Reduce setup size",detail:"This setup is too large to publish. Remove Properties, queries, or groups, then review again.",tone:"negative"};case"active-revision-schema-v1":return{title:"Historical results will be kept",detail:"Existing results remain visible after you publish this setup.",tone:"neutral"}}return{title:t.severity==="fail"?"An unexpected setup issue blocks publishing":"An unexpected setup issue needs review",detail:t.severity==="fail"?"Review the affected item, make a correction, and review again. If it remains blocked, contact support.":"Review the affected item before publishing. If it remains, contact support.",tone:t.severity==="fail"?"negative":"caution",affected:n}}function Wa(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function Vc(t){const s=[...new Set(t)];return s.length===0?"":s.length===1?` Affected: ${s[0]}.`:s.length<=3?` Affected: ${s.join(", ")}.`:` Affected: ${s.slice(0,3).join(", ")}, and ${s.length-3} more.`}function Ky(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${Wa(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${Wa(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${Wa(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${Wa(n,"item")} need review.`:s}})()}${Vc(a)}`}function Gy(t,s){const n=new Map;for(const a of t){const r=Fy(a,s),l=[a.ruleId,a.severity,r.title,r.detail].join("\0"),i=n.get(l)??{ruleId:a.ruleId,severity:a.severity,meaning:r,paths:new Set,affected:new Set};i.paths.add(JSON.stringify(a.path)),r.affected&&i.affected.add(r.affected),n.set(l,i)}return[...n.values()].map((a,r)=>({id:`${a.ruleId}-${a.severity}-${r}`,title:a.meaning.title,detail:Ky(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function zr(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function Hr(t,s,n){const a=Gc(n,t.path),r=_c(n,t.path),l=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=l?n?.targets.find(u=>u.stableKey===l):void 0,c=a?.label??r?.label,d=Vc(c?[c]:[]),h={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...h,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${d}`};case"excluded-target-has-assignments":return{...h,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${d}`};case"group-unknown-target":return{...h,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${d}`};case"measurement.discovery.proposed_new_target":{const u=zr(a)??"the proposed Property";return{...h,title:"Review a new Property",detail:`Review ${u}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const u=zr(a)??"the proposed Property",p=i?.label??"an existing Property";return{...h,title:"Review a moved Property",detail:`Review ${u}. It may be the same Property as ${p}.`}}case"measurement.discovery.rebind_ambiguous":{const u=zr(a)??"the proposed Property",p=i?.label??"an existing Property";return{...h,title:"Choose an existing Property",detail:`Review ${u}. It may match ${p}; choose the correct Property.`}}default:return{...h,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function _y(t,s=!1){const n=[],a=t.targets.added.length+t.targets.removed.length+t.targets.changed.length,r=t.groups.added.length+t.groups.removed.length+t.groups.changed.length,l=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),l>0&&n.push(`${l} query assignment ${l===1?"change":"changes"}`),r>0&&n.push(`${r} group ${r===1?"change":"changes"}`),s&&n.unshift("Existing results remain visible after you publish this setup."),{title:s?"Historical results will be kept":t.activeRevision===null?"New setup ready":"Changes ready",items:n.length>0?n:["No changes from the published setup."]}}function Ps(t){return[...new Set(t)]}function Js(t){return Ps(t).sort()}function Uy(t,s,n){return t.kind==="groups"?{groupKeys:Js(t.groupIds),queryIds:Js(n)}:{targetKeys:Js(t.kind==="all"?s:t.propertyIds),queryIds:Js(n)}}function By(t){return{assignmentCount:t.assignments.requested,addedAssignments:t.assignments.added,alreadyPresentAssignments:t.assignments.alreadyPresent,resolvedPropertyCount:t.resolvedTargetKeys.length,overlapCount:t.overlapCount,addedProviderCalls:t.execution.addedProviderCalls,fullRunProviderCalls:t.execution.fullRunProviderCalls}}function gl(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function Vy(t){const s=t.plan;if(s.schemaVersion===2)return{defaultContext:{providers:[],locations:[]},targets:s.targets.map(a=>({stableKey:a.stableKey,label:a.label,status:"included",aliases:[...a.aliases],urlMatchers:a.urlMatchers.map(gl).filter(Boolean),source:a.discoveryIdentity?"sitemap":"manual",...a.discoveryIdentity?{discoveryIdentity:a.discoveryIdentity}:{}})),assignments:s.assignments.map(a=>({targetKey:a.targetKey,queryId:a.queryId,queryClass:a.queryClass,classificationSource:"operator"})),groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:a.competitors.map(r=>({...r,aliases:[...r.aliases]}))}))};const n=s.targetQuerySelections.flatMap(a=>a.queryIds.map(r=>({targetKey:a.targetKey,queryId:r,queryClass:"unclassified",classificationSource:"rule"})));return{defaultContext:{providers:[],locations:[]},targets:s.targets.map(a=>({stableKey:a.stableKey,label:a.label,status:"included",aliases:[...a.aliases],urlMatchers:a.urls.map(gl).filter(Boolean),source:"manual"})),assignments:n,groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:(a.competitors??[]).map(r=>({stableKey:fi(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function Qy({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:l,canEdit:i=!0,onCreateQueries:c,onManageProjectQueries:d,onPublished:h,service:u=Ry}){const[p,g]=o.useState(null),[m,y]=o.useState(null),[x,b]=o.useState("import"),[N,C]=o.useState(!0),[M,k]=o.useState(null),[f,v]=o.useState(null),[S,q]=o.useState([]),[I,w]=o.useState({...dl}),[V,F]=o.useState("idle"),[W,B]=o.useState(""),[Q,te]=o.useState(ul),[O,U]=o.useState([]),[se,D]=o.useState([]),[E,P]=o.useState({kind:"all"}),[Y,re]=o.useState(null),[ne,de]=o.useState(null),[Ce,J]=o.useState(!1),[oe,Ne]=o.useState(null),[X,ie]=o.useState(0),[G,he]=o.useState(null),[Le,be]=o.useState({...na}),[ee,Re]=o.useState(null),[De,qe]=o.useState(""),[xe,K]=o.useState(null),[Oe,R]=o.useState(!1),[ye,Ke]=o.useState(!1),[ze,Je]=o.useState(null),[pe,ht]=o.useState(null),[Ve,tt]=o.useState(null),[Wt,dt]=o.useState(null),[st,pt]=o.useState(null),St=o.useRef(0),Rt=o.useRef(0),Ge=m?.draft??null,A=m?.etag??null,ke=o.useMemo(()=>!i&&l?{baseActiveRevision:l.revision,authoring:Vy(l)}:null,[i,l]),ue=Ge??ke;async function He(_){const ae=++St.current;C(!0),k(null);try{let[Ae,me]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);if(!me.draft&&_&&i&&(await u.createDraft(t,Ae.activeRevision),[Ae,me]=await Promise.all([u.loadSetup(t),u.loadDraft(t)])),ae!==St.current)return;g(Ae),y(me),b(My(me.draft));const Te=Qr(me.draft);U(Te)}catch(Ae){if(ae!==St.current)return;k(ls(Ae,"Could not load advanced measurement setup."))}finally{ae===St.current&&C(!1)}}o.useEffect(()=>(He(!0),()=>{St.current+=1}),[t,i,u]),o.useEffect(()=>{!N&&!Ge&&ke&&b("properties")},[Ge,N,ke]);async function Tt(){const _=await u.loadDraft(t);return y(_),_}async function Mt(_){pt(null);try{const[ae,Ae]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);g(ae),y(Ae);const me=Qr(Ae.draft);U(me),b(Te=>qy(Ae.draft,Te)),v(_)}catch(ae){v(ls(ae,_))}}async function ot(_,ae,Ae,me={}){const{preserveBusyAction:Te=!1}=me;if(!i||!A||Ve&&!Te)return null;Te||tt(_),v(null),pt(null);try{const _e=await ae(A),mt=await Tt();return q((_e.warnings??[]).map((yt,ss)=>Hr(yt,ss,mt.draft?.authoring))),mt}catch(_e){return xn(_e)?await Mt("This setup changed in another session. The latest draft is loaded; review your changes again."):v(ls(_e,Ae)),null}finally{Te||tt(null)}}const Z=o.useMemo(()=>(ue?.authoring.targets??[]).map(_=>{const ae=hl(_);return{id:_.stableKey,name:_.label,url:ae[0]??"No URL",urls:ae,state:$y(_.status)}}),[ue]),Fe=o.useMemo(()=>ue?.authoring.targets.filter(_=>_.status==="included")??[],[ue]),Ie=o.useMemo(()=>Fe.map(_=>({id:_.stableKey,label:_.label,urlCount:hl(_).length})),[Fe]),Pe=ue?.authoring.assignments.length??0,qt=o.useMemo(()=>{if(!ue)return[];const _=new Set(s.map(me=>me.id)),ae=s.map(me=>({id:me.id,text:me.query,source:"saved-project-queries",propertyIds:Ps(ue.authoring.assignments.filter(Te=>Te.queryId===me.id).map(Te=>Te.targetKey))})),Ae=Ps(ue.authoring.assignments.map(me=>me.queryId).filter(me=>!_.has(me))).map(me=>({id:me,source:"unavailable-tracked-query",state:"missing",propertyIds:Ps(ue.authoring.assignments.filter(Te=>Te.queryId===me).map(Te=>Te.targetKey))}));return[...ae,...Ae]},[s,ue]),vt=o.useMemo(()=>(ue?.authoring.groups??[]).map(_=>({id:_.stableKey,name:_.label,propertyIds:_.targetKeys,competitors:_.competitors.map(ae=>ae.domain)})),[ue]),Yt=o.useMemo(()=>{if(se.length===0)return null;const _=Uy(E,Ie.map(Ae=>Ae.id),se);return(_.groupKeys?.length??_.targetKeys?.length??0)>0?_:null},[E,Ie,se]),nt=Yt?JSON.stringify(Yt):"";o.useEffect(()=>{const _=Yt,ae=++Rt.current;if(!i||!Ge||!A||!_){re(null),de(null),Ne(null),J(!1);return}re(null),de(null),Ne(null),J(!0);const Ae=window.setTimeout(()=>{u.previewAssignments(t,_).then(me=>{if(ae===Rt.current){if(me.draftEtag!==A){re(null),de(null),Ne("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}re(me),de(nt)}}).catch(me=>{ae===Rt.current&&(re(null),de(null),Ne(Ay(me)))}).finally(()=>{ae===Rt.current&&J(!1)})},250);return()=>{window.clearTimeout(Ae),Rt.current+=1}},[Yt,nt,X,i,Ge,A,t,u]);const $t=o.useMemo(()=>[...Pe===0?[{id:"no-query-assignments",title:"Assign at least one query",detail:"Apply a tracked query to at least one Property before publishing.",tone:"negative"}]:[],...ue?.authoring.assignments.some(_=>_.queryClass==="unclassified")&&!(ke&&l?.plan.schemaVersion===1)?[{id:"unclassified-query-assignments",title:"Remove an unavailable query",detail:"One or more saved assignments no longer have a tracked query. Clear them before publishing.",tone:"negative"}]:[],...S],[Pe,ke,l,S,ue]),Zt=n?{status:"unavailable",message:"Tracked queries are loading."}:a?{status:"unavailable",message:"Tracked queries could not be loaded. Retry before assigning Properties."}:{status:"available"};async function vs(_){let ae;try{ae=Ty(_)}catch(me){v(ls(me,"Check the sitemap details and try again."));return}w(_),F("reviewing");const Ae=await ot("import",me=>u.importSitemap(t,me,ae),"Could not review this sitemap.");if(Ae?.draft){const me=Ae.draft.authoring.targets.filter(_e=>_e.status==="proposed").map(_e=>_e.stableKey),Te=Ae.draft.authoring.targets.filter(_e=>_e.status==="included").map(_e=>_e.stableKey);U([...Te,...me]),B(""),te(ul),b("properties"),F("idle")}else F("error")}async function js(_){if(!c||_.length===0||Ve)return[];tt("create-queries"),dt(null);try{return await c(_)}catch(ae){throw dt(Ct(ae)),ae}finally{tt(null)}}async function Ns(_){if(!Ge||!A||Ve)return;const ae=new Set(_),me=Ge.authoring.targets.filter(_e=>_e.status==="proposed"&&_e.discoveryIdentity).map(_e=>({discoveryIdentity:_e.discoveryIdentity,action:ae.has(_e.stableKey)?"create":"ignore"})),Te=me.length>0||Ge.authoring.targets.some(_e=>_e.status!=="proposed"&&_e.status==="included"!==ae.has(_e.stableKey));tt("properties"),v(null),pt(null);try{if(!Te){U([...ae]),P({kind:"all"}),b("groups");return}await u.applySitemapSelection(t,A,me,[...ae]);const _e=await Tt(),mt=Qr(_e.draft);U(mt),P({kind:"all"}),b("groups")}catch(_e){xn(_e)?await Mt("This setup changed in another session. The latest Properties are loaded."):v(ls(_e,"Could not save the selected Properties."))}finally{tt(null)}}async function Gs(_){const ae=_.groupIds&&_.groupIds.length>0?{groupKeys:Js(_.groupIds),queryIds:Js(_.queryIds)}:{targetKeys:Js(_.propertyIds),queryIds:Js(_.queryIds)};if(!Y||ne!==JSON.stringify(ae)||!A||Y.draftEtag!==A){v("Review the latest assignment impact before assigning queries.");return}await ot("assignments",me=>u.applyAssignments(t,me,ae),"Could not apply these queries.")&&(D([]),he(`${Y.assignments.added} new assignment${Y.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function ft(_){if(_.propertyIds.length===0)return;await ot("replace-assignments",Ae=>u.replaceAssignments(t,Ae,{targetKeys:Ps(_.propertyIds),queryIds:[_.queryId]}),"Could not replace this query assignment.")&&(D(Ae=>Ae.filter(me=>me!==_.queryId)),he("Query assignments replaced."))}async function xs(_,ae=!1){if(_.length===0)return;if(!await ot("paired-assignments",me=>u.applyPairedAssignments(t,me,[..._]),"Could not assign these queries.",{preserveBusyAction:ae}))throw new Error("Could not assign these queries.")}async function Ze(_){if(!(!i||!c||_.length===0||Ve)){tt("create-and-pair-questions"),dt(null);try{let ae;try{ae=await c(Ps(_.map(Te=>Te.text)))}catch(Te){throw dt(Ct(Te)),Te}const Ae=new Map(ae.map(Te=>[Te.query,Te.id])),me=_.map(Te=>({targetKey:Te.propertyId,queryId:Ae.get(Te.text)})).filter(Te=>Te.queryId!==void 0);if(me.length!==_.length){const Te=new Error("The created queries could not be matched to their Properties.");throw dt("The queries were added, but could not be paired with every Property. Try again to pair them."),Te}try{await xs(me,!0)}catch(Te){throw dt("The queries were added, but could not be assigned to their Properties. Try again to pair them."),Te}}finally{tt(null)}}}async function Ft(_){if(!Ge)return;const ae=Ps(Ge.authoring.assignments.filter(me=>me.queryId===_).map(me=>me.targetKey));if(ae.length===0)return;await ot(`remove-${_}`,me=>u.removeAssignment(t,me,ae,_),"Could not clear this query assignment.")&&D(me=>me.filter(Te=>Te!==_))}async function es(_){if(!Ge||!A||Ve)return;const ae=_.name.trim();if(!ae)return;const Ae=ee??fi(ae,"group"),me=Ge.authoring.groups.find(yt=>yt.stableKey===Ae);if(me&&ee===null){v(`A group named "${me.label}" already exists. Edit it or choose a different name.`);return}const Te=_.competitorDomains.split(/[\s,]+/).map(yt=>yt.trim()).filter(Boolean),_e=Te.find(yt=>pl(yt)===null);if(_e){v(`"${_e}" is not a valid competitor domain.`);return}const mt=Ps(Te.map(yt=>pl(yt)));tt("group"),v(null),pt(null);try{const yt=await u.upsertGroup(t,A,{stableKey:Ae,label:ae,targetKeys:Ps(_.propertyIds),competitors:mt.map(L=>me?.competitors.find(we=>we.domain===L)??{stableKey:fi(L,"competitor"),label:L,domain:L,aliases:[]})}),ss=await Tt();q(yt.warnings.map((L,we)=>Hr(L,we,ss.draft?.authoring))),be({...na}),Re(null)}catch(yt){xn(yt)?await Mt("This setup changed in another session. The latest groups are loaded."):v(ls(yt,"Could not save this group."))}finally{tt(null)}}function as(_){const ae=Ge?.authoring.groups.find(Ae=>Ae.stableKey===_);ae&&(Re(_),be({name:ae.label,propertyIds:[...ae.targetKeys],competitorDomains:ae.competitors.map(Ae=>Ae.domain).join(", ")}))}async function gs(_){await ot("remove-group",Ae=>u.removeGroup(t,Ae,_),"Could not remove this group.")&&(P(Ae=>Ae.kind==="groups"&&Ae.groupIds.includes(_)?{kind:"all"}:Ae),ee===_&&(Re(null),be({...na})))}function jt(_){qe(_),K(null),Je(null),ht(null)}async function Pt(){if(!(!i||!De.trim()||Oe||ye)){R(!0),Je(null),ht(null);try{K(await u.previewGroupMembership(t,{csv:De}))}catch(_){K(null),Je(ls(_,"Could not review this CSV."))}finally{R(!1)}}}async function ts(_){if(!(!i||!A||!xe||_.length===0||Ve)){if(xe.draftEtag!==A){Je("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}Ke(!0),tt("group-import"),Je(null),ht(null),pt(null);try{const ae=await u.applyGroupMembership(t,A,{csv:De,sourceChecksum:xe.sourceChecksum,previewChecksum:xe.previewChecksum,acceptedRows:Ps(_.map(String)).map(Number)}),Ae=await Tt();q(ae.warnings.map((me,Te)=>Hr(me,Te,Ae.draft?.authoring))),qe(""),K(null),ht(`${ae.addedMemberships} membership${ae.addedMemberships===1?"":"s"} added${ae.unchangedMemberships>0?`; ${ae.unchangedMemberships} already present`:""}.`)}catch(ae){xn(ae)?(await Mt("This setup changed in another session. The latest draft is loaded; review the CSV again."),Je("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Je(ls(ae,"Could not apply this CSV."))}finally{tt(null),Ke(!1)}}}async function Kt(){if(!(!Ge||!A||Ve||Pe===0)){tt("review"),v(null),pt(null);try{const[_,ae]=await Promise.all([u.compilePreview(t),u.diffPreview(t)]),Ae=[..._.checks,...ae.checks],me=Ae.some(Te=>Te.ruleId==="active-revision-schema-v1");if(q(Gy(Ae.filter(Te=>Te.ruleId!=="active-revision-schema-v1"),{authoring:ue?.authoring,queries:s})),!_.ok||!ae.ok)return;if(ae.diff.activeRevision!==Ge.baseActiveRevision){await Mt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(_.compiledChecksum!==ae.compiledChecksum){v("The setup changed while it was being reviewed. Review the latest changes again.");return}pt({etag:A,baseActiveRevision:Ge.baseActiveRevision,compiledChecksum:_.compiledChecksum,changes:_y(ae.diff,me),providerCalls:_.plan.executionNodes.reduce((Te,_e)=>Te+_e.expectedSnapshots,0)})}catch(_){v(ls(_,"Could not review this setup."))}finally{tt(null)}}}async function _s(){if(!(!Ge||!A||!st||Ve)){if(A!==st.etag||Ge.baseActiveRevision!==st.baseActiveRevision){pt(null),v("The setup changed after review. Review the latest changes before publishing.");return}tt("publish"),v(null);try{await u.publish(t,A,{expectedActiveRevision:st.baseActiveRevision,expectedCompiledChecksum:st.compiledChecksum}),y({draft:null,etag:null}),pt(null),h?.()}catch(_){xn(_)?await Mt("The setup changed before it could be published. Review the latest draft and publish again."):v(ls(_,"Could not publish this setup."))}finally{tt(null)}}}async function Nt(){if(!(!A||Ve)){tt("discard"),v(null);try{await u.discard(t,A),y({draft:null,etag:null}),pt(null),h?.()}catch(_){xn(_)?await Mt("This setup changed in another session. The latest draft is loaded."):v(ls(_,"Could not discard these changes."))}finally{tt(null)}}}async function Jt(){if(!(!Ge||!A||!p||Ve)){tt("restart"),v(null),pt(null);try{await u.discard(t,A),await u.createDraft(t,p.activeRevision),w({...dl}),B(""),U([]),D([]),P({kind:"all"}),re(null),Ne(null),he(null),be({...na}),Re(null),qe(""),K(null),Je(null),ht(null),await He(!1)}catch(_){xn(_)?await Mt("The setup changed again. Reloaded the latest draft and published setup."):v(ls(_,"Could not restart this setup."))}finally{tt(null)}}}if(N)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-loading-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-loading-title",children:"Advanced measurement setup"})}),e.jsx("div",{className:"h-28 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement setup"})]});if(M)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-error-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-error-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:M}),e.jsx(T,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{He(!0)},children:"Try again"})]})]});if(!ue||i&&!A)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-empty-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-empty-title",children:"Advanced measurement setup"})}),e.jsx("p",{className:"text-sm text-secondary",children:i?"Start setup from the project Overview.":"No advanced setup is available to review."})]});if(i&&Ge&&p&&Ge.baseActiveRevision!==p.activeRevision)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-stale-draft-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-stale-draft-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"This draft is based on an older published setup."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Restart from the latest setup before making more changes."}),e.jsx(T,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:Ve==="restart",onClick:()=>{Jt()},children:Ve==="restart"?"Restarting…":"Discard draft and restart"})]}),f?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:f}):null]});const xt=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:r,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[p?.mode==="active-v1"?e.jsx("p",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-3 text-sm text-secondary",children:"Review and publish this setup to enable class-filtered reporting."}):null,f?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:f}):null,xt,x==="import"||x==="properties"?e.jsx(Ha,{currentStep:x,hasDraft:Ge!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},importProperties:{importDraft:I,onImportDraftChange:_=>{w(_),F("idle"),v(null)},onReviewSitemap:_=>{vs(_)},reviewState:V,properties:Z,propertiesState:"ready",propertiesSearch:W,onPropertiesSearchChange:B,maxVisibleProperties:Q,onShowAllProperties:()=>te(Z.length),selectedPropertyIds:O,onSelectedPropertyIdsChange:_=>U([..._]),onContinue:_=>{Ns(_)},isContinuing:Ve==="properties",onRetryProperties:()=>{Tt()},onReturnToImport:()=>b("import")}}):x==="queries"?e.jsx(Ha,{currentStep:"queries",hasDraft:Ge!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},onManageProjectQueries:d,queries:{onCreateQueries:c?_=>js(_):void 0,isCreatingQueries:Ve==="create-queries"||Ve==="create-and-pair-questions",isBusy:Ve!==null,createQueriesError:Wt,availability:Zt,properties:Ie,queries:qt,selectedQueryIds:se,isApplying:Ve==="assignments"||Ve==="paired-assignments",onSelectedQueryIdsChange:_=>D([..._]),onApplySelectedQueries:_=>Gs(_),groups:vt,audience:E,onAudienceChange:_=>{P(_),he(null)},assignmentImpact:Y&&ne===nt&&Y.draftEtag===A?By(Y):null,isPreviewingAssignmentImpact:Ce,assignmentImpactError:oe,onRetryAssignmentImpact:()=>ie(_=>_+1),assignmentNotice:G,onReplaceAssignments:ft,isReplacingAssignments:Ve==="replace-assignments",onCreateAndPairQuestions:i&&c?Ze:void 0,onClearQueryAssignments:Ft,onRemoveQuery:Ft,canContinue:Pe>0,onBack:()=>b("groups"),onContinue:()=>b("review")}}):x==="groups"?e.jsx(Ha,{currentStep:"groups",hasDraft:Ge!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},groups:{properties:Ie,groups:vt,groupDraft:Le,isSaving:Ve==="group",onGroupDraftChange:be,onSaveGroup:es,onEditGroup:_=>as(_.id),onRemoveGroup:gs,onClearGroupDraft:()=>{Re(null),be({...na})},membershipImport:{csv:De,preview:xe,isReviewing:Oe,isApplying:ye,error:ze,notice:pe,onCsvChange:jt,onReview:Pt,onApply:ts},onBack:()=>{b("properties")},onContinue:()=>b("queries")}}):e.jsx(Ha,{currentStep:"review",hasDraft:Ge!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},review:{counts:{properties:Fe.length,queries:new Set(ue.authoring.assignments.map(_=>_.queryId)).size,groups:ue.authoring.groups.length,assignments:ue.authoring.assignments.length,providerCalls:st?.providerCalls},flaggedExceptions:$t,reviewedChanges:st?.changes,isReviewing:Ve==="review",canReviewChanges:Pe>0&&!Ve,onReviewChanges:Kt,onBack:()=>b("queries"),canPublish:st!==null&&!Ve,isPublishing:Ve==="publish",onPublish:_s}})]})}const zy=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function fl(t){return t.label!=="Complete"}const gn="__all_properties__",Hy=50,Qc=50,Wy=20,Yy=50,Jy=250,Xy=5,Zy=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],eb={"this-property":"Matches this Property","another-property":"Matches another Property","owned-unassigned":"Site URL not included in a Property",external:"External URL","multiple-properties":"Matches multiple Properties","invalid-url":"Invalid URL"},zc={plan_v1:"Setup update required.",no_completed_run:"Not measured yet.",no_population:"No matching queries.",evidence_incomplete:"Evidence incomplete.",identity_ambiguous:`${ro}.`,"identity-ambiguous":`${ro}.`,not_applicable:"Not applicable.",incomplete:"The latest measurement is incomplete.","evidence-incomplete":"Some source evidence is incomplete.","no-population":"No measurements are available for this selection.",unavailable:"This measurement is unavailable."},tb={numerator:null,denominator:null,reason:"plan_v1"};function Dn(t){return t.numerator===null?!1:Number.isFinite(t.numerator)&&Number.isFinite(t.denominator)&&t.numerator>=0&&t.denominator>0&&t.numerator<=t.denominator}function sb(t){return Dn(t)?`${t.numerator} of ${t.denominator} (${et(t.numerator/t.denominator)})`:"N/A"}function Hc(t){if(Dn(t))return"";const s=t.reason??"unavailable";return zc[s]??s}function yl(t){const s=[];return t.market&&s.push(t.market),t.urls.length>0&&s.push(`${t.urls.length} ${t.urls.length===1?"URL":"URLs"}`),s.join(" · ")}function nb(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function ab(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function rb(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function la({metric:t,compact:s=!1}){const n=s?Dn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Dn(t)?"text-lg font-semibold text-heading":"text-lg font-semibold text-secondary",a=Dn(t)?ki(t):null;return e.jsxs("span",{className:"inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums",...Dn(t)?{}:{title:Hc(t)},children:[e.jsx("span",{className:n,children:sb(t)}),a?e.jsx("span",{className:"text-xs text-secondary",children:a}):null]})}function Bi({shown:t,total:s,onShowAll:n,itemLabel:a}){return t>=s?null:e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",t," of ",s]}),e.jsxs(T,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function bl({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,l]=o.useState(Qc),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((c,d)=>e.jsx("li",{className:a,children:c},`${c}:${d}`))}),e.jsx(Bi,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>l(Number.MAX_SAFE_INTEGER)})]})]})}function ib({evidence:t,state:s="ready",onRetry:n}){const[a,r]=o.useState(Qc),l=t.slice(0,a);return e.jsxs("section",{"aria-label":"Evidence",children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:"Evidence"}),s==="loading"?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Loading evidence…"}):s==="error"?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsx("span",{children:"Evidence could not be loaded."}),n?e.jsx(T,{type:"button",size:"sm",variant:"outline",onClick:n,children:"Retry evidence"}):null]}):t.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"No source evidence is available."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[640px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children:l.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(je,{tone:i.tone,children:eb[i.kind]}),i.historical?e.jsx(je,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:i.query}),i.provider||i.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[i.provider,i.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:i.url})]},i.id))})]})}),e.jsx(Bi,{shown:l.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function ob({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(bl,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(bl,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(ib,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function lb({values:t}){return e.jsxs("section",{"aria-labelledby":"advanced-measurement-share-of-voice",className:"border-y border-default py-4",children:[e.jsx("h2",{id:"advanced-measurement-share-of-voice",className:"text-sm font-medium text-heading",children:"Brand share of voice"}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[420px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Name"}),e.jsx("th",{children:"Share of voice"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.name}),e.jsx("td",{className:"text-secondary",children:e.jsx(la,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function vl({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function l(i){if(r)return;const c=n.findIndex(u=>u.value===s);let d=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?d=(c+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?d=(c-1+n.length)%n.length:i.key==="Home"?d=0:i.key==="End"&&(d=n.length-1),d===null)return;i.preventDefault();const h=n[d];a(h.value),i.currentTarget.querySelectorAll('[role="radio"]')[d].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:l,children:n.map(i=>{const c=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":c,tabIndex:c?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${c?"segmented-option-active":""}`,children:i.label},i.value)})})}function cb({outcomes:t}){const s=[{key:"both",count:t.bothSignals,label:"mentioned and cited",tone:"text-primary"},{key:"mentioned-only",count:t.mentionedOnly,label:"mentioned only",tone:"text-primary"},{key:"cited-only",count:t.citedOnly,label:"cited only",tone:"text-primary"},{key:"neither",count:t.neither,label:"neither signal",tone:"text-negative"},...t.notMeasured>0?[{key:"not-measured",count:t.notMeasured,label:"not measured",tone:"text-faint"}]:[]];return e.jsx("div",{"aria-label":"Property outcomes",className:"flex flex-wrap gap-x-8 gap-y-3 py-3",children:s.map(n=>e.jsxs("div",{className:"whitespace-nowrap",children:[e.jsx("p",{className:`font-mono text-xl font-semibold leading-none tabular-nums ${n.tone}`,children:n.count}),e.jsxs("p",{className:"mt-1 text-[13px] text-secondary",children:[n.label,n.key==="not-measured"?e.jsx(Be,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function db({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:l=!1,isViewLoading:i=!1,isLoadingMore:c=!1,isLoadMoreError:d=!1,viewSearch:h,onViewChange:u,onLoadMore:p,onPropertyExpand:g,onRetryEvidence:m,renderPropertyLink:y}){const x=t.currentView!=null,b=t.classReporting==="available"&&(x||t.classScopes!=null),[N,C]=o.useState(t.currentView?.queryClass??"all"),[M,k]=o.useState(t.currentView?.scope.key??gn),[f,v]=o.useState(h??""),[S,q]=o.useState(Hy),[I,w]=o.useState(Wy),[V,F]=o.useState(t.currentView?.sort??"label-asc"),[W,B]=o.useState(null),Q=o.useRef(h??""),te=b&&!x&&N!=="all"?N==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,O=x?{aggregate:t.currentView.aggregate,groups:[]}:te,U=o.useCallback(K=>{if(!x||!u)return;const Oe=K.scope??(M===gn?"all":"group"),R=K.search??f;Q.current=R,u({scope:Oe,...Oe==="group"?{groupKey:K.groupKey??M}:{},queryClass:K.queryClass??N,...R?{search:R}:{},...K.sort?{sort:K.sort}:{}})},[u,f,N,M,x]);o.useEffect(()=>{!t.currentView||i||(C(t.currentView.queryClass),k(t.currentView.scope.key??gn),t.currentView.sort&&F(t.currentView.sort))},[i,t.currentView]),o.useEffect(()=>{h!==void 0&&(Q.current=h,v(K=>K.trim()===h.trim()?K:h))},[h]),o.useEffect(()=>{if(!x||!u||f===Q.current)return;const K=window.setTimeout(()=>U({search:f}),Jy);return()=>window.clearTimeout(K)},[u,U,f,x]);const se=t.availableGroups??O.groups;o.useEffect(()=>{M===gn||se.some(K=>K.id===M)||k(gn)},[se,M]);const D=x?void 0:O.groups.find(K=>K.id===M),E=D?.aggregate??O.aggregate,P=K=>b?K:tb,Y=V,re=f.trim().toLocaleLowerCase(),ne=o.useMemo(()=>!x&&re?E.properties.filter(K=>K.name.toLocaleLowerCase().includes(re)):E.properties,[E.properties,re,x]),de=x?ne:ne.slice(0,S),Ce=(x?t.currentView?.scope.kind==="group":D!=null)&&N==="non-brand"&&b&&(x||D.confirmedCompetitorCount>0)&&(E.shareOfVoice?.length??0)>0,J=b?E.unavailablePropertyCount??0:0,oe=t.flaggedResults.reduce((K,Oe)=>K+(Oe.count??1),0),Ne=t.flaggedResultsTotal??oe,X=[P(E.metrics.propertiesMentioned),P(E.metrics.mentionCoverage),P(E.metrics.citationCoverage)].map(Hc).find(Boolean),ie=b?t.nextActionText??X??(J>0?`${J} ${J===1?"property is":"properties are"} unavailable.`:Ne>0?`${Ne} flagged ${Ne===1?"result needs":"results need"} review.`:null):zc.plan_v1,Le=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?nb(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,be=ab(t.latestMeasurement.date),ee=[{value:gn,label:"All properties"},...se.map(K=>({value:K.id,label:K.label}))],Re=se.length>Xy;function De(K){k(K),U(K===gn?{scope:"all"}:{scope:"group",groupKey:K})}function qe(K){C(K),U({queryClass:K})}function xe(K){const Oe=W!==K;B(Oe?K:null),Oe&&g?.(K)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":i,className:"space-y-5",children:[e.jsx("header",{className:"border-b border-default pb-4",children:e.jsx("div",{role:"status","aria-label":"Measurement status and next action",className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:i?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(je,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(je,{tone:"caution",children:"Includes historical data"}):null,Le?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:Le}):null,be?e.jsx("span",{className:"text-sm text-secondary",children:be}):null,ie?e.jsx("span",{className:"text-sm text-secondary",children:ie}):null,s&&b&&n?e.jsx(T,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!b?e.jsx(T,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||l,children:l?"Opening setup…":"Republish setup"}):null]})})}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4 border-b border-default pb-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-group-label",htmlFor:Re?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),Re?e.jsx("select",{id:"advanced-measurement-group",value:M,onChange:K=>De(K.target.value),className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-mono-400",children:ee.map(K=>e.jsx("option",{value:K.value,children:K.label},K.value))}):e.jsx(vl,{ariaLabelledBy:"advanced-measurement-group-label",value:M,options:ee,onChange:De})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-class-label",className:"block text-sm font-medium text-heading",children:"Query type"}),e.jsx(vl,{ariaLabelledBy:"advanced-measurement-class-label",value:N,options:Zy,onChange:qe,disabled:!b})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:f,onChange:K=>v(K.target.value),placeholder:"Search properties",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]})]}),!i&&Ce?e.jsx(lb,{values:E.shareOfVoice??[]}):null,i?e.jsx("div",{className:"h-44 animate-pulse rounded-md bg-surface-subtle","aria-label":"Updating Property results"}):e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-title",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{id:"advanced-measurement-properties-title",className:"text-base font-semibold text-heading",children:["Properties",e.jsx(Be,{text:"Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other."})]}),e.jsxs("span",{className:"text-sm text-secondary",children:[t.currentView?.propertyTotal??ne.length," ",(t.currentView?.propertyTotal??ne.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(cb,{outcomes:t.currentView.outcomes}):null,e.jsx("div",{className:"overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("caption",{className:"sr-only",children:"Property measurement results"}),e.jsx("thead",{children:e.jsxs("tr",{children:[zy.map(K=>{const Oe=Y.startsWith(`${K.key}-`),R=Oe&&Y.endsWith("-desc")?"descending":Oe?"ascending":"none";return e.jsx("th",{"aria-sort":R,className:(K.numeric,void 0),children:u?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const ye=`${K.key}-${Oe&&Y.endsWith("-asc")?"desc":"asc"}`;F(ye),U({sort:ye})},"aria-label":`Sort by ${K.label.toLowerCase()}`,children:[K.label,e.jsx(Un,{className:`h-3 w-3 transition-transform ${Oe?"opacity-100":"opacity-0"} ${R==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):K.label},K.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[de.map(K=>{const Oe=W===K.id;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:R=>{rb(R.target)||xe(K.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[y?y({id:K.id,name:K.name}):K.name,fl(K.status)||K.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[fl(K.status)?e.jsx(je,{tone:K.status.tone,children:K.status.label}):null,K.historical?e.jsx(je,{tone:"caution",children:"Historical"}):null]}):null,yl(K)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:yl(K)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(la,{metric:K.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(la,{metric:K.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(T,{size:"icon",variant:"ghost","aria-expanded":Oe,"aria-label":Oe?`Hide details for ${K.name}`:`Show details for ${K.name}`,onClick:()=>xe(K.id),children:e.jsx(Un,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${Oe?"rotate-180":""}`,"aria-hidden":"true"})})})]},K.id),Oe?(K.providers??[]).map(R=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:R.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(la,{metric:R.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(la,{metric:R.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${K.id}:${R.provider}`)):null,Oe?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(ob,{property:K,onRetryEvidence:m})})},`${K.id}:details`):null]},K.id)}),de.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"py-8 text-center text-sm text-secondary",children:"No properties match this search."})}):null]})]})}),x&&t.currentView.nextCursor&&p?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",de.length," of ",t.currentView.propertyTotal]}),d?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(T,{size:"sm",variant:"outline",disabled:c,onClick:()=>p(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more properties":"Show 50 more"})]}):x?de.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",de.length," of ",t.currentView.propertyTotal]}):null:e.jsx(Bi,{shown:de.length,total:ne.length,itemLabel:"properties",onShowAll:()=>q(Number.MAX_SAFE_INTEGER)})]}),!i&&!re&&Ne>0?e.jsx("section",{"aria-label":"Flagged results",className:"border-t border-default pt-4",children:e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:["Flagged results (",Ne,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,I).map(K=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(je,{tone:K.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:K.property}),e.jsx("span",{className:"text-secondary",children:K.summary})]},K.id))}),I<t.flaggedResults.length?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",t.flaggedResults.slice(0,I).reduce((K,Oe)=>K+(Oe.count??1),0)," of ",Ne," flagged results"]}),e.jsx(T,{size:"sm",variant:"outline",onClick:()=>w(K=>Math.min(t.flaggedResults.length,K+Yy)),children:"Show 50 more"})]}):oe<Ne?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",oe," of ",Ne," flagged results"]}),x&&t.currentView.nextCursor&&p?e.jsx(T,{size:"sm",variant:"outline",disabled:c,onClick:()=>p(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function Wc(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function ub(t){return t.activePlanSchemaVersion===null?{surface:"simple-overview",setupAction:t.hasDraft?"continue":"set-up"}:t.activePlanSchemaVersion<2?{surface:"advanced-overview-v1",setupAction:"republish"}:{surface:"advanced-overview",setupAction:t.hasDraft?"continue":"edit"}}function mb({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:l,onRunMeasurement:i,onRetryReport:c,onViewChange:d,onLoadMore:h,onPropertyExpand:u,onRetryEvidence:p,renderPropertyLink:g,isRunningMeasurement:m,isOpeningSetup:y,isViewLoading:x,isLoadingMore:b,isLoadMoreError:N,viewSearch:C}){return t.surface==="simple-overview"?n:e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&l?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(T,{type:"button",size:"sm",disabled:y,onClick:l,children:y?"Opening setup…":Wc(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,r==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):r==="error"&&!a?e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load the advanced measurement report."}),c?e.jsx(T,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:c,children:"Retry report"}):null]}):a?e.jsx(db,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:l,onViewChange:d,onLoadMore:h,onPropertyExpand:u,onRetryEvidence:p,renderPropertyLink:g,isRunningMeasurement:m,isRepublishingSetup:y,isViewLoading:x,isLoadingMore:b,isLoadMoreError:N,viewSearch:C}):e.jsx("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-secondary",children:"No advanced measurement report is available yet."})]})}const $n={numerator:null,denominator:null,reason:"plan_v1"};function hb(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function jl(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator,...t.unattributed===void 0?{}:{unattributed:t.unattributed}}}function pb(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function xb(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function gb(t){if(!t)return"Date unavailable";const s=new Date(t);return Number.isFinite(s.getTime())?s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}):"Date unavailable"}function fb(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function yb(t){const s=new Map;for(const n of t){const a=fb(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function bb(t,s){if(t.plan.schemaVersion!==1)throw new Error("Version-one report adapter received a different setup version.");const n=t.plan,a=new Map(n.targets.map(y=>[y.stableKey,y])),r=new Map(n.querySnapshots.map(y=>[y.queryId,y.queryText])),l=new Map;for(const y of n.targetQuerySelections){const x=l.get(y.targetKey)??[];x.push(...y.queryIds.map(b=>r.get(b)).filter(b=>!!b)),l.set(y.targetKey,[...new Set(x)])}const i=yb(s.evidence),c=n.executionNodes.reduce((y,x)=>y+x.expectedSnapshots,0),d=s.run?.status==="completed"&&c>0,h=d?c:0,u=d?c:0,p=s.targets.map(y=>{const x=a.get(y.id),b=i.get(y.id)??[],N=b.map(k=>({id:`${k.observationId}:${k.usageEdgeId}:${k.sourceUrl}`,kind:pb(k.classification),query:k.queryText,url:k.sourceUrl,tone:xb(k.classification),historical:k.historical||k.bridged})),C=b.some(k=>k.historical||k.bridged),M=s.run?y.completeness.complete?x?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${y.completeness.executed} of ${y.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:y.id,name:y.label,mentionCoverage:jl(y.mentionCoverage),citationCoverage:jl(y.citationCoverage),status:M,assignedQueries:l.get(y.id)??[],urls:x?.urls.map(hb)??[],evidence:N,historical:C}}),g=new Map(p.map(y=>[y.id,y])),m=new Map(n.groups.map(y=>[y.stableKey,y]));return{classReporting:"plan-v1",latestMeasurement:{status:s.run?.status==="completed"?{label:"Complete",tone:"positive"}:s.run?.status==="partial"?{label:"Partial result",tone:"caution"}:{label:"Not measured",tone:"neutral"},completedSlots:h,totalSlots:u,date:gb(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:$n,mentionCoverage:$n,citationCoverage:$n},properties:p},groups:s.groups.map(y=>({id:y.id,label:y.label,confirmedCompetitorCount:m.get(y.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:$n,mentionCoverage:$n,citationCoverage:$n},properties:y.targetIds.map(x=>g.get(x)).filter(x=>!!x)}}))},flaggedResults:[]}}function vb({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1),[c,d]=o.useState(null),[h,u]=o.useState(t.displayName),[p,g]=o.useState(t.canonicalDomain),[m,y]=o.useState(t.country),[x,b]=o.useState(t.language),[N,C]=o.useState(t.ownedDomains??[]),[M,k]=o.useState(""),[f,v]=o.useState(t.aliases??[]),[S,q]=o.useState(""),[I,w]=o.useState(null),[V,F]=o.useState(!1),[W,B]=o.useState(!1),[Q,te]=o.useState(""),[O,U]=o.useState(""),[se,D]=o.useState(""),[E,P]=o.useState(""),[Y,re]=o.useState(""),[ne,de]=o.useState(null),[Ce,J]=o.useState(null);o.useEffect(()=>{a||(u(t.displayName),g(t.canonicalDomain),y(t.country),b(t.language),C(t.ownedDomains??[]),v(t.aliases??[]))},[t,a]);function oe(){r(!1),d(null),u(t.displayName),g(t.canonicalDomain),y(t.country),b(t.language),C(t.ownedDomains??[]),v(t.aliases??[]),k(""),q("")}function Ne(){const R=M.trim();R&&(N.includes(R)||C([...N,R]),k(""))}function X(R){C(N.filter(ye=>ye!==R))}function ie(){const R=S.trim();if(!R)return;const ye=R.toLowerCase();f.some(Ke=>Ke.toLowerCase()===ye)||v([...f,R]),q("")}function G(R){v(f.filter(ye=>ye!==R))}async function he(){if(!(!h.trim()||!p.trim()||!m.trim()||!x.trim())){i(!0),d(null);try{await s(t.name,{displayName:h.trim(),canonicalDomain:p.trim(),ownedDomains:N,aliases:f,country:m.trim(),language:x.trim()}),r(!1),Ee({title:"Project settings saved",detail:`${h.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(R){d(R instanceof Error?R.message:"Failed to save")}finally{i(!1)}}}async function Le(){const R=Q.trim(),ye=O.trim(),Ke=se.trim(),ze=E.trim();if(!(!R||!ye||!Ke||!ze)){F(!0),w(null);try{const Je={label:R,city:ye,region:Ke,country:ze};Y.trim()&&(Je.timezone=Y.trim()),await um(t.name,Je),n(),te(""),U(""),D(""),P(""),re(""),B(!1),Ee({title:"Location added",detail:`${R} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${R}`,dedupeMode:"drop"})}catch(Je){w(Je instanceof Error?Je.message:"Failed to add location")}finally{F(!1)}}}async function be(R){F(!0),w(null);try{await dm(t.name,R),n(),Ee({title:"Location removed",detail:`${R} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${R}`,dedupeMode:"drop"})}catch(ye){w(ye instanceof Error?ye.message:"Failed to remove location")}finally{F(!1)}}async function ee(R){F(!0),w(null);try{await cm(t.name,R),n(),Ee({title:"Default location updated",detail:`${R} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(ye){w(ye instanceof Error?ye.message:"Failed to set default location")}finally{F(!1)}}async function Re(R){de(R),J(null);try{await mm(t.name,R),Ee({title:`${R.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(ye){J(ye instanceof Error?ye.message:"Could not download tracking results.")}finally{de(null)}}const De=h!==t.displayName||p!==t.canonicalDomain||m!==t.country||x!==t.language||JSON.stringify(N)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(f)!==JSON.stringify(t.aliases??[]),qe=!le()&&!Os(),xe="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",K="mb-1 block text-sm font-medium text-secondary",Oe=Q.trim()&&O.trim()&&se.trim()&&E.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),qe&&!a&&e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),c&&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:[c,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>d(null),children:"×"})]}),qe&&a?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:K,children:"Display name"}),e.jsx("input",{className:xe,type:"text",value:h,onChange:R=>u(R.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:K,children:"Canonical domain"}),e.jsx("input",{className:xe,type:"text",value:p,onChange:R=>g(R.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:K,children:"Country"}),e.jsx("input",{className:xe,type:"text",value:m,onChange:R=>y(R.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:K,children:"Language"}),e.jsx("input",{className:xe,type:"text",value:x,onChange:R=>b(R.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:K,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:N.map(R=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[R,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>X(R),"aria-label":`Remove ${R}`,children:"×"})]},R))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${xe} flex-1`,type:"text",placeholder:"docs.example.com",value:M,onChange:R=>k(R.target.value),onKeyDown:R=>R.key==="Enter"&&(R.preventDefault(),Ne())}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:!M.trim(),onClick:Ne,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:K,children:"Aliases"}),e.jsx("p",{className:"mb-1.5 text-sm text-secondary",children:"Other brand names that may appear in answers."}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:f.map(R=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[R,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>G(R),"aria-label":`Remove ${R}`,children:"×"})]},R))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${xe} flex-1`,type:"text",placeholder:"Facebook",value:S,onChange:R=>q(R.target.value),onKeyDown:R=>R.key==="Enter"&&(R.preventDefault(),ie())}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:!S.trim(),onClick:ie,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(T,{type:"button",disabled:l||!De||!h.trim()||!p.trim(),onClick:Xe(he),children:l?"Saving...":"Save changes"}),e.jsx(T,{type:"button",variant:"outline",disabled:l,onClick:oe,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-default bg-surface overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(R=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:R},R))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Aliases"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.aliases??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.aliases.map(R=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:R},R))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.country})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.language})]}),t.tags?.length?e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Tags"}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map(R=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:R},R))})})]}):null,e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[I&&e.jsxs("div",{className:"mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-xs text-negative",children:[I,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>w(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-faint",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(R=>e.jsxs("tr",{className:"border-t border-mono-800/30",children:[e.jsx("td",{className:"py-1.5 pr-3",children:e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium ${R.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[R.label,R.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:R.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:R.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:R.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:R.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[qe&&R.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:V,onClick:()=>{ee(R.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${R.label} as default location`,children:"Set default"}),qe&&e.jsx("button",{type:"button",disabled:V,onClick:()=>{be(R.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${R.label}`,children:"Remove"})]})})]},R.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),qe?W?e.jsxs("div",{className:"mt-2 rounded border border-base bg-bg-elevated/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-secondary",children:"Add location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Label *"}),e.jsx("input",{className:xe,type:"text",value:Q,onChange:R=>te(R.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"City *"}),e.jsx("input",{className:xe,type:"text",value:O,onChange:R=>U(R.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Region *"}),e.jsx("input",{className:xe,type:"text",value:se,onChange:R=>D(R.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Country *"}),e.jsx("input",{className:xe,type:"text",value:E,onChange:R=>P(R.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Timezone (optional)"}),e.jsx("input",{className:xe,type:"text",value:Y,onChange:R=>re(R.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(T,{type:"button",size:"sm",disabled:V||!Oe,onClick:Xe(Le),children:V?"Adding...":"Add location"}),e.jsx(T,{type:"button",size:"sm",variant:"outline",disabled:V,onClick:()=>{B(!1),w(null)},children:"Cancel"})]})]}):e.jsx(T,{type:"button",size:"sm",variant:"outline",onClick:()=>B(!0),children:"+ Add location"}):null]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted",children:"Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"max-w-xl text-xs leading-5 text-muted",children:"Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:ne!==null,onClick:Xe(()=>Re("csv")),children:ne==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:ne!==null,onClick:Xe(()=>Re("json")),children:ne==="json"?"Preparing JSON...":"Download JSON"})]})]}),Ce&&e.jsx("p",{className:"mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:Ce})]})]})]})}function aa(t){return{...t??{}}}function jb(t,s){const n=Object.entries(t).sort(([r],[l])=>r.localeCompare(l)),a=Object.entries(s).sort(([r],[l])=>r.localeCompare(l));return n.length===a.length&&n.every(([r,l],i)=>{const c=a[i];return c?.[0]===r&&c[1]===l})}function Nb({project:t,onSave:s}){const{isAdmin:n}=Sn(),a=$e({queryKey:["settings"],queryFn:ql,staleTime:6e4,enabled:n&&!le()}),[r,l]=o.useState(t.providers.length===0),[i,c]=o.useState(t.providers),[d,h]=o.useState(()=>aa(t.providerModels)),[u,p]=o.useState({providers:t.providers,providerModels:aa(t.providerModels)}),[g,m]=o.useState(!1),[y,x]=o.useState(!1),[b,N]=o.useState(null),[C,M]=o.useState(null),k=o.useRef(null),f=a.data?.providerCatalog??[],v=o.useMemo(()=>new Set((a.data?.providers??[]).filter(B=>B.configured).map(B=>B.name)),[a.data]),S=o.useMemo(()=>{const B=new Map(a.data?.providers.map(te=>[te.name,te.model])),Q=new Map(f.map(te=>[te.name,{...te,defaultModel:B.get(te.name)||te.defaultModel}]));for(const te of Object.keys(d))Q.has(te)||Q.set(te,{name:te,displayName:te,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...Q.values()].sort((te,O)=>te.displayName.localeCompare(O.displayName))},[f,d,a.data?.providers]),q=!jb(d,u.providerModels);o.useEffect(()=>{if(g||y)return;const B={providers:t.providers,providerModels:aa(t.providerModels)};p(B),l(B.providers.length===0),c(B.providers),h(B.providerModels)},[t]);function I(){x(!0),l(!1),i.length===0&&c([...v])}function w(B,Q,te=!1){x(!0),h(O=>{const U={...O};return Q==="__inherit__"?delete U[B]:Q==="__custom__"?U[B]=te?"":U[B]??"":U[B]=Q,U}),Q==="__custom__"&&queueMicrotask(()=>k.current?.focus())}function V(B,Q){x(!0),c(te=>Q?[...new Set([...te,B])]:te.filter(O=>O!==B))}function F(){x(!1),l(u.providers.length===0),c(u.providers),h(aa(u.providerModels)),N(null),M(null)}async function W(){if(!(a.isError||a.isLoading||!r&&i.length===0)){m(!0),N(null),M(null);try{const B=Object.fromEntries(Object.entries(d).filter(([te,O])=>O.trim()!==""&&(r||i.includes(te)))),Q={providers:r?[]:i,providerModels:B};await s(Q),p({providers:[...Q.providers],providerModels:aa(Q.providerModels)}),x(!1),M("Engine settings saved. They apply on the next sweep.")}catch(B){N(nr(B))}finally{m(!1)}}}return le()||!n?null:a.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):a.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):f.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):v.size===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsxs("p",{className:"text-sm text-secondary",children:["Configure an answer engine in ",e.jsx(qs,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":g,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Execution"}),e.jsx("h2",{children:"Answer engines"})]}),e.jsx("p",{className:"supporting-copy",children:"Changes apply on the next sweep."})]}),e.jsxs("fieldset",{disabled:g,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:r,onChange:()=>{x(!0),l(!0)}})," All configured engines"]}),e.jsx("p",{className:"project-engine-help",children:"Includes engines configured later in global Settings."}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:!r,onChange:I})," Choose engines"]}),!r&&e.jsx("div",{className:"project-engine-list",children:S.map(B=>{const Q=i.includes(B.name),te=v.has(B.name),O=Q&&!te,U=d[B.name],se=B.knownModels.some(E=>E.id===U),D=U===void 0?"__inherit__":se?U:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:Q,disabled:!te&&!Q,onChange:E=>V(B.name,E.target.checked)})," ",e.jsx("span",{children:B.displayName}),O&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),Q&&(B.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${B.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${B.name}`,value:D,onChange:E=>w(B.name,E.target.value,se),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",B.defaultModel||"default"]}),B.knownModels.map(E=>e.jsx("option",{value:E.id,children:E.displayName},E.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),D==="__custom__"&&e.jsx("input",{ref:k,"aria-label":`${B.displayName} custom model ID`,value:U??"",onChange:E=>{x(!0),h(P=>({...P,[B.name]:E.target.value}))},"aria-describedby":`project-model-hint-${B.name}`}),e.jsxs("p",{id:`project-model-hint-${B.name}`,className:"project-engine-help",children:[U?"Project override":"Inherited from instance settings",". ",B.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},B.name)})})]}),!r&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),b&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:b}),C&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:C}),q&&e.jsx("p",{className:"project-engine-warning",children:"Applies on the next sweep. Existing history remains visible. If the recorded model changes, month-to-month comparison may exclude that engine."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{type:"button",onClick:()=>{W()},disabled:g||!r&&i.length===0,children:g?"Saving engines…":"Save engines"}),e.jsx(T,{type:"button",variant:"outline",onClick:F,disabled:g,children:"Cancel"})]})]})}const Ya={edit:"Edit schedule",pause:"Pause",resume:"Resume",save:"Save schedule"},wb=[{value:"daily",label:"Every day"},{value:"weekly@mon",label:"Every Monday"},{value:"weekly@wed",label:"Every Wednesday"},{value:"weekly@fri",label:"Every Friday"},{value:"twice-daily",label:"Twice a day (6am & 6pm)"},{value:"calendar",label:"Every N days"},{value:"custom",label:"Custom cron expression"}],Nl=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Toronto","America/Vancouver","Europe/London","Europe/Paris","Europe/Berlin","Asia/Tokyo","Asia/Shanghai","Asia/Singapore","Australia/Sydney"];function Wr(t,s){const n=s==="UTC"?"UTC":s.split("/").pop()?.replace(/_/g," ")??s,a=new Date(`${t.startDate}T00:00:00Z`),r=Number.isNaN(a.getTime())?t.startDate:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(a),[l,i]=t.time.split(":").map(Number),c=Number.isInteger(l)&&Number.isInteger(i)?new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",timeZone:"UTC"}).format(new Date(Date.UTC(1970,0,1,l,i))):t.time;return`Every ${t.everyDays} days starting ${r} at ${c} · ${n}`}function Sb({projectName:t}){const s=us(),n=!le()&&!Os()&&!s,a=ps(),[r,l]=o.useState(!1),[i,c]=o.useState("daily"),[d,h]=o.useState(6),[u,p]=o.useState(""),[g,m]=o.useState(14),[y,x]=o.useState(""),[b,N]=o.useState("00:00"),[C,M]=o.useState("UTC"),[k,f]=o.useState(!1),[v,S]=o.useState(""),[q,I]=o.useState(!1),[w,V]=o.useState(!1),[F,W]=o.useState(null),[B,Q]=o.useState(void 0),te=hm({client:H,path:{name:t}}),O=$e({...Bl({client:H,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),U=O.isPending||O.isFetching,se=O.isError,D=O.data?.find(X=>X.kind==="answer-visibility")??null,E=r&&B!==void 0&&(D?.updatedAt??null)!==B,P=X=>{a.setQueryData(te,ie=>{const G=(ie??[]).filter(he=>he.kind!=="answer-visibility");return X?[...G,X]:G})},Y=X=>{if(X){if(X.recurrence)c("calendar"),m(X.recurrence.everyDays),x(X.recurrence.startDate),N(X.recurrence.time);else{const G=ym(X.preset??null,X.cronExpr);c(G.freq),h(G.hour),p(G.customCron)}const ie=Nl.includes(X.timezone);M(ie?X.timezone:"Other"),f(!ie),S(ie?"":X.timezone)}else c("daily"),h(6),p(""),m(14),x(""),N("00:00"),M("UTC"),f(!1),S("");Q(X?.updatedAt??null)},re=()=>{n&&(Y(D),W(null),l(!0))},ne=()=>{Y(D),W(null)},de=async()=>{(await O.refetch()).isError?W("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):W(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},Ce=async(X,ie)=>{if(X instanceof Gn&&X.code==="SCHEDULE_VERSION_CONFLICT"){await de();return}W(X instanceof Error?X.message:ie)},J=async()=>{if(n&&!(E||B===void 0)){I(!0),W(null);try{const X=await O.refetch();if(X.isError||X.data===void 0){W("Canonry could not verify the latest schedule. Try again before saving.");return}const ie=X.data.find(be=>be.kind==="answer-visibility")??null;if((ie?.updatedAt??null)!==B)return;const he={timezone:k?v.trim()||"UTC":C,enabled:ie?.enabled??!0,providers:ie?.providers??[],expectedUpdatedAt:B};i==="calendar"?he.recurrence={everyDays:g,startDate:y,time:b}:i==="custom"?he.cron=u.trim():he.preset=fm(i,d);const Le=await to(t,he);l(!1),Q(void 0),P(Le),Ee({title:"Schedule saved",detail:Le.recurrence?Wr(Le.recurrence,Le.timezone):jr(Le.preset??null,Le.cronExpr,Le.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(X){await Ce(X,"Failed to save schedule")}finally{I(!1)}}},oe=async()=>{if(!n||!D)return;const X=D.updatedAt;I(!0),W(null);try{const ie=await O.refetch();if(ie.isError||ie.data===void 0){W("Canonry could not verify the latest schedule. Try again before updating it.");return}const G=ie.data.find(be=>be.kind==="answer-visibility")??null;if(!G||G.updatedAt!==X){W("This schedule changed elsewhere. Review the latest version and try again.");return}const he={timezone:G.timezone,enabled:!G.enabled,providers:G.providers,expectedUpdatedAt:X};G.recurrence?he.recurrence=G.recurrence:G.preset?he.preset=G.preset:he.cron=G.cronExpr;const Le=await to(t,he);P(Le),Ee({title:Le.enabled?"Schedule resumed":"Schedule paused",detail:Le.recurrence?Wr(Le.recurrence,Le.timezone):jr(Le.preset??null,Le.cronExpr,Le.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(ie){await Ce(ie,"Failed to update schedule")}finally{I(!1)}},Ne=async()=>{if(!n||!D)return;const X=D.updatedAt;V(!0),W(null);try{await gm(t,X),P(null),l(!1),Q(void 0),Ee({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(ie){await Ce(ie,"Failed to remove schedule")}finally{V(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),n&&!U&&!se&&!r&&e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:re,children:D?Ya.edit:"+ Set schedule"})]}),U&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),F&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:F}),!U&&se&&e.jsxs(ve,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{O.refetch()},children:"Retry"})]}),!U&&!se&&!r&&D===null&&e.jsx(ve,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?_n:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!U&&!se&&!r&&D!==null&&e.jsx(ve,{className:"surface-card compact-card",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[s&&e.jsx("p",{className:"text-sm text-secondary",children:_n}),e.jsx("p",{className:"text-sm font-medium text-strong",children:D.recurrence?Wr(D.recurrence,D.timezone):jr(D.preset??null,D.cronExpr,D.timezone)}),!D.recurrence&&e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:D.cronExpr})]}),D.enabled&&D.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",pm(D.nextRunAt,D.timezone)]}),D.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(D.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(je,{tone:D.enabled?"positive":"neutral",children:D.enabled?"Active":"Paused"}),n&&e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:q,onClick:Xe(oe),children:D.enabled?Ya.pause:Ya.resume}),n&&e.jsx(T,{type:"button",variant:"ghost",size:"sm",disabled:w,onClick:Xe(Ne),children:w?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[E&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",role:"alert",children:[e.jsx("p",{children:"This schedule changed elsewhere. Load the latest version before saving."}),e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:ne,children:"Load latest schedule"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Frequency",value:i,onChange:X=>c(X.target.value),children:wb.map(X=>e.jsx("option",{value:X.value,children:X.label},X.value))})]}),i!=="calendar"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:d,disabled:i==="twice-daily"||i==="custom",onChange:X=>h(parseInt(X.target.value)),children:Array.from({length:24},(X,ie)=>e.jsx("option",{value:ie,children:xm(ie)},ie))})]})]}),i==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:u,onChange:X=>p(X.target.value)})]}),i==="calendar"&&e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Repeat every"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Repeat every days",type:"number",min:"1",max:"3650",value:g,onChange:X=>m(Number(X.target.value))}),e.jsx("p",{className:"text-xs text-muted",children:"days"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Start date"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Start date",type:"date",value:y,onChange:X=>x(X.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Recurrence time",type:"time",value:b,onChange:X=>N(X.target.value)})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Timezone",value:k?"Other":C,onChange:X=>{X.target.value==="Other"?(f(!0),M("Other")):(f(!1),M(X.target.value))},children:[Nl.map(X=>e.jsx("option",{value:X,children:X},X)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),k&&e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:v,onChange:X=>S(X.target.value)})]}),F&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:F}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:()=>{l(!1),Q(void 0),W(null)},children:"Cancel"}),e.jsx(T,{type:"button",size:"sm",disabled:q||O.isFetching||se||E||i==="custom"&&!u.trim()||i==="calendar"&&(!Number.isInteger(g)||g<1||g>3650||!y||!b),onClick:Xe(J),children:q?"Saving...":Ya.save})]})]})]})}const Cb=[{value:"citation.lost",label:"Citation lost"},{value:"citation.gained",label:"Citation gained"},{value:"run.completed",label:"Run completed"},{value:"run.failed",label:"Run failed"}];function kb({projectName:t}){const[s,n]=o.useState("loading"),[a,r]=o.useState(!1),[l,i]=o.useState(""),[c,d]=o.useState(["citation.lost","citation.gained"]),[h,u]=o.useState(!1),[p,g]=o.useState(null),[m,y]=o.useState({}),[x,b]=o.useState(new Set),N=!le()&&!Os();o.useEffect(()=>{bm(t).then(n).catch(()=>n([]))},[t]);const C=v=>{d(S=>S.includes(v)?S.filter(q=>q!==v):[...S,v])},M=async()=>{if(!(!l.trim()||c.length===0)){u(!0),g(null);try{const v=await vm(t,{channel:"webhook",url:l.trim(),events:c});n(S=>S==="loading"?[v]:[...S,v]),i(""),d(["citation.lost","citation.gained"]),r(!1),Ee({title:"Webhook added",detail:`Notifications will be sent to ${v.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(v){g(v instanceof Error?v.message:"Failed to add webhook")}finally{u(!1)}}},k=async v=>{if(!x.has(v)){b(S=>new Set(S).add(v));try{await Nm(t,v),n(S=>S==="loading"?S:S.filter(q=>q.id!==v)),Ee({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${v}`,dedupeMode:"drop"})}catch(S){g(S instanceof Error?S.message:"Failed to remove webhook")}finally{b(S=>{const q=new Set(S);return q.delete(v),q})}}},f=async v=>{y(S=>({...S,[v]:{state:"testing"}}));try{const S=await jm(t,v);y(q=>({...q,[v]:{state:S.ok?"ok":"fail",status:S.status}})),S.ok&&Ee({title:"Test notification sent",detail:`Webhook returned status ${S.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${v}`,dedupeMode:"replace"})}catch{y(S=>({...S,[v]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),N&&s!=="loading"&&e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),g(null)},children:a?"Cancel":"+ Add webhook"})]}),N&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:l,onChange:v=>i(v.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Cb.map(v=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:c.includes(v.value),onChange:()=>C(v.value)}),e.jsx("span",{className:"text-sm text-neutral",children:v.label})]},v.value))})]}),p&&e.jsx("p",{className:"text-negative-400 text-sm",children:p}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),g(null)},children:"Cancel"}),e.jsx(T,{type:"button",size:"sm",disabled:h||!l.trim()||c.length===0,onClick:Xe(M),children:h?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(ve,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-neutral break-all",title:v.urlHost,children:v.urlDisplay??v.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:v.events.map(S=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-strong bg-surface-inset px-2 py-0.5 text-[10px] font-medium text-secondary uppercase tracking-wide",children:S.replace("."," ")},S))})}),e.jsx("td",{children:e.jsx(je,{tone:v.enabled?"positive":"neutral",children:v.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[m[v.id]&&(()=>{const S=m[v.id],q=S.state==="testing"?"Sending…":S.state==="ok"?`Delivered${S.status?` (${S.status})`:""}`:`Failed${S.status?` (${S.status})`:""}`;return e.jsx(je,{tone:S.state==="ok"?"positive":S.state==="fail"?"negative":"neutral",children:q})})(),N&&e.jsx(T,{variant:"ghost",size:"sm",type:"button",disabled:m[v.id]?.state==="testing",onClick:()=>{f(v.id)},children:"Test"}),N&&e.jsx(T,{variant:"ghost",size:"sm",type:"button",disabled:x.has(v.id),onClick:()=>{k(v.id)},children:x.has(v.id)?"Removing…":"Remove"})]})})]},v.id))})]}),p&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:p})]})]})}function Ab({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:l}){return le()||us()?null:e.jsx(Sm,{open:t,onOpenChange:n,children:e.jsxs(Cm,{onCloseAutoFocus:i=>{r&&(i.preventDefault(),r())},children:[e.jsxs(km,{children:[e.jsx(Am,{children:"Run AI sweep for the whole project?"}),e.jsxs(Rm,{children:["Runs all tracked queries for ",s,". View filters do not limit the sweep. Provider charges apply."]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsx(T,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(Ye,{disabled:l,onClick:a,children:"Run project-wide sweep"})]})]})})}const wl=2e3,Sl=3e5;function Rb(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Pb(t,s){t.setQueriesData({predicate:n=>n.queryKey[0]==="project-dashboard-full"&&n.queryKey[1]===s.id},n=>!n||typeof n!="object"||!("project"in n)?n:{...n,project:s})}function Ib({projectName:t,refreshNonce:s}){const n=ps(),[a,r]=o.useState(null),[l,i]=o.useState([]),[c,d]=o.useState(null),[h,u]=o.useState([]),[p,g]=o.useState([]),[m,y]=o.useState(null),[x,b]=o.useState(""),[N,C]=o.useState(""),[M,k]=o.useState(""),[f,v]=o.useState(!0),[S,q]=o.useState(!1),[I,w]=o.useState(null),[V,F]=o.useState("performance");o.useEffect(()=>{W()},[t,s]);async function W(){v(!0),w(null);try{const P=await n.fetchQuery({...Yl({client:H,path:{name:t}}),staleTime:zt});if(r(P),P.connected){const[Y,re,ne,de]=await Promise.all([n.fetchQuery({...ph({client:H,path:{name:t}}),staleTime:zt}).catch(()=>null),n.fetchQuery({...xh({client:H,path:{name:t}}),staleTime:zt}).catch(()=>[]),n.fetchQuery({...gh({client:H,path:{name:t}}),staleTime:zt}).catch(()=>[]),P.siteUrl?Promise.resolve([]):n.fetchQuery({...fh({client:H,path:{name:t}}),staleTime:zt}).then(Ce=>Ce.sites).catch(()=>[])]);d(Y),u(re),g(ne),i(de)}else d(null),u([]),g([]),i([])}catch(P){w(P instanceof Error?P.message:"Failed to load Bing data")}finally{v(!1)}}async function B(){if(N.trim()){w(null);try{const P=await yh(t,N.trim());await It(n,"bing"),C(""),P.availableSites.length>0&&i(P.availableSites),await W()}catch(P){w(P instanceof Error?P.message:"Failed to connect")}}}async function Q(){try{await bh(t),await It(n,"bing"),r(null),i([]),d(null),u([]),g([]),y(null),k(""),w(null)}catch(P){w(P instanceof Error?P.message:"Failed to disconnect")}}async function te(){if(M)try{await vh(t,M),await It(n,"bing"),await W()}catch(P){w(P instanceof Error?P.message:"Failed to set site")}}async function O(){if(x.trim())try{const P=await jh(t,x.trim());await It(n,"bing"),y(P),u(Y=>[P,...Y])}catch(P){w(P instanceof Error?P.message:"Inspection failed")}}async function U(P){q(!0),w(null);try{const Y=await ao(t,{urls:[P]}),{succeeded:re,failed:ne,total:de}=Y.summary;Ee({title:"Bing submission requested",detail:ne===0?`${re} URL submitted to Bing.`:`${re}/${de} submitted successfully, ${ne} failed.`,tone:ne===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${P}`,dedupeMode:"replace"})}catch(Y){const re=Y instanceof Error?Y.message:"Submission failed";w(re),Ee({title:"Bing submission failed",detail:re,tone:"negative",dedupeKey:`bing:indexing:${t}:${P}`,dedupeMode:"replace"})}finally{q(!1)}}async function se(){q(!0),w(null),Ee({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const P=await ao(t,{allUnindexed:!0}),{succeeded:Y,failed:re,total:ne}=P.summary;Ee({title:"Bing submissions requested",detail:re===0?`${Y}/${ne} URL${ne!==1?"s":""} submitted to Bing.`:`${Y}/${ne} submitted successfully, ${re} failed.`,tone:re===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(P){const Y=P instanceof Error?P.message:"Batch submission failed";w(Y),Ee({title:"Bing submissions failed",detail:Y,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{q(!1)}}if(f)return e.jsx(ve,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return le()?e.jsxs(ve,{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(je,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(ve,{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(je,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:N,onChange:P=>C(P.target.value),onKeyDown:P=>{P.key==="Enter"&&B()}}),e.jsx(Ye,{size:"sm",disabled:!N.trim(),onClick:Xe(B),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-secondary hover:text-neutral underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),I&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:I})]});if(!a.siteUrl)return e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{tone:"positive",children:"Connected"}),!le()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Xe(Q),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.domain})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Ht(a.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Select site"}),l.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:M,onChange:P=>k(P.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(P=>e.jsxs("option",{value:P.url,children:[P.url,P.verified?" (verified)":""]},P.url))]}),!le()&&e.jsx(Ye,{size:"sm",disabled:!M,onClick:Xe(te),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-muted",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),I&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:I})]});const D=[{key:"performance",label:"Performance",eyebrow:"Performance",title:"Search performance"},{key:"coverage",label:"Coverage",eyebrow:"Coverage",title:"Index monitoring"},{key:"inspections",label:"Inspections",eyebrow:"Inspection",title:"URL inspection history"}],E=D.find(P=>P.key===V)??D[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{tone:"positive",children:"Connected"}),!le()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Xe(Q),children:"Disconnect"})]})]}),I&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:I}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["This project uses ",e.jsx("code",{children:a.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Ht(a.updatedAt):"—"})]})]})]})]}),e.jsxs(ve,{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:E.eyebrow}),e.jsx("h3",{children:E.title})]}),e.jsx("p",{className:"text-xs text-muted",children:c?.lastInspectedAt?`Last inspected ${Ht(c.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:D.map(P=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${V===P.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>F(P.key),children:P.label},P.key))}),V==="coverage"&&c&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(La,{label:"Indexed",value:c.summary.indexed,tone:"positive"}),e.jsx(La,{label:"Not in index",value:c.summary.notIndexed+(c.summary.unknown??0),tone:"negative"}),e.jsx(La,{label:"Status unknown",value:c.summary.unknown??0,tone:"neutral"}),e.jsx(La,{label:"Coverage",value:et(c.summary.percentage,Qn.percent),tone:"neutral"})]}),c.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",c.notIndexed.length,")"]}),!le()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:S,onClick:Xe(se),children:S?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!le()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:c.notIndexed.map(P=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:P.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.httpCode??"—"}),!le()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:S,onClick:()=>{U(P.url)},children:"Submit"})})]},P.id))})]})})]}),(c.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(c.unknown??[]).length,")"]}),!le()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:S,onClick:Xe(se),children:S?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!le()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(c.unknown??[]).map(P=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:P.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.lastCrawledDate?Ht(P.lastCrawledDate):"—"}),!le()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:S,onClick:()=>{U(P.url)},children:"Submit"})})]},P.id))})]})})]}),c.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",c.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:c.indexed.map(P=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:P.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.lastCrawledDate?Ht(P.lastCrawledDate):"—"})]},P.id))})]})})]})]}),V==="coverage"&&!c&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),V==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!le()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:x,onChange:P=>b(P.target.value),onKeyDown:P=>{P.key==="Enter"&&O()}}),e.jsx(Ye,{size:"sm",disabled:!x.trim(),onClick:Xe(O),children:"Inspect"})]}),m&&e.jsxs("div",{className:"rounded border border-base bg-bg-elevated/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-strong",children:m.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:m.inIndex?"text-positive-400":"text-negative-400",children:m.inIndex?"Yes":"No"})," · ","HTTP: ",m.httpCode??"—"," · ","Crawled: ",m.lastCrawledDate??"—"]})]}),h.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:h.map(P=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:P.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(je,{tone:P.inIndex?"positive":"negative",children:P.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Ht(P.inspectedAt)})]},P.id))})]})})]}),V==="performance"&&e.jsx("div",{className:"mt-4",children:p.length===0?e.jsx("p",{className:"text-xs text-muted",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:qa[bn.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:qa[bn.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:qa[bn.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:qa[bn.Position]})]})}),e.jsx("tbody",{children:p.map((P,Y)=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:P.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:P.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:P.impressions}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:et(P.ctr)}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:P.averagePosition.toFixed(1)})]},Y))})]})})})]})]})}function Tb({projectName:t}){const s=ps(),[n,a]=o.useState("google"),[r,l]=o.useState(!0),[i,c]=o.useState("idle"),[d,h]=o.useState(null),u=o.useRef(null),[p,g]=o.useState(null),[m,y]=o.useState(null),[x,b]=o.useState(0);async function N(M=!1){M||l(!0),h(null);try{const[k,f]=await Promise.all([s.fetchQuery({...Ni({client:H,path:{name:t}}),staleTime:zt}).catch(()=>[]),s.fetchQuery({...Yl({client:H,path:{name:t}}),staleTime:zt}).catch(()=>null)]),v=k.find(S=>S.connectionType==="gsc")??null;g(v),y(f)}catch(k){h(k instanceof Error?k.message:"Failed to load search engine connections")}finally{l(!1)}}async function C(){if(i!=="idle")return;u.current?.abort();const M=new AbortController;u.current=M;const k=M.signal;c("syncing"),h(null),Ee({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const f=[],v=[];try{async function S(){if(!p)return;const w=await mh(t);if(!w?.id)return;const V=Date.now()+Sl;for(;Date.now()<V;){if(k.aborted||(await new Promise(W=>setTimeout(W,wl)),k.aborted))return;const F=await Yr(w.id).catch(()=>null);if(!F)break;if(["completed","failed","cancelled"].includes(F.status)){F.status!=="completed"&&f.push(`Google sync ${F.status}`);return}}v.push("Google sync is still running — search data will appear shortly")}async function q(){if(!m?.connected)return;const w=await hh(t).catch(()=>null);if(!w?.id){f.push("Bing sweep could not be started");return}const V=Date.now()+Sl;for(;Date.now()<V;){if(k.aborted||(await new Promise(W=>setTimeout(W,wl)),k.aborted))return;const F=await Yr(w.id).catch(()=>null);if(!F)break;if(["completed","failed","cancelled","partial"].includes(F.status)){F.status==="failed"?f.push("Bing sweep failed"):F.status==="partial"&&v.push("Bing sweep finished with some pages unverified");return}}v.push("Bing sweep is still running — coverage will update shortly")}const I=await Promise.allSettled([S(),q()]);for(const w of I)w.status==="rejected"&&f.push(w.reason instanceof Error?w.reason.message:"Sync failed");if(await Promise.all([It(s,"gsc"),It(s,"bing")]),k.aborted)return;if(c("reloading"),await N(!0),b(w=>w+1),f.length>0){const w=`Partial refresh: ${[...f,...v].join("; ")}`;h(w),Ee({title:"Search coverage partially refreshed",detail:w,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else v.length>0?Ee({title:"Search coverage refresh incomplete",detail:v.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):Ee({title:"Search coverage refreshed",detail:"Google and Bing workspaces are reloaded with the latest stored coverage.",tone:"positive",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}catch(S){if(!k.aborted){const q=S instanceof Error?S.message:"Refresh failed";h(q),Ee({title:"Search coverage refresh failed",detail:q,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{k.aborted||c("idle")}}return o.useEffect(()=>(N(),()=>{u.current?.abort()}),[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([M,k])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===M,className:`project-subnav-link ${n===M?"project-subnav-link-active":""}`,onClick:()=>a(M),children:k},M))}),!le()&&e.jsxs(Ye,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{C()},children:[e.jsx(pa,{className:`h-3.5 w-3.5 ${i!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":i==="syncing"?"Refreshing search data…":i==="reloading"?"Reloading workspaces…":"Refresh search data"]})]}),d&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:d}),n==="google"&&e.jsx(Nx,{projectName:t,refreshNonce:x}),n==="bing"&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(Ib,{projectName:t,refreshNonce:x})]})]})}function Cl({label:t,summary:s,displayValue:n,tooltip:a}){const{figure:r,sign:l}=bi(s.value),i=s.progress!==void 0?Math.min(Math.max(s.progress,0),100):0;return e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("p",{className:"aeo-hero-row-label",children:[t,(a||s.tooltip)&&e.jsx(Be,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${ma[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[r,l?e.jsx("span",{className:"text-faint",children:l}):null]})}),e.jsx("div",{className:"aeo-hero-row-bar","aria-hidden":"true",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.tone}`,style:{width:`${i}%`}})})]})}function Mb({id:t,title:s,meta:n,defaultOpen:a=!1,children:r}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:a||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsx("h2",{className:"overview-disclosure-title",children:s}),e.jsxs("span",{className:"overview-disclosure-meta",children:[n&&e.jsx("span",{children:n}),e.jsx(Un,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:r})]})}function qb({insights:t,suggestedQueries:s,onManageQueries:n}){const{openEvidence:a}=vi(),r=n?s.rows:[];if(t.length===0&&r.length===0)return null;const l=g=>e.jsxs("div",{className:"py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:g.title}),g.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:g.detail}):null]}),e.jsx(je,{tone:g.tone,children:g.actionLabel})]}),g.affectedPhrases.length>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:["Evidence · ",g.affectedPhrases.length," affected ",g.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:g.affectedPhrases.map((m,y)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(ei,{state:m.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:m.query}),m.provider?e.jsx(uh,{provider:m.provider}):null,!le()&&m.evidenceId?e.jsx(T,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(m.evidenceId)},children:"View evidence"}):null]},m.evidenceId||`${g.id}-${y}`))})]}):null]},g.id),i=g=>e.jsxs("div",{className:"flex items-start justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:g.query}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:g.reason})]}),n?e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},g.query),c=t.slice(0,1),d=r.slice(0,1),h=t.slice(1),u=r.slice(1),p=h.length+u.length;return e.jsxs("section",{className:"visibility-disclosure-panel","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[c.map(l),d.map(i)]}),p>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[p," more ",p===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[h.map(l),u.map(i)]})]}):null]})}function Jb(t){const{projectName:s}=Jc({from:"/projects/$projectName"}),a=Vl()?.dashboard.projects.find(v=>v.project.name===s||v.project.id===s)?.project.name??null,r=$e({...wm({client:H}),enabled:!a}),l=a??r.data?.find(v=>v.name===s||v.id===s)?.name??null,i=Ql(),c=zl(t.tab,Hl(i)),[d,h]=o.useState(null),u=l!==null&&d===l,p=o.useCallback(()=>{l&&h(l)},[l]),{commandCenter:g,isLoading:m,overviewLoading:y,overviewError:x,isError:b,latestVisibilityRevision:N,competitorHistoryRevision:C,refetch:M}=Wl(l,{overview:c==="overview"&&u}),k=!a&&r.isLoading||m;return!l&&!a&&r.isSuccess&&!m?e.jsx("div",{className:"page-container",children:e.jsxs(ve,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(T,{asChild:!0,children:e.jsx(qs,{to:"/",children:"Return to overview"})})]})}):!g&&(b||r.isError)?e.jsxs("div",{className:"page-container",role:"alert",children:[e.jsx("p",{children:"Could not load this project."}),e.jsx(T,{type:"button",variant:"outline",onClick:()=>{Promise.all([r.refetch(),M()])},children:"Retry"})]}):!g||k?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(v=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},v))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(v=>e.jsx("div",{className:"skeleton-text-sm w-full"},v))})]})]}):e.jsx(Ob,{model:g,refetch:M,latestVisibilityRevision:N,competitorHistoryRevision:C,overviewLoading:y,overviewError:x,overviewRequested:u,onRequestOverview:p,...t})}function $b({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=o.useRef(null),l=o.useRef(null),[i,c]=o.useState(null);o.useLayoutEffect(()=>{const u=r.current,p=l.current;if(!u||!p)return;const g=()=>{const y=u.getBoundingClientRect().width;if(!y)return;const x=Number.parseFloat(getComputedStyle(u).columnGap)||0,b=new Map([...p.querySelectorAll("[data-project-tab]")].map(v=>[v.dataset.projectTab,v.getBoundingClientRect().width])),N=v=>b.get(v)??0,C=v=>v.reduce((S,q)=>S+N(q),0)+Math.max(0,v.length-1)*x,M=[...t.map(v=>v.key),...s.length?["more"]:[],...n?[n.key]:[]];let k=t.map(v=>v.key),f=!1;if(C(M)>y){const v=t.find(I=>I.key===a),S=v?[v.key]:[];f=!!(n&&C([...S,"more",n.key])>y);const q=["more",...n&&!f?[n.key]:[]];for(const I of t)if(I.key!==v?.key){if(C([...S,I.key,...q])>y)break;S.push(I.key)}k=t.filter(I=>S.includes(I.key)).map(I=>I.key)}c(v=>v?.settingsInMore===f&&v.visibleKeys.join()===k.join()?v:{visibleKeys:k,settingsInMore:f})};if(g(),typeof ResizeObserver>"u")return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g);const m=new ResizeObserver(g);return m.observe(u),m.observe(p),()=>m.disconnect()},[t,s,n,a]);const d=i?t.filter(u=>i.visibleKeys.includes(u.key)):t,h=[...t.filter(u=>!d.includes(u)),...s,...i?.settingsInMore&&n?[n]:[]];return e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",ref:r,children:[e.jsx("div",{className:"project-subnav-measure","aria-hidden":"true",children:e.jsxs("div",{className:"project-subnav-measure-row",ref:l,children:[[...t,...n?[n]:[]].map(u=>e.jsx("span",{className:"project-subnav-link","data-project-tab":u.key,children:u.label},u.key)),e.jsxs("span",{className:"project-subnav-link project-subnav-more-trigger","data-project-tab":"more",children:["More",e.jsx(Un,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),d.map(u=>e.jsx(qs,{to:u.href,search:p=>({...p,onboarding:void 0}),className:`project-subnav-link ${u.key===a?"project-subnav-link-active project-subnav-current":""}`,"aria-current":u.key===a?"page":void 0,children:e.jsx("span",{className:"project-subnav-label",children:u.label})},u.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(Lb,{items:h,activeTab:a}),n&&!i?.settingsInMore&&e.jsx(qs,{to:n.href,search:u=>({...u,onboarding:void 0}),className:`project-subnav-link ${a==="settings"?"project-subnav-link-active":""}`,"aria-current":a==="settings"?"page":void 0,children:n.label})]})]})}function Lb({items:t,activeTab:s}){const[n,a]=o.useState(!1),r=o.useRef(null),l=o.useRef(null),i=o.useRef("first"),c=o.useId(),d=t.map(u=>u.key).join();if(o.useEffect(()=>{a(!1)},[d]),o.useEffect(()=>{if(!n)return;const u=r.current?.querySelectorAll('[role="menuitem"]');(i.current==="last"?u?.[u.length-1]:u?.[0])?.focus()},[n]),o.useEffect(()=>{if(!n)return;const u=g=>{r.current&&!r.current.contains(g.target)&&a(!1)},p=g=>{g.key==="Escape"&&(a(!1),l.current?.focus())};return document.addEventListener("pointerdown",u),document.addEventListener("keydown",p),()=>{document.removeEventListener("pointerdown",u),document.removeEventListener("keydown",p)}},[n]),t.length===0)return null;const h=t.some(u=>u.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",ref:l,className:`project-subnav-link project-subnav-more-trigger ${h?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?c:void 0,onClick:()=>{i.current="first",a(u=>!u)},onKeyDown:u=>{u.key!=="ArrowDown"&&u.key!=="ArrowUp"||(u.preventDefault(),i.current=u.key==="ArrowUp"?"last":"first",a(!0))},children:["More",e.jsx(Un,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:c,"aria-label":"More project sections",onKeyDown:u=>{const p=[...u.currentTarget.querySelectorAll('[role="menuitem"]')],g=p.indexOf(document.activeElement),m=u.key==="Home"?0:u.key==="End"?p.length-1:u.key==="ArrowDown"?(g+1)%p.length:u.key==="ArrowUp"?(g-1+p.length)%p.length:null;m!==null&&(u.preventDefault(),p[m]?.focus())},onBlur:u=>{r.current?.contains(u.relatedTarget)||a(!1)},children:t.map(u=>e.jsx(qs,{to:u.href,search:p=>({...p,onboarding:void 0}),role:"menuitem",tabIndex:-1,className:`project-subnav-menu-item ${u.key===s?"project-subnav-menu-item-active":""}`,"aria-current":u.key===s?"page":void 0,onClick:()=>a(!1),children:u.label},u.key))}):null]})}const Eb=20,Db=5;function Ob({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r,overviewLoading:l,overviewError:i,overviewRequested:c,onRequestOverview:d}){const h=Xc(),u=ps(),{account:p,canWrite:g}=Sn(),[m,y]=o.useState(null),x=o.useRef(null),b=Vl(),N=s.project.name,C=b?.dashboard.projects.some($=>$.project.name===N)??!1,M=Zc({strict:!1}),k=Pm(M),f=Jh(k),v=$e({...Im({client:H,path:{name:N}}),enabled:!le()&&!!N&&(g||t==="portfolio"||t==="overview"||t==="settings"||f),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),S=b?b.dashboard.settings.providerStatuses.filter($=>$.state==="ready").map($=>so($.name)):void 0,q=v.data?.answerVisibilityProviderReady,I=S,w=s.project.providers.map(so),V=I?.some($=>w.length===0||w.includes($))===!0,F=w.length===0||w.includes(Tm),W=$e({...Mm({client:H}),enabled:!le()&&g&&q===void 0&&F&&!V,staleTime:6e4,retry:!1}),B=F?W.isSuccess?typeof W.data.browserVersion=="string":W.isError?!1:void 0:!1,Q=q??qm({projectProviders:w,configuredApiProviders:I,cdpConfigured:B}),te=o.useMemo(()=>Hl(Ql()),[]),O=zl(t,te),U=o.useMemo(()=>s.competitors.map($=>$.domain),[s.competitors]),[se,D]=o.useState(!1),[E,P]=o.useState(!1),Y=$m(),re=o.useCallback(($,ge)=>{h({to:".",search:fe=>Lm(fe,$),replace:ge?.replace===!0})},[h]),ne=M.queryWorkspace==="research"||O==="discovery"&&M.queryWorkspace===void 0?"research":"tracked",de=nc(ne,sc(p?.role,p?.role==="viewer"?_l():null)),Ce=$e({...Si({client:H,path:{name:N}}),enabled:!le()&&(O==="queries"||O==="discovery")&&de==="tracked"}),J=M.manageQueries===!0,oe=o.useCallback(()=>{h({to:".",replace:!0,search:$=>({...$,siteHealthRunId:void 0})})},[h]),[Ne,X]=o.useState(J),[ie,G]=o.useState(""),[he,Le]=o.useState(!1),[be,ee]=o.useState(null),[Re,De]=o.useState("30d"),[qe,xe]=o.useState(void 0),[K,Oe]=o.useState(""),[R,ye]=o.useState(!1),[Ke,ze]=o.useState(null),[Je,pe]=o.useState(!1),ht=Em(M),[Ve,tt]=o.useState(void 0),[Wt,dt]=o.useState(void 0),st=o.useCallback($=>{tt($.search),$.sort&&dt($.sort),h({to:".",search:ge=>({...ge,...Dm($)}),replace:!1})},[h]),[pt,St]=o.useState(!1),Rt=s?.project.displayName||s?.project.name||N,Ge=Om(),A=$e({...no({client:H,path:{name:N}}),enabled:O==="portfolio"&&!!N,staleTime:0,refetchOnMount:"always"}),ke=$e({...Fm({client:H,path:{name:N}}),enabled:!le()&&!!N&&(g||O==="portfolio"||O==="overview"||O==="settings"),staleTime:0,refetchOnMount:"always"}),ue=ke.data?.active??null,He=ke.data!==void 0,Tt=new Set(ue&&Number(ue.plan.schemaVersion)===2?ue.plan.groups?.map($=>$.stableKey)??[]:[]),ot={...ht.scope==="group"&&!!ht.groupKey&&He&&!Tt.has(ht.groupKey)?{scope:"all",queryClass:ht.queryClass}:ht,...Ve?{search:Ve}:{}},Z=ue===null?null:Number(ue.plan.schemaVersion),Fe=ue?.revision??0,Ie=He?`${N}:${Fe}`:null,Pe=o.useRef(null);o.useEffect(()=>{const $=Pe.current;Ie!==null&&(Pe.current=Ie),Km($,Ie)&&(st({scope:"all",queryClass:"all"}),St(!1))},[Ie,st]);const qt={client:H,path:{name:N},query:{scope:ot.scope,...ot.groupKey?{groupKey:ot.groupKey}:{},queryClass:ot.queryClass,...ot.search?{search:ot.search}:{},...Wt?{sort:Wt}:{},limit:50}},vt=kl({...Gm(qt),enabled:!1,initialPageParam:qt,getNextPageParam:($,ge)=>{if(!$.properties.nextCursor)return;const fe=ge[0]?.measurement.displayedRunId;return{path:qt.path,query:{...qt.query,cursor:$.properties.nextCursor,...fe?{runId:fe}:{}}}},placeholderData:yi,staleTime:0,refetchOnMount:"always"}),Yt=vt.data?.pages[0]?.measurement.displayedRunId,nt=$e({..._m({client:H,path:{name:N},query:{revision:Fe,...Yt?{runId:Yt}:{}}}),enabled:O==="overview"&&!!N&&ue!==null&&Z===1,staleTime:0,refetchOnMount:"always"}),$t=ke.data!==void 0,Zt=A.data!==void 0,vs=ke.isPending&&!$t,js=ke.isError&&!$t,Ns=A.isPending&&!Zt,Gs=A.isError&&!Zt,ft=nt.data!==void 0,xs=ub({activePlanSchemaVersion:v.data?.activeSchemaVersion??Z,hasDraft:v.data?.draft!==null&&v.data?.draft!==void 0}),Ze=xs.surface==="simple-overview",Ft=v.data===void 0&&ke.data===void 0&&(ke.isLoading||v.isLoading);o.useEffect(()=>{O==="overview"&&Ze&&!Ft&&d()},[Ft,Ze,d,O]);const es=Xh({tab:O,surface:Ft?"unresolved":xs.surface,embedded:le(),scoped:f,queryWorkspace:de,tracking:Ce.isError?{state:"error"}:Ce.data?{state:"ready",mode:Ce.data.mode,scopeUnavailable:ac(Ce.data,k)}:{state:"pending"}}),as=Sc(N,k,{enabled:es.kind==="report-picker"}),gs=O==="overview"&&Ze&&!Ft,jt=Wl(N,{evidence:gs}),Pt=jt.commandCenter?.visibilityEvidence??s.visibilityEvidence,ts=o.useMemo(()=>{const $=new Map(Pt.map(fe=>[Kn(fe.query),fe.queryClass??null])),ge=Um(Bm(s.project));return fe=>{const gt=$.get(Kn(fe));return gt!==void 0?gt:ge?.classify(fe)??null}},[Pt,s.project]),Kt=o.useMemo(()=>[...new Set([...Pt.map($=>$.query),...s.movementComparison.addedQueries,...s.movementComparison.removedQueries])],[Pt,s.movementComparison]),_s=o.useMemo(()=>s.visibilitySweeps.map($=>$.createdAt),[s.visibilitySweeps]),Nt=g&&!le()&&!us()&&O!=="overview",Jt=$e({...no({client:H,path:{name:N}}),enabled:Nt,staleTime:wi,refetchOnWindowFocus:"always"}),xt=Z===2&&k.measurementScope==="group"?k.measurementScopeKey:void 0,_=Z===2&&k.measurementScope==="project",ae=o.useMemo(()=>{if(!(ue?.plan.schemaVersion!==2||!xt))return ue.plan.groups.find($=>$.stableKey===xt)},[ue,xt]),Ae={client:H,path:{name:N},query:{window:Re,queryClass:Z===2&&k.queryClass!=="unknown"?k.queryClass:"non-brand",...xt?{groupKey:xt}:{},..._?{scope:"all-markets"}:{}}},me=O==="overview"&&!k.marketKey&&!!N&&(Ze||He)&&!Ft&&(Ze||(k.measurementScope==="project"||Z===2&&k.measurementScope==="group")&&k.queryClass!=="unknown"&&(Z===2||k.queryClass!=="branded")),[Te,_e]=o.useState(null);o.useEffect(()=>{me||_e(null)},[me]),o.useEffect(()=>{_e(null)},[N]);const mt=Te===N,yt=me&&mt,ss=$e({...Vm(Ae),enabled:yt,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});Qm(N,JSON.stringify([r,s.competitors.map($=>$.domain).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,Fe,v.data?.draft?.etag??null]),yt);const L=ss.isError?ss.data===void 0?"Could not load competitors over time. Your pinned competitors remain available.":"Could not refresh competitors over time. Showing the last available data.":void 0,we=o.useMemo(()=>s.competitors.map($=>({domain:$.domain,label:$.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:$.citationCount,answeredResults:$.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),lt=o.useMemo(()=>{if(ue?.plan.schemaVersion!==2)return we;const $=xt?ae?.competitors??[]:ue.plan.groups.flatMap(fe=>fe.competitors),ge=new Map;for(const fe of $){const gt=fe.domain.trim().toLowerCase();!gt||ge.has(gt)||ge.set(gt,{domain:fe.domain,label:fe.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const fe of we){const gt=fe.domain.trim().toLowerCase();!gt||ge.has(gt)||ge.set(gt,fe)}return[...ge.values()]},[ue,xt,we,ae]),Lt=Z===2?lt:we,Xt=Ot({...zm({client:H}),meta:{skipGlobalErrorToast:!0}}),Qe=v.data!==void 0?"success":v.isError?"error":"pending",bt=o.useMemo(()=>{const $=vt.data?.pages;return $?!Sh($):!1},[vt.data]),rs=o.useMemo(()=>{const $=vt.data?.pages,ge=$?.[0],fe=$?.at(-1);if(!(!ge||!fe||bt))return{...ge,properties:{...ge.properties,items:$.flatMap(gt=>gt.properties.items),nextCursor:fe.properties.nextCursor}}},[bt,vt.data]),Hn=o.useMemo(()=>{if(ue)return ue.plan.schemaVersion===1?nt.data?bb(ue,nt.data):void 0:rs?Ch({overview:rs,activePlan:ue,sort:Wt,report:nt.data,reportState:rs.measurement.displayedRunId===void 0?"ready":nt.isFetching&&nt.data===void 0?"loading":nt.isError&&nt.data===void 0?"error":nt.data?"ready":"loading"}):void 0},[ue,nt.data,nt.isError,nt.isFetching,rs]),fs=Z===2?bt?"error":vt.isPending?"loading":vt.isError&&Hn===void 0?"error":"ready":nt.isPending&&!ft?"loading":nt.isError&&!ft?"error":"ready",rn=(s?.recentRuns??[]).some($=>$.kind===Zs["answer-visibility"]&&($.status===Ms.running||$.status===Ms.queued)),Et=s.queryCounts.total>0,ws=o.useMemo(()=>(s?.project.locations??[]).map($=>$.label),[s?.project.locations]),on=o.useMemo(()=>new Set(Pt.map($=>$.location??"")),[Pt]),Sa=on.has(""),Wn=o.useMemo(()=>[...new Set(Pt.map($=>$.query))].sort(($,ge)=>$.localeCompare(ge)),[Pt]),ln=Wn.length>0||s.queryCounts.total>0||(Jt.data?.length??0)>0||ue!==null,ka=g&&!ln&&(ke.data===void 0&&ke.isPending||Jt.isLoading||gs&&jt.evidenceLoading),Ss=g&&(v.isError&&!v.isFetching||Nt&&Jt.isError&&!Jt.isFetching),Us=g&&!Ss&&(ka||Q===void 0||v.isFetching),Bs=!Us&&!Ss&&ln&&Q===!0,Cn=g&&!Us&&!Bs,kn=!le()&&O==="overview"&&Cn&&!ln,Yn=$e({...Hm({client:H,path:{name:N},query:{limit:Eb}}),enabled:kn&&!!N,retry:!1}),An=Yn.isSuccess&&Yn.data.scans.some($=>$.status==="completed"||$.status==="partial"),hr=kn&&Yn.isSuccess&&!An,Vs=kn&&An,cn=$e({...Bl({client:H,path:{name:N}}),enabled:!le()&&!us()&&!!N,retry:!1}).data?.find($=>$.kind===Zs["answer-visibility"]),Jn=cn?.enabled&&cn.nextRunAt?Wm(cn.nextRunAt,cn.timezone):null,Xn=Jn?`Next AI sweep ${Jn}`:null,Aa=o.useMemo(()=>{const $=[...on].filter(Boolean);return $.length>1?$:ws},[on,ws]);o.useEffect(()=>{if(!gs||qe===void 0||qe===""||!N){ze(null),pe(!1);return}pe(!0),Ym(N,qe,20).then($=>{ze($),pe(!1)}).catch(()=>{ze(null),pe(!1)})},[qe,N,gs]);const Qs=o.useMemo(()=>{if(!Ke)return null;const $=new Map;for(const ge of Ke){for(const[fe,gt]of Object.entries(ge.providerRuns??{}))$.set(`${ge.query}::${fe}`,gt.map(ks=>({runId:ks.runId,citationState:ks.citationState,createdAt:ks.createdAt,answerMentioned:ks.answerMentioned,visibilityState:ks.visibilityState,visibilityTransition:ks.visibilityTransition,mentionState:ks.mentionState,mentionTransition:ks.mentionTransition})));(!ge.providerRuns||Object.keys(ge.providerRuns).length===0)&&$.set(`${ge.query}::`,ge.runs.map(fe=>({runId:fe.runId,citationState:fe.citationState,createdAt:fe.createdAt,answerMentioned:fe.answerMentioned,visibilityState:fe.visibilityState,visibilityTransition:fe.visibilityTransition,mentionState:fe.mentionState,mentionTransition:fe.mentionTransition})))}return $},[Ke]),Zn=o.useMemo(()=>{const $=qe!==void 0?Pt.filter(ge=>qe===""?!ge.location:ge.location===qe):Pt;return Qs?$.map(ge=>{const fe=Qs.get(`${ge.query}::${ge.provider}`)??Qs.get(`${ge.query}::`);return fe?{...ge,runHistory:fe}:ge}):$},[Pt,qe,Qs]);async function Ra(){if(!(m!==N||!g||le()||us()||Ge.isPending||rn||!Bs))try{await Ge.mutateAsync({projectName:N,projectLabel:Rt,sourceAction:"project-run"}),y(null),n()}catch{}}function pr(){h({to:"/setup",search:{experience:"legacy",setupProject:N}})}function Pa(){h({to:"/projects/$projectName/technical-aeo",params:{projectName:N}})}async function xr(){P(!0);try{await dh(N),Ee({title:"Project deleted",detail:`${Rt} was removed.`,tone:"positive",dedupeKey:`project:delete:${N}`,dedupeMode:"drop"}),h({to:"/"}),n()}catch($){console.error("Failed to delete project:",$)}finally{P(!1)}}async function Ia(){const $=ie.split(`
7
- `).map(ge=>ge.trim()).filter(Boolean);if($.length!==0){Le(!0);try{await th(N,$),n(),G("")}finally{Le(!1)}}}async function j($){ee($);try{await eh(N,[$]),n()}catch(ge){Ee({title:"Could not remove query",detail:ge instanceof Error?ge.message:`Failed to remove "${$}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{ee(null)}}async function z($){const ge=$.trim();if(!ge)return!1;try{return await Xm(N,[ge]),n(),!0}catch(fe){return Ee({title:"Could not add competitor",detail:fe instanceof Error?fe.message:`Failed to add ${ge}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function ce($){const ge=s.competitors.find(fe=>fe.domain===$);if(!ge)return Ee({title:"Could not remove competitor",detail:`Could not find ${$} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await Zm(N,ge.id),n(),!0}catch(fe){return Ee({title:"Could not remove competitor",detail:fe instanceof Error?fe.message:`Failed to remove ${ge.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function Se($){const ge=$.trim();if(!ge||!xt||Z!==2||!g||le()||Xt.isPending)return!1;try{const fe=await Xt.mutateAsync({client:H,path:{name:N},headers:{"Idempotency-Key":Rb()},body:{expectedActiveRevision:Fe,groupKey:xt,domain:ge}});return Promise.allSettled([v.refetch()]),Ee({title:fe.draftCreated?"Competitor added to a market draft":"Market competitor updated",detail:`Publish the Advanced Measurement draft before ${ge} is used in future market runs.`,tone:"positive",dedupeKey:`competitor:market-pin:${xt}:${ge}`,dedupeMode:"replace"}),!0}catch(fe){return Ee({title:"Could not add market competitor",detail:fe instanceof Error?fe.message:`Failed to add ${ge} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function at($,ge){const fe=await ih($,ge);return await u.invalidateQueries({queryKey:oh({client:H})}),u.setQueryData(lh({client:H,path:{name:$}}),fe),Pb(u,fe),ge.providers!==void 0&&await u.invalidateQueries({queryKey:ch({client:H,path:{name:$}}),exact:!0}),fe}const Ue=`/projects/${encodeURIComponent(s.project.name)}`,ut=[{key:"overview",label:"AI Visibility",href:Ue},{key:"search-console",label:"Search Engines",href:`${Ue}/search-console`},{key:"activity",label:"Activity",href:`${Ue}/activity`},{key:"technical-aeo",label:"Site Health",href:`${Ue}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${Ue}/conversions`},{key:"local",label:"Local Presence",href:`${Ue}/local`},{key:"queries",label:"Queries",href:`${Ue}/queries`},{key:"backlinks",label:"Backlinks",href:`${Ue}/backlinks`}],Dt=[{key:"history",label:"Change History",href:`${Ue}/history`}],ct=ut.filter($=>Nr($.key,te)),Me=Dt.filter($=>Nr($.key,te)),Cs=Nr("settings",te)?{key:"settings",label:"Settings",href:`${Ue}/settings`}:null;function dn($){const ge=Ze?$:e.jsx(wg,{projectName:N,selection:k,showUnmeasuredFallback:!ue&&!Et&&k.measurementScope==="project"&&k.queryClass==="all"&&!k.provider&&!k.model&&!k.location&&!k.from&&!k.to&&!k.revision&&!k.measurementRunId&&!k.queryKey&&!k.marketKey,onSelectionChange:re,onManageQueries:le()?void 0:()=>{h({to:"/projects/$projectName/queries",params:{projectName:N},search:gt=>({...gt,queryWorkspace:"tracked",trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:le()?void 0:({id:gt,label:ks})=>e.jsx(qs,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:N,targetKey:gt},search:sh,"aria-label":`Property details for ${ks}`,className:"inline-flex min-h-11 items-center text-sm text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:"Property details"}),fallback:$});if(le())return ge;let fe=nh(k,Ze?"simple":"advanced",typeof M.sentimentEvaluationDefinitionId=="string"?M.sentimentEvaluationDefinitionId:void 0);return Ze&&(fe.location=qe===""?"none":qe,fe=ah(fe,Zn,K)),e.jsx(rh,{hasSourceEvidence:!Ze||!!(fe.runId||fe.runIds?.length),evidenceReady:!Ze||!(jt.isLoading||jt.evidenceLoading||jt.evidenceError),waitForResolvedRun:!Ze,projectName:N,runOptions:s.visibilitySweeps.slice(0,Db).map(gt=>({id:gt.id,label:Ht(gt.finishedAt??gt.createdAt)})),selection:fe,children:ge})}function Rn(){switch(es.kind){case"report-picker":{if(as.error)return Kl(Gl(as.error))?e.jsx("p",{className:"text-[13px] text-secondary",children:$a.savedScopeUnavailable}):null;const $=as.data;if(!$)return e.jsx("div",{className:"skeleton-text h-11 w-56",role:"status","aria-label":"Loading measurement scope"});if($.selection.availability.state!=="available"||$.scopeOptions.length<=1)return null;const ge=Zr($.scopeOptions,k)??$.selection.scope;return e.jsx(io,{labelVisibility:"sr-only",options:$.scopeOptions,selected:ge,marketKey:k.marketKey,onSelect:(fe,gt)=>re({measurementScope:fe.kind,measurementScopeKey:fe.kind==="project"?void 0:fe.id,measurementMarketKey:gt})})}case"tracking-picker":{const $=Ce.data?.scopeOptions??[],ge=Zr($,k);return ge?e.jsx(io,{labelVisibility:"sr-only",options:$,selected:ge,onSelect:fe=>re({measurementScope:fe.kind,measurementScopeKey:fe.kind==="project"?void 0:fe.id})}):null}case"scope-unavailable":return e.jsx("p",{className:"text-[13px] text-secondary",children:$a.savedScopeUnavailable});case"project-wide":return e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[13px] text-secondary",children:$a.projectWide}),e.jsx(Be,{text:$a.projectWideHelp})]});case"none":return null}}const ys=O==="overview"&&!Ze&&(k.from||k.to)?`${k.from?.slice(0,10)??"First measurement"} to ${k.to?.slice(0,10)??"Latest measurement"}`:null,Ta=Rn(),zi=me?e.jsx(pp,{window:Re,landscape:ss.data,pinnedFallback:Lt,canWrite:g,isEmbed:le(),onWindowChange:De,onPin:xt&&g&&!le()?Se:!_&&g&&!le()?z:void 0,onUnpin:xt||_||!g||le()?void 0:ce,onAddCompetitor:xt&&g&&!le()?Se:!_&&g&&!le()?z:void 0,error:L,onRetry:yt?()=>{ss.refetch()}:void 0,isLoading:yt&&ss.isPending&&ss.data===void 0,scopeLabel:xt?`${ae?.label??xt} group`:_?"All markets":"Project-wide"}):null,gr=le()?null:e.jsxs(e.Fragment,{children:[e.jsx(Fl,{}),e.jsx(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>X(!Ne),children:Ne?"Done":"Manage queries"})]}),Hi=!le()&&Ne?e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[Wn.length>0?e.jsx("ul",{className:"mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto rounded border border-default",children:Wn.map($=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsx("span",{className:"min-w-0 truncate text-sm text-strong",title:$,children:$}),e.jsx("button",{type:"button",className:"shrink-0 rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500 disabled:opacity-50","aria-label":`Remove query ${$}`,title:`Stop tracking "${$}"`,disabled:be!==null,onClick:()=>{j($)},children:be===$?"Removing…":"Remove"})]},$))}):e.jsx("p",{className:"mb-3 text-xs text-muted",children:"No queries tracked yet. Add some below."}),e.jsx("textarea",{className:"w-full resize-none rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:3,placeholder:"Enter queries to add, one per line",value:ie,onChange:$=>G($.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[ie.split(`
8
- `).filter($=>$.trim()).length," to add"]}),e.jsx(Ye,{type:"button",size:"sm",disabled:!ie.trim()||he,onClick:Xe(Ia),children:he?"Adding...":"Add queries"})]})]}):null;return e.jsxs("div",{className:"page-container",children:[le()?e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain," · ",s.contextLabel]})]}),e.jsx("div",{className:us()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:ys!==null?e.jsx("p",{className:"text-sm text-muted",children:ys}):null})]}):e.jsxs("div",{className:"project-context-row",children:[e.jsx("h1",{className:"project-context-title md:sr-only",children:s.project.displayName||s.project.name}),Ta!==null?e.jsx("div",{className:"project-context-scope",children:Ta}):null,s.project.canonicalDomain?e.jsx("span",{className:"project-context-domain",children:s.project.canonicalDomain}):null,e.jsx("div",{className:"project-context-actions","data-project-actions":!0,children:us()?e.jsx(Jm,{projectName:N,running:rn,portfolio:!Ze}):e.jsxs(e.Fragment,{children:[Xn?e.jsx("p",{className:"text-sm text-secondary",children:Xn}):null,hr?e.jsx(Ye,{type:"button",onClick:Pa,children:"Map site"}):Vs?e.jsx(Ye,{type:"button",onClick:Pa,children:"View Page Health"}):null,e.jsx(Ye,{type:"button",variant:"outline",disabled:Ge.isPending||rn||Us,onClick:Ss?()=>{Promise.all([v.refetch(),...Nt?[Jt.refetch()]:[]])}:Cn?pr:$=>{x.current=$.currentTarget,y(N)},children:Ge.isPending?"Starting…":rn?"AI sweep running…":Us?"Checking AI readiness…":Ss?"Retry AI readiness":Cn?"Set up AI Visibility":"Run AI sweep"})]})})]}),!le()&&!us()&&e.jsx(Ab,{open:m===N,projectLabel:Rt,onOpenChange:$=>y($?N:null),onConfirm:Xe(Ra),onClosed:()=>x.current?.focus(),disabled:Ge.isPending||rn||!Bs}),e.jsx($b,{items:ct,overflowItems:Me,settingsItem:Cs,activeTab:O}),O==="portfolio"&&!le()?e.jsx(Qy,{projectName:N,canEdit:g,queries:A.data??[],isQueryLoading:Ns,isQueryError:Gs,onRetryQueries:()=>{A.refetch()},publishedPlan:ue,onCreateQueries:async $=>(await Y.mutateAsync({projectName:N,queries:[...$]}),(await A.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{h({to:"/projects/$projectName",params:{projectName:N},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([v.refetch(),ke.refetch()]).finally(()=>{h({to:"/projects/$projectName",params:{projectName:N}})})}},N):O==="overview"?Ft||Ze&&!C&&(!c||l)?e.jsxs("div",{role:"status","aria-live":"polite",children:[e.jsx("span",{className:"sr-only",children:"Loading project overview"}),e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-hidden":"true"})]}):Ze&&i?e.jsxs("div",{role:"alert",className:"page-section-divider",children:[e.jsx("p",{children:"Could not load AI visibility."}),e.jsx(T,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[js?e.jsxs("div",{role:"alert",className:"mb-5 flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("span",{children:"Could not check the advanced measurement setup. Existing project-wide results remain available."}),e.jsx(T,{type:"button",size:"sm",variant:"outline",onClick:()=>{ke.refetch()},children:"Retry setup check"})]}):null,dn(e.jsx(mb,{mode:xs,canEdit:g&&!le()&&!vs&&!js,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(Kg,{projectName:s.project.name,competitorDomains:U,analyticsRevision:a,queryTexts:Kt,classifyQuery:ts,sweepTimes:_s})}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"av-card-head",children:[e.jsx("h2",{className:"av-card-title",children:"Where competitors are winning"}),Et?e.jsx("p",{className:"av-card-meta",children:"Latest sweep"}):null]}),Et?e.jsxs("div",{className:"competitive-summary",children:[e.jsx(np,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:U},s.project.name),e.jsxs("div",{className:"competitive-gaps",children:[e.jsx("p",{className:"competitive-gaps-scope",children:"All queries"}),e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Cl,{label:"Mention gaps",summary:s.mentionGaps,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.mentionGaps.value}),e.jsxs("span",{className:"text-secondary",children:[" / ",s.queryCounts.total]}),e.jsx("span",{className:"sr-only",children:" queries, all queries"})]}),tooltip:"Across all queries, branded and non-brand: a competitor was mentioned in an answer and your brand was not mentioned by any engine. The mention-share query type does not filter these counts."}),e.jsx(Cl,{label:"Citation gaps",summary:s.gapQueries,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.gapQueries.value}),e.jsxs("span",{className:"text-secondary",children:[" / ",s.queryCounts.total]}),e.jsx("span",{className:"sr-only",children:" queries, all queries"})]}),tooltip:"Across all queries, branded and non-brand: a competitor was cited as a source and your domain was not cited by any engine. The mention-share query type does not filter these counts."})]})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Competitive mention and citation gaps appear after the first AI Visibility sweep."})]}),e.jsx("div",{className:"page-section-divider",children:e.jsx(eg,{projectName:s.project.name,classify:ts,hasCompetitors:U.length>0,providerScores:s.providerScores})}),e.jsxs(Mb,{id:"evidence-section",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${qe===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":qe===void 0,onClick:()=>{xe(void 0)},children:"All locations"}),s.project.locations.map($=>e.jsx("button",{className:`filter-chip ${qe===$.label?"filter-chip-active":""}`,type:"button","aria-pressed":qe===$.label,onClick:()=>{xe($.label),ye(!1)},children:$.label},$.label)),Sa&&e.jsx("button",{className:`filter-chip ${qe===""?"filter-chip-active":""}`,type:"button","aria-pressed":qe==="",onClick:()=>{xe(""),ye(!1)},children:"No location"}),Aa.length>1&&qe===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${R?"filter-chip-active":""}`,type:"button","aria-pressed":R,onClick:()=>ye($=>!$),title:"Side-by-side location comparison",children:"Compare"})]}),jt.evidenceLoading||jt.evidenceError?e.jsxs(e.Fragment,{children:[gr&&e.jsx(xc,{actions:gr}),Hi,jt.evidenceLoading?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading query evidence…"}):e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load query evidence."}),e.jsx(T,{type:"button",variant:"outline",onClick:()=>{jt.refetch()},children:"Retry"})]})]}):e.jsx(zp,{evidence:Zn,compareLocations:R,providerSelection:K,onProviderSelectionChange:Oe,addedQueries:s.movementComparison.addedQueries,actions:gr,actionPanel:Hi})]}),!le()&&e.jsx("div",{className:"page-section-divider",children:e.jsx(sg,{runs:s.recentRuns,collapsed:!0})})]}),report:Hn,reportState:fs,onOpenSetup:le()?void 0:()=>{h({to:"/projects/$projectName/portfolio",params:{projectName:N}})},onRetryReport:()=>{Z===2?Promise.all([vt.refetch(),nt.refetch()]):nt.refetch()},onViewChange:$=>{st({scope:$.scope,...$.groupKey?{groupKey:$.groupKey}:{},queryClass:$.queryClass,...$.search?.trim()?{search:$.search.trim()}:{}})},onLoadMore:$=>{$===rs?.properties.nextCursor&&vt.fetchNextPage()},onPropertyExpand:()=>{pt&&nt.isError&&nt.refetch(),St(!0)},onRetryEvidence:()=>{nt.refetch()},isViewLoading:vt.isPlaceholderData,isLoadingMore:vt.isFetchingNextPage,isLoadMoreError:vt.isFetchNextPageError,viewSearch:ot.search??""},`${N}:${Fe}`)),!Ze&&k.measurementScope==="project"?e.jsxs("details",{className:"visibility-disclosure",onToggle:$=>{$.currentTarget.open&&d()},children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Project signals"})}),!c||l?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading project signals…"}):i?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load project signals."}),e.jsx(T,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsx(qb,{insights:s.insights,suggestedQueries:s.suggestedQueries,onManageQueries:le()?void 0:()=>{h({to:"/projects/$projectName/queries",params:{projectName:N},search:$=>({...$,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]},N):null,zi!==null?e.jsxs("details",{className:`visibility-disclosure${Ze?" page-section-divider":""}`,open:mt,onToggle:$=>_e($.currentTarget.open?N:null),children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Competitor history"})}),e.jsx("div",{className:"visibility-disclosure-panel",children:zi})]}):null]}):O==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(vb,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async($,ge)=>{await at($,ge)},onRefresh:()=>{n()}}),e.jsx(Nb,{project:s.project,onSave:async $=>{await at(s.project.name,$)}}),g&&!le()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Advanced measurement"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Measure individual properties, locations, or site sections with separate query sets."}),Qe==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):Qe==="error"?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:"Could not load advanced measurement setup."}),e.jsx(T,{type:"button",size:"sm",variant:"outline",onClick:()=>{v.refetch()},children:"Retry"})]}):e.jsx(T,{type:"button",variant:"outline",onClick:()=>{h({to:"/projects/$projectName/portfolio",params:{projectName:N}})},children:Wc(xs.setupAction)})]}):null,e.jsx(Sb,{projectName:s.project.name}),e.jsx(kb,{projectName:s.project.name}),g&&!le()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-negative-400",children:"Delete project"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Permanently deletes this project and all its queries, competitors, runs, and snapshots."}),se?e.jsxs(ve,{className:"surface-card p-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(T,{type:"button",variant:"destructive",disabled:E,onClick:Xe(xr),children:E?"Deleting...":"Yes, delete project"}),e.jsx(T,{type:"button",variant:"outline",disabled:E,onClick:()=>D(!1),children:"Cancel"})]})]}):e.jsxs(Ye,{type:"button",variant:"outline",onClick:()=>D(!0),children:[e.jsx(tc,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):O==="queries"||O==="discovery"?e.jsx(Jg,{projectName:N,queryWorkspace:ne,onQueryWorkspaceChange:$=>re({queryWorkspace:$,trackingQueryId:void 0}),researchMode:M.researchMode==="test"?"test":"find",onResearchModeChange:$=>re({researchMode:$}),selection:k,onSelectionChange:re,trackingQueryId:typeof M.trackingQueryId=="string"?M.trackingQueryId:void 0,onTrackingQueryIdChange:$=>re({trackingQueryId:$})}):O==="technical-aeo"?e.jsx(Nh,{projectName:s.project.name,projectId:s.project.id,initialRunId:M.siteHealthRunId,onReleaseInitialRun:oe}):O==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(ly,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(Hf,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):O==="history"?e.jsx(Sf,{projectName:s.project.name}):O==="activity"?e.jsx(lx,{projectName:s.project.name}):O==="backlinks"?e.jsx(zx,{projectName:s.project.name}):O==="local"?e.jsx(Sx,{projectName:s.project.name,projectId:s.project.id}):O==="search-console"?e.jsx(Tb,{projectName:s.project.name}):null]})}export{Jb as ProjectPage,$b as ProjectSubnav,Ab as ProjectSweepConfirmation,Pb as patchProjectDashboardCache};