@canonry/canonry 6.0.0 → 6.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 (32) hide show
  1. package/assets/assets/{AuditHistoryPanel-Bz2NVB6-.js → AuditHistoryPanel-Dtt7cbYo.js} +1 -1
  2. package/assets/assets/{BacklinksPage-Dte5-usf.js → BacklinksPage-h25kHk3u.js} +1 -1
  3. package/assets/assets/{HistoryPage-C1S4nw3I.js → HistoryPage-70YWNYBU.js} +1 -1
  4. package/assets/assets/{MeasurementPropertyPage-DWjsHZdt.js → MeasurementPropertyPage-CBPQ3A99.js} +1 -1
  5. package/assets/assets/ProjectPage-Dbbxf8yl.js +8 -0
  6. package/assets/assets/{RunsPage-D9wEJFfV.js → RunsPage-B6LqcDRg.js} +1 -1
  7. package/assets/assets/{SettingsPage-CN3Gew7Y.js → SettingsPage-DNV6Is27.js} +1 -1
  8. package/assets/assets/{SiteHealthSection-Bft5TfoU.js → SiteHealthSection-CWEIYXut.js} +3 -3
  9. package/assets/assets/{TrafficPage-tkNvySQH.js → TrafficPage-ZZqGgMyL.js} +2 -2
  10. package/assets/assets/{TrafficSourceDetailPage-RhRfPizo.js → TrafficSourceDetailPage-_RMyqM86.js} +1 -1
  11. package/assets/assets/{extract-error-message-tfl_SU7q.js → extract-error-message-D-AaTlPU.js} +1 -1
  12. package/assets/assets/index-BCKrocfL.js +86 -0
  13. package/assets/assets/index-C17E5ZcA.css +1 -0
  14. package/assets/assets/{react-sigma_core.esm.min-BUu3mcQJ.js → react-sigma_core.esm.min-CaRTZKvV.js} +1 -1
  15. package/assets/assets/{v2-overview-adapter-CzeGhaXn.js → v2-overview-adapter-C16fKgpq.js} +1 -1
  16. package/assets/index.html +2 -2
  17. package/dist/{chunk-ZO62Z2WN.js → chunk-B5W7HDCG.js} +23 -10
  18. package/dist/{chunk-K4356AGP.js → chunk-DMU3SFC4.js} +2 -2
  19. package/dist/{chunk-6M7HSNXJ.js → chunk-HTTYBQN4.js} +2 -2
  20. package/dist/{chunk-HAALQW4R.js → chunk-LXHE4DVO.js} +20 -2
  21. package/dist/{chunk-4NC5ZAC2.js → chunk-MJ3QINUW.js} +3 -3
  22. package/dist/{chunk-XGERCNUR.js → chunk-PDOMOHOP.js} +2 -2
  23. package/dist/{chunk-F4G7I7T7.js → chunk-QFI47QVP.js} +25 -10
  24. package/dist/cli.js +17 -9
  25. package/dist/{demo-server-54OUTZMY.js → demo-server-VP6CP33U.js} +4 -4
  26. package/dist/index.js +6 -6
  27. package/dist/{intelligence-service-MEIAMMLT.js → intelligence-service-6F63MYQ5.js} +2 -2
  28. package/dist/mcp.js +4 -4
  29. package/package.json +14 -14
  30. package/assets/assets/ProjectPage-CAJ9XvNt.js +0 -8
  31. package/assets/assets/index-B11OXdEC.css +0 -1
  32. package/assets/assets/index-Cu_xgdb1.js +0 -86
@@ -1,8 +0,0 @@
1
- import{j as e,r as c,t as Yd,u as Me,L as Bs,h as ws,o as Ht,B as Ar,C as dc,D as Jd,k as Xd,l as Zd}from"./vendor-tanstack-ZXXkndVj.js";import{T as re,t as eu,a as tu,s as Hi,M as Aa,I as _e,f as Fe,R as Lt,m as su,B as L,c as nu,b as au,d as ru,u as Qi,e as iu,n as na,S as uc,C as mc,g as hc,h as xc,i as zi,j as lu,k as ou,l as Ln,o as pc,p as gc,q as ve,r as De,v as Y,w as ce,x as Xs,y as qt,z as tt,A as cu,D as du,E as uu,F as fc,G as mu,H as hu,J as Fn,K as $n,L as xu,N as pu,O as Hn,P as ss,Q as gu,U as fu,V as kl,W as yc,X as ts,Y as Wi,Z as yu,_ as bu,$ as vu,a0 as ju,a1 as Al,a2 as Oe,a3 as Nu,a4 as wu,a5 as Dr,a6 as Su,a7 as Cu,a8 as ku,a9 as Au,aa as Ru,ab as Pu,ac as Iu,ad as Tu,ae as Lu,af as $u,ag as Mu,ah as qu,ai as Eu,aj as Du,ak as Ou,al as bc,am as gn,an as Fu,ao as vc,ap as pr,aq as Ku,ar as Ze,as as Gu,at as _u,au as Bu,av as gr,aw as Uu,ax as Vu,ay as Hu,az as En,aA as Qu,aB as zu,aC as Wu,aD as jc,aE as wi,aF as Yu,aG as Yi,aH as Ju,aI as aa,aJ as Ns,aK as Rr,aL as _s,aM as Nc,aN as mr,aO as Si,aP as Xu,aQ as Rl,aR as wc,aS as fr,aT as Zu,aU as Sc,aV as Cc,aW as kc,aX as em,aY as Yt,aZ as Cn,a_ as Pr,a$ as Or,b0 as tm,b1 as sm,b2 as nm,b3 as am,b4 as rm,b5 as Sa,b6 as Pl,b7 as Qa,b8 as Fr,b9 as im,ba as lm,bb as Il,bc as Kr,bd as Mn,be as Ac,bf as Ji,bg as Rc,bh as om,bi as cm,bj as Tl,bk as dm,bl as um,bm as mm,bn as hm,bo as xm,bp as pm,bq as gm,br as fm,bs as ym,bt as bm,bu as vm,bv as jm,bw as Nm,bx as wm,by as Sm,bz as Cm,bA as km,bB as Am,bC as Rm,bD as Pm,bE as Im,bF as Tm,bG as Lm,bH as $m,bI as Mm,bJ as qm,bK as Em,bL as Dm,bM as Ds,bN as Om,bO as kt,bP as Fm,bQ as Km,bR as Gm,bS as _m,bT as Bm,bU as Um,bV as Vm,bW as Hm,bX as Qm,bY as zm,bZ as Wm,b_ as Ym,b$ as Jm,c0 as Xm,c1 as Zm,c2 as eh,c3 as th,c4 as sh,c5 as nh,c6 as ah,c7 as rh,c8 as ih,c9 as Ll,ca as lh,cb as $l,cc as oh,cd as ch,ce as dh,cf as uh,cg as mh,ch as hh,ci as xh,cj as Pc,ck as ph,cl as gh,cm as fh,cn as Ic,co as yh,cp as bh,cq as vh,cr as Ee,cs as Tc,ct as jh,cu as rt,cv as Nh,cw as wh,cx as Sh,cy as Ch,cz as kh,cA as Lc,cB as $c,cC as Ah,cD as Rh,cE as Mc,cF as qc,cG as Ec,cH as Ph,cI as Ih,cJ as Th,cK as Lh,cL as $h,cM as Mh,cN as qh,cO as Eh,cP as Dh,cQ as Oh,cR as Fh,cS as Kh,cT as Gh,cU as _h,cV as Bh,cW as Uh,cX as Vh,cY as yr,cZ as Hh,c_ as Qh,c$ as Dc,d0 as zh,d1 as Wh,d2 as Oc,d3 as Yh,d4 as Jh,d5 as Xh,d6 as Zh,d7 as ex,d8 as tx,d9 as sx,da as nx,db as ax,dc as rx,dd as ix,de as Xi,df as lx,dg as ox,dh as cx,di as dx,dj as ux,dk as mx,dl as hx,dm as xx,dn as px,dp as gx,dq as fx,dr as yx,ds as bx,dt as vx,du as jx,dv as Nx,dw as Fc,dx as Zi,dy as wx,dz as Sx,dA as Cx,dB as kx,dC as Ax,dD as Rx,dE as el,dF as Px,dG as Ix,dH as Tx,dI as Lx,dJ as $x,dK as Kc,dL as Gr,dM as Mx,dN as qx,dO as Ml,dP as Ex,dQ as Dx,dR as Ox,dS as Fx,dT as Kx,dU as Gx,dV as _x,dW as Gc,dX as Bx,dY as _c,dZ as Bc,d_ as Uc,d$ as Vc,e0 as Ux,e1 as Vx,e2 as Hx,e3 as Qx,e4 as zx,e5 as Wx,e6 as Yx,e7 as ql,e8 as Jx,e9 as Xx,ea as Zx,eb as ep,ec as tp,ed as sp,ee as np,ef as ap,eg as El,eh as rp,ei as ip,ej as lp,ek as op,el as cp,em as dp,en as up,eo as mp,ep as hp,eq as xp,er as pp,es as gp,et as _r,eu as fp,ev as yp,ew as bp,ex as vp,ey as jp,ez as Np,eA as wp,eB as Sp,eC as Cp,eD as kp,eE as Ap,eF as Rp,eG as Pp,eH as Ip,eI as Tp,eJ as Hc,eK as Lp,eL as $p,eM as Mp,eN as qp,eO as Ep,eP as Dp,eQ as za,eR as Op,eS as Fp,eT as Kp,eU as Dl,eV as Gp}from"./index-Cu_xgdb1.js";import{u as Dn,D as pn,a as Zs,b as Qc,M as hr,c as zs,S as _p}from"./SiteHealthSection-Bft5TfoU.js";import{A as tl,a as Bp,b as Up,c as Vp,V as Ol}from"./v2-overview-adapter-CzeGhaXn.js";import{o as Dt,C as Ra,f as fn,a as xs,b as Qt,c as Tt,d as hs,e as ct,g as os,h as Kn,M as sl,i as zc,j as oa,p as Hp,k as Qp,l as Fl,m as zp}from"./ChartPrimitives-B5okB5g-.js";import{g as Wc,y as Pa,U as Wp,z as Yp,L as Jp,D as Xp,l as Zp,j as br,I as Yc,J as eg,C as ra,X as tg,e as sg,K as ng,P as ag,N as rg,O as Jc}from"./vendor-lucide-N6vOpZmh.js";import{u as ig,a as lg,b as og,t as cg,e as dg,c as Pt}from"./extract-error-message-tfl_SU7q.js";import{R as Us,C as yn,a as Ia,X as Vs,Y as Hs,T as bn,b as Ci,L as vr,A as hn,d as Ys,e as ug,B as Xc,f as Zc,g as mg,h as hg}from"./vendor-recharts-llkUFBGR.js";import{A as xg}from"./AuditHistoryPanel-Bz2NVB6-.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B4giJcws.js";import"./vendor-yaml-GWJz5H2G.js";const pg=1e6;function gg(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/pg);if(n.showTinyAsLessThan&&t>0&&r===a.format(0)){const l=10**-(a.resolvedOptions().maximumFractionDigits??0);return`<${a.format(l)}`}return r}const Wa={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 ed(t,s){return t!=="viewer"||s!==null}function td(t,s){return t==="research"&&!s?"tracked":t}function sd(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 ki(t,s){return t.find(n=>n.kind===s.measurementScope&&(n.kind==="project"||n.id===s.measurementScopeKey))}function fg(t){return t.measurementScope!=="project"||t.marketKey!==void 0}function yg(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"report":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 Ai({state:t,label:s,className:n}){return e.jsx(re,{tone:tu(t),className:n,children:s??eu(t)})}const kn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Kl={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},bg={"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."},vg="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function jg(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:Fe(t.score,Lt.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 Ng({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(_e,{text:vg})]}),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:Fe(a.share)})]},a.label))})]})}function wg({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=c.useState("non-brand"),l=c.useId(),i=t.scope==="pooled",o=!i&&t.branded.snapshotsTotal>0,d=o?a:"non-brand",m=i?"pooled":d,u=d==="branded"?t.branded:t.breakdown,h=d==="branded"?t.breakdown:t.branded,g=jg(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:h.snapshotsTotal>0}),x=Hi(g.headline),y=m==="non-brand"?Aa[t.tone]:"text-secondary";function p(v){const j=kn.findIndex(I=>I.value===d);let w=null;v.key==="ArrowRight"||v.key==="ArrowDown"?w=(j+1)%kn.length:v.key==="ArrowLeft"||v.key==="ArrowUp"?w=(j-1+kn.length)%kn.length:v.key==="Home"?w=0:v.key==="End"&&(w=kn.length-1),w!==null&&(v.preventDefault(),r(kn[w].value),v.currentTarget.querySelectorAll('[role="radio"]')[w]?.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(_e,{text:bg[m]})]}),o?e.jsx("div",{role:"radiogroup","aria-labelledby":l,className:"segmented flex-wrap",onKeyDown:p,children:kn.map(v=>{const j=v.value===d;return e.jsx("button",{type:"button",role:"radio","aria-checked":j,tabIndex:j?0:-1,onClick:()=>r(v.value),className:`segmented-option min-h-11 ${j?"segmented-option-active":""}`,children:v.label},v.value)})}):e.jsx("span",{className:"mention-share-class",children:Kl[m]})]}),g.numeric?e.jsxs("p",{className:`mention-share-value ${y}`,children:[x.figure,x.sign?e.jsx("span",{className:"text-faint",children:x.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:Kl[m]}),` · ${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(Ng,{breakdown:u,projectLabel:s})]})}function Ma({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 Ca({options:t,value:s,onChange:n,label:a,className:r=""}){const l=c.useId();function i(o){const d=t.findIndex(u=>u.value===s);let m=null;o.key==="ArrowRight"||o.key==="ArrowDown"?m=(d+1)%t.length:o.key==="ArrowLeft"||o.key==="ArrowUp"?m=(d-1+t.length)%t.length:o.key==="Home"?m=0:o.key==="End"&&(m=t.length-1),m!==null&&(o.preventDefault(),n(t[m].value),o.currentTarget.querySelectorAll('[role="radio"]')[m].focus())}return e.jsx("div",{role:"radiogroup","aria-label":a,className:`segmented ${r}`.trim(),onKeyDown:i,children:t.map(o=>{const d=o.value===s,m=o.description?`${l}-${o.value}`:void 0;return e.jsxs(c.Fragment,{children:[e.jsx("button",{type:"button",role:"radio","aria-checked":d,"aria-describedby":m,tabIndex:d?0:-1,onClick:()=>n(o.value),className:`segmented-option pointer-coarse:min-h-11 ${d?"segmented-option-active":""}`,children:o.label}),o.description?e.jsx("span",{id:m,className:"sr-only",children:o.description}):null]},o.value)})})}const Sg=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],Cg={"7d":"last 7 days","30d":"last 30 days","90d":"last 90 days",all:"all sweeps"},kg={"non-brand":"Non-brand",branded:"Branded",all:"All queries"},Ag={"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."},Rg={"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"},Gl="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.",Ri=100;function Pg(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function nd(t){return t==="unavailable"?"Unavailable":"Not measured"}function Pi(t){switch(t){case"own":return"Your domain";case"direct-competitor":return"Competitor";case"ota-aggregator":return"Aggregator";case"editorial-media":return"Editorial";case"other":return"Other";default:return"Unclassified"}}function Os(t,s,n){return t===1?s:n}function ad(t){const s=t.label.trim(),n=nu(t.domain);return s&&s.toLowerCase()!==t.domain.toLowerCase()&&s.toLowerCase()!==n.toLowerCase()?s:null}function rd({row:t}){const s=ad(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 Ig(t){const s=ad(t);return s?`${s} (${t.domain})`:t.domain}function _l(t,s){return s&&t>=Ri?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:t})]}):e.jsx("strong",{children:t})}function Ii({action:t,domain:s,mutation:n}){const[a,r]=c.useState(!1),[l,i]=c.useState(null);async function o(){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(L,{type:"button",size:"sm",variant:"outline",disabled:a,onClick:()=>{o()},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 Tg({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 Xn({count:t,of:s,state:n,toneClass:a}){return n!=="measured"?e.jsx("span",{className:"text-[13px] text-secondary",children:nd(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 Bl({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":nd(s)});const{figure:a,sign:r}=Hi(Fe(t,Lt.percent));return e.jsxs("span",{className:`av-n-sm ${n}`,children:[a,r?e.jsx("span",{className:"text-faint",children:r}):null]})}function Lg({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(rd,{row:l})}),e.jsx("td",{className:"text-[13px] text-secondary",children:Pi(l.surfaceClass)}),e.jsx("td",{children:e.jsx(Xn,{count:l.mentionCount,of:n,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Xn,{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(Tg,{urls:l.sampleUrls}):null,r?e.jsx(Ii,{action:"pin",domain:l.domain,mutation:r}):null]})})]},l.domain))})]})})}function $g({onAddCompetitor:t}){const s=c.useId(),[n,a]=c.useState(""),[r,l]=c.useState(!1),[i,o]=c.useState(null);async function d(){const m=n.trim();if(!(!m||r)){l(!0),o(null);try{if(await t(m)===!1){o("Could not add competitor. Try again.");return}a("")}catch{o("Could not add competitor. Try again.")}finally{l(!1)}}}return e.jsxs("details",{className:"inline-disclosure",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:m=>{m.preventDefault(),d()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:m=>a(m.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(L,{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 Mg({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:l,onPin:i,onUnpin:o,onAddCompetitor:d,error:m,onRetry:u,isLoading:h=!1,scopeLabel:g}){const x=c.useId(),y=a&&!r,p=s?.pinned??n,v=s?.observed??[],j=s?.otherSources??[],w=s?.evidence,I=Pg(s),k=s?.basis==="observed",f=k?v.filter(_=>_.shareOfVoice!==null):p,b=k?v.filter(_=>_.shareOfVoice===null):v,S=s?.filters.queryClass,A=s?.marketState?.draft?.pendingCompetitorDomains.length??0,P=s?.truncated===!0,C=w?.answeredResults??0,U=w?w.answeredResults+w.missingAnswerTextResults:0,O=S==="non-brand"&&s?.project.shareOfVoice!=null?Aa[su(s.project.shareOfVoice)]:"text-primary",J=_=>y?_.pinned?o?e.jsx(Ii,{action:"unpin",domain:_.domain,mutation:o}):null:i?e.jsx(Ii,{action:"pin",domain:_.domain,mutation:i}):null:null,V=f.some(_=>J(_)!==null),H=[g,S?kg[S]:null,Cg[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: ${Rg[s.reason]}`}),s&&b.length>0){const _=b.length;te.push({key:"others",text:P&&_>=Ri?`${Ri} or more other competitors seen`:`${_} other ${Os(_,"competitor","competitors")} seen`})}A>0&&te.push({key:"pending",text:`${s?.scope.kind==="all-markets"?"Pending publication across markets":"Pending publication"}: ${A} ${Os(A,"competitor","competitors")}`});const D=[w&&w.missingAnswerTextResults>0?"Answer data incomplete":null,w&&w.incompleteSourceResults>0?"Citation data incomplete":null].filter(Boolean);D.length>0&&te.push({key:"incomplete",text:D.join(" · "),className:Aa.caution});const $=[];if(s&&w){$.push(s.runCount!==void 0?e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:s.runCount})," ",Os(s.runCount,"sweep","sweeps"),", ",e.jsx("strong",{children:w.answeredResults})," ",Os(w.answeredResults,"answer","answers")]}):e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:w.answeredResults})," ",Os(w.answeredResults,"answer","answers")]})),!s.reason&&I==="measured"&&s.project.shareOfVoice!==null&&$.push(e.jsxs(e.Fragment,{children:["Mention share: you ",e.jsx("strong",{children:s.project.mentionCount}),f.map(M=>e.jsxs(Yd.Fragment,{children:[", ",M.domain," ",e.jsx("strong",{children:M.mentionCount})]},M.domain))," ","of ",e.jsx("strong",{children:w.mentionCredits})," ",k?"brand mentions":"tracked-brand mentions"]})),$.push(e.jsxs(e.Fragment,{children:["Answers with source links: ",e.jsx("strong",{children:w.sourceResults})]})),b.length===0&&$.push("Other competitors seen: none"),w.missingAnswerTextResults>0&&$.push(e.jsxs(e.Fragment,{children:["No answer text: ",e.jsx("strong",{children:w.missingAnswerTextResults})," ",Os(w.missingAnswerTextResults,"answer","answers"),", left out of mention share"]})),w.incompleteSourceResults>0&&$.push(e.jsxs(e.Fragment,{children:["Incomplete source lists: ",e.jsx("strong",{children:w.incompleteSourceResults})," ",Os(w.incompleteSourceResults,"answer","answers"),", not counted as misses"]}));const _=w.excludedProbeResults+w.excludedNonCompletedResults;_>0&&$.push(e.jsxs(e.Fragment,{children:["Left out: ",e.jsx("strong",{children:_})," ",Os(_,"answer","answers")," from spot checks or unfinished sweeps"]}))}const Q=[...s?[{name:"You",row:s.project}]:[],...f.map(_=>({name:_.domain,row:_}))].filter(_=>_.row.sampleUrls.length>0);I==="measured"&&Q.length>0&&$.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsx("summary",{children:"Sample pages cited"}),e.jsx("div",{className:"av-subdetails-body",children:Q.map(({name:_,row:M})=>e.jsxs("div",{children:[e.jsx("p",{children:_}),e.jsx("ul",{className:"space-y-1 font-mono text-[11px] text-muted",children:M.sampleUrls.map(W=>e.jsx("li",{className:"break-all",children:W},W))})]},M.domain))})]})),s&&b.length>0&&$.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other competitors seen: ",_l(b.length,P)]}),e.jsx("div",{className:"av-subdetails-body",children:e.jsx(Lg,{rows:b,state:I,named:C,cited:U,onPin:y?i:void 0})})]}));const B=s?.observedNames??[];if(B.length>0){const _=s?.observedNamesTotal??B.length;$.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Company names in answers: ",_>B.length?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:B.length})," of ",e.jsx("strong",{children:_})]}):e.jsx("strong",{children:B.length})]}),e.jsx("ul",{className:"av-subdetails-body",children:B.map(M=>e.jsxs("li",{children:[M.name," · ",M.answerCount," ",Os(M.answerCount,"answer","answers")]},M.name))})]}))}return j.length>0&&$.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other sites cited: ",_l(j.length,P)]}),e.jsx("ul",{className:"av-subdetails-body",children:j.map(_=>e.jsxs("li",{children:[e.jsxs("span",{children:[Ig(_)," · ",Pi(_.surfaceClass)," · ",_.citationCount," ",Os(_.citationCount,"citation","citations")]}),_.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:_.sampleUrls.map(M=>e.jsx("li",{className:"break-all",children:M},M))}):null]},_.domain))})]})),e.jsxs("section",{"aria-labelledby":x,"aria-busy":h,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:x,className:"av-card-title",children:"Competitors over time"}),e.jsx(_e,{text:S?`${Ag[S]} ${Gl}`:Gl})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsx("p",{className:"av-card-meta",children:H}),e.jsx(Ca,{label:"Competitors over time window",className:"flex-wrap",options:Sg,value:t,onChange:l})]})]}),e.jsxs("div",{className:"av-card-body space-y-3",children:[m?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:[e.jsx("span",{children:m}),u?e.jsx(L,{type:"button",size:"sm",variant:"outline",onClick:u,children:"Retry competitors over time"}):null]}):null,h&&!s&&p.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"}),V?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(Bl,{percent:s.project.shareOfVoice,state:I,toneClass:O})}),e.jsx("td",{children:e.jsx(Xn,{count:s.project.mentionCount,of:C,state:I,toneClass:O})}),e.jsx("td",{children:e.jsx(Xn,{count:s.project.citationCount,of:U,state:I,toneClass:O})}),V?e.jsx("td",{className:"av-brand-actions"}):null]}):null,f.map(_=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(rd,{row:_})}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:Pi(_.surfaceClass)}),e.jsx("td",{children:e.jsx(Bl,{percent:_.shareOfVoice,state:I,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Xn,{count:_.mentionCount,of:C,state:I,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Xn,{count:_.citationCount,of:U,state:I,toneClass:"text-primary"})}),V?e.jsx("td",{className:"av-brand-actions",children:J(_)}):null]},_.domain))]})]}):null,te.length>0?e.jsx("div",{className:"space-y-1 text-[13px] text-secondary",children:te.map(_=>e.jsx("p",{className:_.className,children:_.text},_.key))}):null]}),e.jsx(Ma,{items:$}),y&&d?e.jsx("div",{className:"border-t border-subtle px-5 py-3",children:e.jsx($g,{onAddCompetitor:d})}):null]})}function Ul({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"},o={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},d=a.length-1,m=new Date(a[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(a[d].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),h=`${a.length} ${a.length===1?"run":"runs"}`,g=a.map((x,y)=>{const p=new Date(x.createdAt).toLocaleDateString();return`${y===d?"Latest run, ":""}${p}: ${l[x.citationState]??x.citationState}${x.model?`, model ${x.model}`:""}`}).join("; ");return e.jsxs("div",{className:"inline-flex w-max items-center gap-2 whitespace-nowrap",role:"img","aria-label":`${r} history across ${h}. ${g}`,children:[a.length>1?e.jsx("span",{className:"text-[11px] text-secondary shrink-0","aria-hidden":"true",children:m}):null,e.jsx("div",{className:"flex shrink-0 items-center gap-[3px]",title:h,"aria-hidden":"true",children:a.map((x,y)=>{const p=!!(x.model&&y>0&&a[y-1]?.model&&a[y-1].model!==x.model),v=y===d;return e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 ${o[x.citationState]??"rounded-sm"} ${i[x.citationState]??"bg-mono-700"} ${p?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${v?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[l[x.citationState]??x.citationState,new Date(x.createdAt).toLocaleDateString(),x.model?`model ${x.model}`:null,p?"model changed":null,v?"latest run":null].filter(Boolean).join(" · ")},`${x.runId}:${x.createdAt}`)})}),e.jsxs("span",{className:"text-[11px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{children:"latest"})]})]})}function Ti(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 qa="__cited__",Ea="__mentioned__",en="__mentionShare__";function Qs(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Dt(n),end:Dt(a),sweepCount:s.sweepCount??1}}function Ta(t,s=new Date){return ru(t,s)}function Da(t,s=new Date){const n=Qs(t);if(!n)return null;const a=Ta(n.start,s),r=Ta(n.end,s);return a===r?a:`${a} to ${r}`}function nl(t,s=new Date){const n=Qs(t),a=Da(t,s);return!n||!a?"Sweep date unavailable":`${a} · ${n.sweepCount} ${n.sweepCount===1?"sweep":"sweeps"}`}function qg(t){const s=Qs(t);return s?au(s.start):""}function La(t){return t.trim().toLowerCase()}function Eg(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
2
- `)}const Dg={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",muse:"Muse",local:"Local"};function dt(t){const s=La(t);return Dg[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Li(t){return Math.round(t*1e3)/10}function $i(t){return t.byProvider??{}}function Og(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?qa:Ea,m=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(h=>({date:h.startDate,[d]:Li(h[m])})),series:[d],hasData:a,singleBucket:r}}const l=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys($i(d))))].sort();return{rows:t.buckets.map(d=>{const m={date:d.startDate},u=$i(d);for(const h of i){const g=u[h];m[h]=g?Li(g[l]):null}return m}),series:i,hasData:a,singleBucket:r}}function id(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Fg(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Kg(t){return t.servedModelAttribution??{}}function Gg(t){return t.modelServiceMismatch??{}}function _g(t){return t.modelPointerChanges??{}}function ka(t){return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function $a(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 Bg(t){return ka([...t.models,...t.includesUnknown?["an unknown model"]:[]])}function Ug(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 Vg(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:Ug(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Hg(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 Qg(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[en]:r?.rate==null?null:Li(r.rate)}}),n=s.map(a=>a[en]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[en],hasData:n.length>0,singleBucket:n.length===1}}function zg(t,s,n){return s==="mentionShare"?Qg(t):Og(t,s,n)}function Wg(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 Yg(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 Jg(t,s,n){const a=n==="mentioned"?"mentionRate":"citationRate";for(let r=t.buckets.length-1;r>=0;r--){const l=$i(t.buckets[r])[s];if(l)return l[a]}return null}function Xe(t){return Date.parse(t)}function ld(t,s){const n=Qs(t);if(!n)return!1;const a=Xe(s);return a>=Xe(n.start)&&a<=Xe(n.end)}function od(t){return t.basketChanges??[]}function cd(t,s){return s.filter(n=>ld(t,n.at)).sort((n,a)=>Xe(n.at)-Xe(a.at))}function jr(t,s){return La(t)==="perplexity"&&s.status==="known"&&!s.model.includes("/")}function Xg(t){return Object.entries(t).filter(([s,n])=>!jr(s,n.configured)).sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>({provider:s,mismatch:n}))}function Zg(t){return[...od(t)].sort((s,n)=>Xe(n.at)-Xe(s.at)).map(s=>({at:Dt(s.at),added:s.added,removed:s.removed}))}function ef(t,s){const n=[...t.events].sort((r,l)=>Xe(r.observedAt)-Xe(l.observedAt));let a=n[0]?.from??t.latestObservation.state;for(const r of n)Xe(r.observedAt)<=Xe(s)&&(a=r.to);return a}function Vl(t,s,n,a){return{provider:t,at:Dt(s.observedAt),onOrBefore:s.fromPreWindowAnchor===!0,anchorAt:s.anchorObservedAt?Dt(s.anchorObservedAt):null,from:s.from,to:s.to,served:n,reroute:a}}function tf(t,s){const n=[];for(const[a,r]of Object.entries(t)){const i=s[a]?.events??[],o=new Set(r.events.map(d=>d.observedAt));for(const d of r.events){const m=jr(a,d.to)?i.find(u=>u.observedAt===d.observedAt):void 0;n.push(Vl(a,d,m?{from:m.from,to:m.to}:null,!1))}for(const d of i)o.has(d.observedAt)||jr(a,ef(r,d.observedAt))&&n.push(Vl(a,d,null,!0))}return n.sort((a,r)=>Xe(r.at)-Xe(a.at)||a.provider.localeCompare(r.provider))}function sf({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&&ld(t,g),i=s.filter(g=>l(g.at)),o=i.reduce((g,x)=>g+x.added.length,0),d=i.reduce((g,x)=>g+x.removed.length,0),m=n.filter(g=>l(g.at)).length,u=t?Da(t,a):null;if(u===null||o+d+m===0){const g=r.reduce((x,y)=>Xe(y)>Xe(x)?y:x);return`No changes since ${Ta(g,a)}`}const h=[u];return o>0&&h.push(`${o} ${o===1?"query":"queries"} added`),d>0&&h.push(`${d} ${d===1?"query":"queries"} removed`),m>0&&h.push(`${m} new ${m===1?"model":"models"}`),h.join(" · ")}function nf(t,s,n,a=null){const r=Xe(t);if(!Number.isFinite(r))return null;const l=s.filter(m=>Xe(m)<r);if(l.length>0)return Dt(l.reduce((m,u)=>Xe(u)>Xe(m)?u:m));const i=n.map(m=>Qs(m)).filter(m=>m!==null).sort((m,u)=>Xe(m.start)-Xe(u.start)),o=i.findIndex(m=>Xe(m.start)<=r&&r<=Xe(m.end));if(o===-1)return null;const d=i[o];return Xe(d.start)===r?o>0?i[o-1].end:a&&Xe(a)<r?Dt(a):null:d.sweepCount===2&&Xe(d.end)===r?d.start:null}function af(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=Xe(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 ia(t,s){let n=!t[0].member;for(const a of t)a.at<=s&&(n=a.member);return n}function rf(t,s,n){return t.some(a=>a.at>s&&a.at<=n)}function Mi(t,s){const n=Xe(s.start),a=Xe(s.end);return s.sweepCount>2?rf(t,n,a):ia(t,n)!==ia(t,a)}function dd(t,s,n,a){const r=Xe(s),l=Xe(n),i={added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]},o=new Set;for(const[h,g]of af(t)){if(!a(g))continue;o.add(h);const x=ia(g,r),y=ia(g,l);x!==y?(y?i.added:i.removed).push(h):(x?i.removedAndAddedBack:i.addedAndRemovedAgain).push(h)}if(o.size===0)return null;const d=h=>[...h.added,...h.removed].some(g=>o.has(g)),m=t.filter(h=>Xe(h.at)>r&&Xe(h.at)<=l&&d(h)).sort((h,g)=>Xe(h.at)-Xe(g.at)),u=[...new Set(m.flatMap(h=>[...h.added,...h.removed]))].filter(h=>o.has(h));return{changes:m,keys:u,moves:i}}function lf(t,s){if(t.length<2)return null;const n=t[0],a=t.at(-1),r=Qs(n),l=Qs(a),i=r?.start??n.startDate,o=l?.end??a.endDate,d=dd(s,i,o,m=>ia(m,Xe(i))!==ia(m,Xe(o))||r!==null&&Mi(m,r)||l!==null&&Mi(m,l));return!d&&n.queryCount===a.queryCount?null:{...d??{changes:[],keys:[],moves:{added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]}},firstCount:n.queryCount,latestCount:a.queryCount}}function ud(t,s){const n=Qs(t);if(!n)return null;const a=dd(s,n.start,n.end,r=>Mi(r,n));return a?{...a,firstCount:t.queryCount,latestCount:t.queryCount}:null}function Br(t){return`${t} ${t===1?"query":"queries"}`}function of(t){const s=[],n=a=>s.length===0?Br(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(`${Br(t.removedAndAddedBack.length)} removed and added back`),t.addedAndRemovedAgain.length>0&&s.push(`${Br(t.addedAndRemovedAgain.length)} added and removed again`),ka(s)}function Hl(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 Ql=320;function zl(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function Wl(t){return t==="non-brand"?0:t==="branded"?1:2}function cf(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 df(t){return t.phrase}function Yl(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 Jl(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 uf(t,s){return t.map(n=>md(n,s))}function md(t,s){return s==="citations"?t:{...t,citationState:Yl(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Yl(n,s)}))}}function Xl(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",o=l==="cited"||l==="emerging";return r==="lost"||l!==null&&o&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||l!==null&&!o&&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 mf(t){const s=Ti(uf(t,"mentions")),n=Ti(t);return[Xl(s,"mentions"),Xl(n,"citations")]}function hf({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 Zl({items:t}){return e.jsx("div",{className:"query-evidence-signals","aria-label":"Latest run mention and citation signals",children:mf(t).map(s=>e.jsx(hf,{signal:s},s.key))})}function xf({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed",providerSelection:a,onProviderSelectionChange:r,addedQueries:l=[]}){const{openEvidence:i}=Qi(),o=c.useId(),[d,m]=c.useState(new Set),u=iu(),[h,g]=c.useState("mentions"),[x,y]=c.useState(n),[p,v]=c.useState("all"),[j,w]=c.useState(""),I=a??j,k=$=>{w($),r?.($)},f=c.useMemo(()=>[...new Set([...t.map($=>$.provider).filter(Boolean),...I?[I]:[]])].sort(),[t,I]),b=c.useMemo(()=>{const $=new Map;for(const Q of t){if(I&&Q.provider!==I)continue;const B=Q.query,_=Q.queryClass??null,M=s?Q.location??null:null,W=JSON.stringify([B,_,M]),ne=$.get(W)??{key:W,phrase:B,queryClass:_,location:M,items:[],rawItems:[]};ne.items.push(md(Q,h)),ne.rawItems.push(Q),$.set(W,ne)}return[...$.values()].sort((Q,B)=>Wl(Q.queryClass)-Wl(B.queryClass))},[t,h,s,I]),S=c.useMemo(()=>b.filter($=>p==="all"||(p==="unclassified"?$.queryClass===null:$.queryClass===p)),[b,p]),A=Dn({rows:S,getSearchText:df}),P=c.useMemo(()=>{const $=new Map;for(const Q of A.filteredRows){const B=$.get(Q.queryClass)??new Set;B.add(Q.phrase),$.set(Q.queryClass,B)}return $},[A.filteredRows]),C=c.useMemo(()=>new Set(l.map(na)),[l]),U=u?6:5,O=A.rows.map($=>$.key),J=O.length>0&&O.every($=>d.has($)),V=$=>{m(Q=>{const B=new Set(Q);return B.has($)?B.delete($):B.add($),B})},H=h==="mentions"?"mentioned":"cited",te=h==="mentions"?"Mention History":"Citation History",D=h==="mentions"?"mentioned":"cited";return e.jsxs("div",{className:"query-evidence",children:[e.jsx(uc,{queryClass:p}),e.jsxs("div",{className:"query-evidence-view-row",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"query-evidence-tabs",role:"tablist","aria-label":"Citation tracking view",children:["mentions","citations"].map($=>e.jsx("button",{id:`${o}-${$}`,type:"button",role:"tab","aria-controls":o,"aria-selected":h===$,tabIndex:h===$?0:-1,onClick:()=>g($),onKeyDown:Q=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(Q.key))return;Q.preventDefault();const B=Q.key==="Home"?"mentions":Q.key==="End"||$==="mentions"?"citations":"mentions";g(B),document.getElementById(`${o}-${B}`)?.focus()},children:$==="mentions"?"Mentions":"Citations"},$))}),e.jsx(_e,{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:$=>y($.target.checked?"detailed":"compact")}),"Show answer previews"]}),e.jsx(L,{type:"button",variant:"ghost",className:"min-h-11",disabled:O.length===0,onClick:()=>{m($=>{const Q=new Set($);for(const B of O)J?Q.delete(B):Q.add(B);return Q})},children:J?"Collapse page":"Expand page"})]})]}),t.length>0||I?e.jsxs("div",{className:"query-evidence-filters",children:[e.jsx(pn,{value:A.query,onChange:A.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:I,onChange:$=>{k($.target.value),A.setPage(1)},children:[e.jsx("option",{value:"",children:"All engines"}),f.map($=>e.jsx("option",{value:$,children:dt($)},$))]})]}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Query class"}),e.jsxs("select",{value:p,onChange:$=>{v($.target.value),A.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:o,role:"tabpanel","aria-labelledby":`${o}-${h}`,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"}),u&&e.jsx("th",{scope:"col","aria-label":"Favorable",children:e.jsxs("span",{className:"inline-flex items-center",children:["Favorable",e.jsx(_e,{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:te}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Answer"})})]})}),cf(A.rows).map($=>e.jsxs("tbody",{children:[e.jsx("tr",{className:"query-evidence-group",children:e.jsxs("th",{scope:"rowgroup",colSpan:U,children:[zl($.queryClass)," (",P.get($.queryClass)?.size??0,")"]})}),$.rows.map(({key:Q,phrase:B,queryClass:_,location:M,items:W,rawItems:ne})=>{const ie=d.has(Q),be=O.indexOf(Q),ke=`${o}-query-${be}`,X=C.has(na(B)),le=W.map(se=>se.citationState),je=le.includes("cited")?"cited":le.includes("emerging")?"emerging":le.includes("lost")?"lost":le.every(se=>se==="pending")?"pending":"not-cited",ee=[...new Set(ne.map(se=>se.queryId).filter(se=>!!se))],oe=ne.map(se=>se.sourceSnapshotId).filter(se=>!!se),G=Ti(W),ue=W.filter(se=>se.citationState===mc.cited||se.citationState==="emerging").length;return e.jsxs(c.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-row",onClick:()=>V(Q),children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("button",{type:"button",className:"query-evidence-query","aria-label":B,"aria-describedby":ke,"aria-expanded":ie,onClick:se=>{se.stopPropagation(),V(Q)},children:[e.jsx(Wc,{size:16,"aria-hidden":"true",className:ie?"rotate-90":""}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{children:B}),e.jsxs("span",{id:ke,className:"query-evidence-meta",children:[e.jsx("span",{children:zl(_)}),s&&e.jsx("span",{children:M??"No location"}),W.filter(se=>se.provider).map(se=>e.jsx("span",{children:dt(se.provider)},se.id))]})]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ai,{state:je,label:Jl(je,h),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":`${ue} of ${W.length} engines ${D}`,title:`${ue} of ${W.length} engines ${D}`,children:[ue,"/",W.length]})]})}),u&&e.jsx("td",{children:e.jsx(hc,{queryId:ee.length===1?ee[0]:null,sourceSnapshotIds:ee.length>1?[]:oe,queryClass:_,location:s?M:void 0})}),e.jsx("td",{children:e.jsx(Ul,{history:G,signal:h})}),e.jsx("td",{className:"evidence-change-cell",children:X?e.jsx("span",{className:"query-evidence-new",children:"new query"}):e.jsx(Zl,{items:ne})}),e.jsx("td",{})]}),ie&&W.map((se,Se)=>e.jsxs(c.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:se.provider?dt(se.provider):"Awaiting engine"})}),e.jsx("td",{children:e.jsx(Ai,{state:se.citationState,className:"rounded-none border-0 bg-transparent p-0 text-sm tracking-normal",label:Jl(se.citationState,h)})}),u&&e.jsx("td",{children:e.jsx(xc,{queryId:se.queryId,sourceSnapshotIds:se.sourceSnapshotId?[se.sourceSnapshotId]:[],queryClass:se.queryClass,provider:se.provider,location:se.location??null})}),e.jsx("td",{children:e.jsx(Ul,{history:se.runHistory,signal:h})}),e.jsx("td",{className:"evidence-change-cell",children:X?null:e.jsx(Zl,{items:[ne[Se]??se]})}),e.jsx("td",{children:e.jsx(L,{variant:"ghost",className:"min-h-11",type:"button",title:`View ${se.provider?dt(se.provider):"saved"} answer for ${se.query}`,onClick:Ce=>{Ce.stopPropagation(),i(se.id)},children:"View"})})]}),x==="detailed"&&e.jsx("tr",{className:"query-evidence-preview-row",children:e.jsx("td",{colSpan:U,children:e.jsx(gf,{item:se,mode:h,onViewFull:()=>i(se.id)},h)})})]},se.id))]},Q)})]},$.queryClass??"unclassified"))]})}),A.totalRows===0&&(A.hasQuery||p!=="all"||I)?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Zs,{page:A.page,pageSize:A.pageSize,visibleRows:A.rows.length,totalRows:A.totalRows,onPageChange:A.setPage,itemLabel:A.hasQuery||p!=="all"||I?"matches":"queries"})]}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",H==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function pf(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const l=ou(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 qi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function gf({item:t,mode:s,onViewFull:n}){const[a,r]=c.useState(!1),[l,i]=c.useState(!1);if(s==="mentions")return e.jsx(eo,{item:t,onViewFull:n});const o=t.evidenceUrls.length>0?t.evidenceUrls.map(d=>({uri:d,title:t.groundingSources.find(m=>m.uri===d)?.title})):t.groundingSources;return e.jsxs("div",{className:"query-evidence-preview space-y-3",children:[e.jsx("p",{className:"text-[13px] font-medium text-secondary",children:t.evidenceUrls.length>0?"Cited sources":o.length>0?"Grounding sources":"Cited domains"}),o.length>0?e.jsx("ul",{className:"space-y-4",children:o.slice(0,l?void 0:6).map((d,m)=>e.jsxs("li",{className:"min-w-0",children:[e.jsx(zi,{url:d.uri,title:d.title}),qi(t,lu(d.uri)??"")&&e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:"Competitor source"})]},`${m}-${d.uri}`))}):t.citedDomains.length>0?e.jsx("ul",{className:"space-y-1 text-sm text-secondary",children:t.citedDomains.slice(0,l?void 0:6).map(d=>e.jsxs("li",{className:"[overflow-wrap:anywhere]",children:[d,qi(t,d)?" · competitor source":""]},d))}):e.jsx("p",{className:"text-sm text-secondary",children:"No cited sources captured for this run."}),(o.length>6||o.length===0&&t.citedDomains.length>6)&&e.jsx(L,{type:"button",variant:"ghost",className:"min-h-11","aria-expanded":l,onClick:()=>i(d=>!d),children:l?"Show fewer sources":"View all sources"}),t.answerSnippet.trim()?e.jsxs("details",{open:a,className:"border-t border-subtle pt-1",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:d=>{d.preventDefault(),r(m=>!m)},children:"Answer text"}),a&&e.jsx(eo,{item:t,onViewFull:n,contextOnly:!0})]}):e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."})]})}function eo({item:t,onViewFull:s,contextOnly:n=!1}){const{matchedTerms:a,mentionedCompetitorDomains:r,recommendedCompetitors:l}=t,i=c.useMemo(()=>pf({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>Ql;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(tl,{headingLevel:4,highlightGroups:i,previewLength:Ql,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(m=>e.jsxs("span",{className:"[overflow-wrap:anywhere]",children:[m,qi(t,m)?" · competitor source":""]},`c-${m}`)),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(m=>e.jsx("span",{className:"[overflow-wrap:anywhere]",children:m},`co-${m}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]})]}),d&&e.jsx(L,{type:"button",variant:"ghost",className:"min-h-11",onClick:m=>{m.stopPropagation(),s()},children:"View full answer"})]})}function Ya({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 Ir({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 Ur=ct[0],Vr=ct[1],to=ct[2],so=ct[3],ff=["both","server","ga4"],no={fontSize:11,paddingTop:6},ao=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),ro=t=>typeof t=="number"?De(Math.round(t)):String(t),fs=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function Hr(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 Qr({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(_e,{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 yf(t,s){return n=>{const{cx:a,cy:r,index:l,key:i}=n,o=l??-1;return!(t[o]!=null&&t[o-1]==null&&t[o+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 bf({projectName:t,sinceMinutes:s}){const[n,a]=c.useState(!0),[r,l]=c.useState(!0),[i,o]=c.useState("both"),d=ig(t,{sinceMinutes:s,granularity:"day",limit:1}),m=lg(t),h=Me({...pc({client:Y,path:{name:t}}),enabled:!!t,staleTime:Ln}).data?.connected===!0,g=Me({...gc({client:Y,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&h,staleTime:Ln}),x=c.useMemo(()=>d.data?.series?.points??[],[d.data]),y=c.useMemo(()=>{const A=g.data;return new Map((A?.days??[]).map(P=>[P.date,P.sessions]))},[g.data]),p=c.useMemo(()=>{const A=C=>C.measured!==!1;if(x.length===0||A(x[0]))return null;const P=x.findIndex(A)-1;return P<0?{from:x[0].bucket,to:x[x.length-1].bucket}:{from:x[0].bucket,to:x[P].bucket}},[x]),v=d.data?.series?.coverageStart??null,j=d.data?.series?.trends,w=c.useMemo(()=>{const A=Hr(j?.crawlerContentHits,x.length),P=Hr(j?.aiUserFetchHits,x.length),C=Hr(j?.aiReferralLandedHits,x.length);return x.map((U,O)=>({...U,crawlerContentHits:U.measured!==!1?fs(U.crawlerContentHits):null,aiUserFetchHits:U.measured!==!1?fs(U.aiUserFetchHits):null,aiReferralLandedHits:U.measured!==!1?fs(U.aiReferralLandedHits):null,ga4Visits:y.get(U.bucket)??null,crawlTrend:A[O],fetchTrend:P[O],visitTrend:C[O]}))},[x,y,j]),I=d.data?.totals,k=I&&{crawlers:fs(I.crawlerContentHits),fetches:fs(I.aiUserFetchHits),visits:fs(I.aiReferralLandedHits)},f=c.useMemo(()=>x.reduce((A,P)=>({crawlers:A.crawlers+fs(P.crawlerContentHits),fetches:A.fetches+fs(P.aiUserFetchHits),visits:A.visits+fs(P.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[x]),b=k??f,S=b.crawlers>0||b.fetches>0||b.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 A=m.data?.sources,P=A!==void 0&&A.length===0,C=!P&&v===null;return e.jsxs(ve,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:P?"No server-side traffic source connected yet.":C?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:P?"Connect a traffic source to see how AI engines read this site over time.":C?"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(Qr,{label:"AI crawlers",value:De(b.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(Qr,{label:"AI page fetches",value:De(b.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(Qr,{label:"AI visitors",value:De(b.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."})]}),x.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:fs(x[x.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:fs(x[x.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:fs(x[x.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(x[x.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(_e,{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:A=>a(A.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:A=>l(A.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Us,{width:"100%",height:206,children:e.jsxs(yn,{data:w,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Ia,{stroke:Ra,vertical:!1}),e.jsx(Vs,{dataKey:"bucket",tick:Qt,stroke:xs,tickFormatter:fn,minTickGap:28}),e.jsx(Hs,{tick:Qt,stroke:xs,width:48,allowDecimals:!1}),e.jsx(bn,{contentStyle:hs.contentStyle,labelStyle:hs.labelStyle,itemStyle:hs.itemStyle,labelFormatter:Tt,formatter:ro}),p&&e.jsx(Ci,{x1:p.from,x2:p.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(vr,{wrapperStyle:no,iconType:"plainline",iconSize:14,formatter:A=>ao.has(A)?"":A}),e.jsx(hn,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Ur,fill:Ur,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(hn,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Vr,fill:Vr,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Ys,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Ur,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Ys,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Vr,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(_e,{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(Ir,{windows:ff,value:i,onChange:o,label:"Visit measurement source",formatOption:A=>A==="ga4"?"GA4":A==="both"?"Both":"Server"})]}),e.jsx(Us,{width:"100%",height:176,children:e.jsxs(yn,{data:w,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Ia,{stroke:Ra,vertical:!1}),e.jsx(Vs,{dataKey:"bucket",tick:Qt,stroke:xs,tickFormatter:fn,minTickGap:28}),e.jsx(Hs,{tick:Qt,stroke:xs,width:48,allowDecimals:!1}),e.jsx(bn,{contentStyle:hs.contentStyle,labelStyle:hs.labelStyle,itemStyle:hs.itemStyle,labelFormatter:Tt,formatter:ro}),p&&e.jsx(Ci,{x1:p.from,x2:p.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(vr,{wrapperStyle:no,iconType:"plainline",iconSize:14,formatter:A=>ao.has(A)?"":A}),i!=="ga4"&&e.jsx(Ys,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:to,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Ys,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:so,strokeWidth:1.8,strokeDasharray:"5 3",dot:yf(w.map(A=>A.ga4Visits),so)}),r&&i!=="ga4"&&e.jsx(Ys,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:to,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const vf=6,la="__other__",ta="_socialTotal";function jf(t,s=vf){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,h)=>h[1]!==u[1]?h[1]-u[1]:u[0].localeCompare(h[0])),r=a.slice(0,s),l=new Set(r.map(([u])=>u)),i=Math.max(0,a.length-s),o=new Map;for(const u of t){let h=o.get(u.date);h||(h={date:u.date,[ta]:0},o.set(u.date,h));const g=l.has(u.source)?u.source:la;h[g]=(h[g]??0)+u.sessions,h[ta]=(h[ta]??0)+u.sessions}const d=[...o.values()].sort((u,h)=>String(u.date).localeCompare(String(h.date))),m=r.map(([u])=>u);return i>0&&m.push(la),{data:d,sources:m,otherCount:i}}function sa(t){return t.replace(/\+/g," ")}function hd(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const io="_totalSessions",lo="_organicSessions";function Nf(t,s){const n=new Map;for(const i of s)n.set(i.date,{[io]:i.sessions,[lo]:i.organicSessions});for(const i of t.days){let o=n.get(i.date);o||(o={[io]:0,[lo]:0},n.set(i.date,o));for(const d of i.bySource)o[d.source]=(o[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([i],[o])=>i.localeCompare(o)).map(([i,o])=>({date:i,...o})),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 wf=["7d","30d","90d"],Sf={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},mn=ct,Ei=os.textDim,xd=os.textFaint,pa=25;function Cf(t){return Qc(t.landingPage)}const kf=25,Af=10,zr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Ja(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function pd(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 Rf({projectName:t}){const{data:s,isLoading:n,isError:a}=og(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."," ",!ce()&&e.jsx(Bs,{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."," ",!ce()&&e.jsxs(e.Fragment,{children:[e.jsx(Bs,{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(re,{tone:cg(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?pd(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ce()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Bs,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function Pf({projectName:t}){const[s,n]=c.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Rf,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Ir,{windows:wf,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(If,{projectName:t,window:s}),e.jsx(bf,{projectName:t,sinceMinutes:Sf[s]})]})}function If({projectName:t,window:s}){const n=ws(),a=s??"30d",[r,l]=c.useState(null),[i,o]=c.useState(null),[d,m]=c.useState(!0),[u,h]=c.useState(!1),[g,x]=c.useState(!1),[y,p]=c.useState(null),[v,j]=c.useState(null),[w,I]=c.useState("sessions"),[k,f]=c.useState("desc"),[b,S]=c.useState("sessions"),[A,P]=c.useState("desc"),[C,U]=c.useState("sessions"),[O,J]=c.useState("desc"),[V,H]=c.useState("sessions"),[te,D]=c.useState("desc"),[$,Q]=c.useState(zr),[B,_]=c.useState([]),[M,W]=c.useState([]),[ne,ie]=c.useState(!1);async function be(Z){m(!0),p(null);try{const Ge=await n.fetchQuery({...pc({client:Y,path:{name:t}}),staleTime:Ln});if(Z.current)return;if(l(Ge),!Ge.connected){o(null),Q(zr),_([]),W([]),m(!1);return}const Te=a==="all"?void 0:a,Pe=await n.fetchQuery({...cu({client:Y,path:{name:t},query:Te?{window:Te}:void 0}),staleTime:Ln}),Gt=Pe.windowStart||Pe.windowEnd?{...Pe.windowStart?{startDate:Pe.windowStart}:{},...Pe.windowEnd?{endDate:Pe.windowEnd}:{}}:void 0,[St,rs,it]=await Promise.all([n.fetchQuery({...gc({client:Y,path:{name:t},query:Te?{window:Te}:void 0}),staleTime:Ln}).catch(()=>zr),n.fetchQuery({...du({client:Y,path:{name:t},query:Te?{window:Te}:void 0}),staleTime:Ln}).catch(()=>[]),n.fetchQuery({...uu({client:Y,path:{name:t},query:Gt}),staleTime:Ln}).catch(()=>[])]);if(Z.current)return;o(Pe),Q(St),_(rs),W(it),m(!1)}catch(Ge){if(Z.current)return;p(Ge instanceof Error?Ge.message:"Failed to load GA4 data"),m(!1)}}c.useEffect(()=>{const Z={current:!1};return be(Z),()=>{Z.current=!0}},[t,a,n]);async function ke(){h(!0),p(null),j(null);try{const Z=await fc(t);j(`Synced ${Z.rowCount.toLocaleString()} page rows, ${Z.aiReferralCount.toLocaleString()} AI and ${Z.socialReferralCount.toLocaleString()} social referral rows (${Z.days} days)`),await qt(n,"ga"),await be({current:!1})}catch(Z){p(Z instanceof Error?Z.message:"Sync failed")}finally{h(!1)}}async function X(){x(!0),p(null),j(null);try{await mu(t),await qt(n,"ga"),l({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),o(null),j("GA4 disconnected")}catch(Z){p(Z instanceof Error?Z.message:"Disconnect failed")}finally{x(!1)}}function le(Z){G.setPage(1),w===Z?f(Ge=>Ge==="desc"?"asc":"desc"):(I(Z),f("desc"))}function je(Z){b===Z?P(Ge=>Ge==="desc"?"asc":"desc"):(S(Z),P("desc"))}function ee(Z){C===Z?J(Ge=>Ge==="desc"?"asc":"desc"):(U(Z),J("desc"))}const oe=c.useMemo(()=>i?.topPages?[...i.topPages].sort((Z,Ge)=>{const Te=Z[w],Pe=Ge[w];return typeof Te=="string"&&typeof Pe=="string"?k==="asc"?Te.localeCompare(Pe):Pe.localeCompare(Te):k==="asc"?Te-Pe:Pe-Te}):[],[i?.topPages,w,k]),G=Dn({rows:oe,getSearchText:Z=>Qc(Z.landingPage),pageSize:Af}),ue=c.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((Z,Ge)=>{const Te=Z[b],Pe=Ge[b];return typeof Te=="string"&&typeof Pe=="string"?A==="asc"?Te.localeCompare(Pe):Pe.localeCompare(Te):A==="asc"?Te-Pe:Pe-Te}):[],[i?.aiReferrals,b,A]),se=c.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((Z,Ge)=>{const Te=Z[V],Pe=Ge[V];return typeof Te=="string"&&typeof Pe=="string"?te==="asc"?Te.localeCompare(Pe):Pe.localeCompare(Te):te==="asc"?Te-Pe:Pe-Te}):[],[i?.aiReferralLandingPages,V,te]),Se=Dn({rows:se,getSearchText:Cf,pageSize:kf}),Ce=Se.totalRows>0?`${Se.totalRows.toLocaleString()} ${Se.hasQuery?Se.totalRows===1?"match":"matches":Se.totalRows===1?"row":"rows"}`:Se.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Ie(Z){Se.setPage(1),V===Z?D(Ge=>Ge==="desc"?"asc":"desc"):(H(Z),D("desc"))}const Be=c.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((Z,Ge)=>{const Te=Z[C],Pe=Ge[C];return typeof Te=="string"&&typeof Pe=="string"?O==="asc"?Te.localeCompare(Pe):Pe.localeCompare(Te):O==="asc"?Te-Pe:Pe-Te}):[],[i?.socialReferrals,C,O]),{socialChartData:qe,socialChartSources:pe,socialOtherCount:F}=c.useMemo(()=>{const Z=jf(M);return{socialChartData:Z.data,socialChartSources:Z.sources,socialOtherCount:Z.otherCount}},[M]),{chartData:Ke,chartSources:T,dateRange:ye}=c.useMemo(()=>{const Z=Nf($,B);return{chartData:Z.data,chartSources:Z.sources,dateRange:Z.dateRange}},[$,B]);if(d&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return ce()||Xs()?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(Tf,{projectName:t,onConnected:()=>{(async()=>(await qt(n,"ga"),await be({current:!1})))()}});const Ve=i?.organicSharePctDisplay??"0%",Ye=i?.channelBreakdown?.organic.sharePctDisplay??Ve,et=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,xe=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,ft=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",ze=i?.paidAiSessionsBySession??0,nt=i?.paidAiSharePctBySessionDisplay??"0%",as=i?new Set(i.aiReferrals.map(Z=>Z.source.toLowerCase())).size:0,xt=ue[0]??null,at=i?.totalDirectSessions??0,yt=i?.directSharePctDisplay??"0%",At=i?.channelBreakdown?.direct.sessions??at,$t=i?.channelBreakdown?.direct.sharePctDisplay??yt,He=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,R=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ae=i?.socialSessions??0,me=i?.socialSharePctDisplay??"0%",Je=i?.channelBreakdown?.social.sessions??Ae,Ft=i?.channelBreakdown?.social.sharePctDisplay??me,Kt=i?new Set(i.socialReferrals.map(Z=>Z.source.toLowerCase())).size:0,ut=Be[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}),v&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:v}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!ce()&&!Xs()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(L,{variant:"outline",size:"sm",disabled:u,onClick:tt(ke),children:[e.jsx(Pa,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(L,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:g,onClick:tt(X),children:[e.jsx(Wp,{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(_e,{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(Wr,{value:Ja(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Wr,{value:Ja(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Ve} of total`,tone:"positive"}),e.jsx(Wr,{value:i.totalUsers===null?"—":Ja(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."}),!ce()&&!Xs()&&e.jsxs(L,{variant:"outline",size:"sm",disabled:u,onClick:tt(ke),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(_e,{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"})]})]}),Ke.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:T.length>0?"AI vs. total sessions":"All sessions (baseline)"}),T.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),T.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(Us,{width:"100%",height:"100%",children:e.jsxs(yn,{data:Ke,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Vs,{dataKey:"date",tick:Qt,tickLine:!1,axisLine:{stroke:xs},tickFormatter:fn}),e.jsx(Hs,{tick:Qt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(bn,{...hs,labelFormatter:Tt,formatter:(Z,Ge)=>{const Te=typeof Z=="number"?Z.toLocaleString():String(Z??0),Pe=String(Ge??"");return Pe==="_totalSessions"?[Te,"Total Sessions"]:Pe==="_organicSessions"?[Te,"Organic Sessions"]:[Te,Pe]}}),e.jsx(vr,{wrapperStyle:{fontSize:11,color:os.text},formatter:Z=>Z==="_totalSessions"?"Total Sessions":Z==="_organicSessions"?"Organic Sessions":Z}),e.jsx(hn,{type:"monotone",dataKey:"_totalSessions",stroke:os.textFaint,fill:os.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),T.map((Z,Ge)=>e.jsx(hn,{type:"monotone",dataKey:Z,stackId:"ai",stroke:mn[Ge%mn.length],fill:mn[Ge%mn.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(Rs,{label:"Organic",value:Ye,hint:`${et.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(Rs,{label:"Social",value:Ft,hint:`${Je.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(Rs,{label:"Direct",value:$t,hint:`${At.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(Rs,{label:"Visitors from AI (at least)",value:ft,hint:ze>0?`${xe.toLocaleString()} sessions · ${ze.toLocaleString()} paid`:`${xe.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(Rs,{label:"Other channels",value:R,hint:`${He.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."})]}),xt&&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:xt.source})," via ",xt.medium,", accounting for ",xt.sessions.toLocaleString()," sessions.",ze>0&&e.jsxs("span",{children:[" Paid AI: ",ze.toLocaleString()," sessions (",nt,")."]})]})]}),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?`${as} 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(ys,{label:"Source",sortKey:"source",current:b,dir:A,onSort:je,align:"left"}),e.jsx(ys,{label:"Medium",sortKey:"medium",current:b,dir:A,onSort:je,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(ys,{label:"Sessions",sortKey:"sessions",current:b,dir:A,onSort:je,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:ue.map(Z=>e.jsx($f,{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:Ce})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(pn,{value:Se.query,onChange:Se.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Se.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(ys,{label:"Landing Page",sortKey:"landingPage",current:V,dir:te,onSort:Ie,align:"left"}),e.jsx(ys,{label:"Source",sortKey:"source",current:V,dir:te,onSort:Ie,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(ys,{label:"Sessions",sortKey:"sessions",current:V,dir:te,onSort:Ie,align:"right"})]})}),e.jsx("tbody",{children:Se.rows.map(Z=>e.jsx(Mf,{row:Z},`${Z.landingPage}:${Z.source}:${Z.medium}:${Z.sourceDimension}`))})]})}),e.jsx(Zs,{page:Se.page,pageSize:Se.pageSize,visibleRows:Se.rows.length,totalRows:Se.totalRows,onPageChange:Se.setPage,itemLabel:Se.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:()=>Se.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(_e,{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(Rs,{label:"Social Sessions",value:Ja(Ae),hint:`${Ae.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Rs,{label:"Share of Traffic",value:me,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Rs,{label:"Platforms",value:String(Kt),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."})]}),ut&&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:`${ut.source} via ${ut.medium}`,children:hd(sa(ut.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:ut.medium,children:["via ",sa(ut.medium)," · ",ut.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(Rs,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Rs,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Rs,{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"})]}),F>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",pe.length-1," sources · ",F," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Us,{width:"100%",height:"100%",children:e.jsxs(yn,{data:qe,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Vs,{dataKey:"date",tick:Qt,tickLine:!1,axisLine:{stroke:xs},tickFormatter:fn}),e.jsx(Hs,{tick:Qt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(bn,{...hs,labelFormatter:Tt,formatter:(Z,Ge)=>{const Te=typeof Z=="number"?Z.toLocaleString():String(Z??0),Pe=String(Ge??"");if(Pe===ta)return[Te,"Total Social"];if(Pe===la){const Gt=`Other (${F} source${F===1?"":"s"})`;return[Te,Gt]}return[Te,sa(Pe)]}}),e.jsx(hn,{type:"monotone",dataKey:ta,stroke:xd,fill:os.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),pe.map((Z,Ge)=>{const Pe=Z===la?Ei:mn[Ge%mn.length];return e.jsx(hn,{type:"monotone",dataKey:Z,stackId:"social",stroke:Pe,fill:Pe,fillOpacity:.4,strokeWidth:1.5},Z)})]})})}),e.jsx(Ef,{sources:pe,otherCount:F})]}),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?Be.length>pa&&!ne?`Top ${pa} of ${Be.length}`:`${Be.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(ys,{label:"Source",sortKey:"source",current:C,dir:O,onSort:ee,align:"left"}),e.jsx(ys,{label:"Medium",sortKey:"medium",current:C,dir:O,onSort:ee,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(ys,{label:"Sessions",sortKey:"sessions",current:C,dir:O,onSort:ee,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(ne?Be:Be.slice(0,pa)).map(Z=>e.jsx(qf,{referral:Z},`${Z.source}:${Z.medium}:${Z.channelGroup}`))})]})}),Be.length>pa&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>ie(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:ne?`Show top ${pa}`:`Show all ${Be.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(_e,{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(pn,{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(ys,{label:"Landing Page",sortKey:"landingPage",current:w,dir:k,onSort:le,align:"left"}),e.jsx(ys,{label:"Sessions",sortKey:"sessions",current:w,dir:k,onSort:le,align:"right"}),e.jsx(ys,{label:"Organic",sortKey:"organicSessions",current:w,dir:k,onSort:le,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:G.rows.map(Z=>e.jsx(Lf,{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(Zs,{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 ${pd(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Tf({projectName:t,onConnected:s}){const[n,a]=c.useState(""),[r,l]=c.useState(null),[i,o]=c.useState(null),[d,m]=c.useState(!1),[u,h]=c.useState(null),g=c.useRef(null),x=c.useCallback(p=>{const v=p.target.files?.[0];if(!v)return;h(null),l(v.name);const j=new FileReader;j.onload=()=>{const w=j.result;try{const I=JSON.parse(w);if(!I.client_email||!I.private_key){h("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),o(null);return}o(w)}catch{h("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),o(null)}},j.onerror=()=>{h("Failed to read file."),o(null)},j.readAsText(v)},[]);async function y(){if(h(null),!n.trim()){h("Property ID is required.");return}if(!i){h("Please upload a service account key file.");return}m(!0);try{await hu(t,{propertyId:n.trim(),keyJson:i});try{await fc(t)}catch{}s()}catch(p){h(p instanceof Error?p.message:"Failed to connect GA4")}finally{m(!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:p=>a(p.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:g,type:"file",accept:".json,application/json",onChange:x,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(Yp,{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(L,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:tt(y),children:d?"Connecting & syncing…":"Connect GA4"})]})}function ys({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 gd={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Wr({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 ${gd[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Rs({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(_e,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${gd[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Lf({page:t}){const s=Fe(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 fd={session:"Session",first_user:"First Visit",manual_utm:"UTM"},yd={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 $f({referral:t}){const s=Fe(t.share),n=fd[t.sourceDimension]??t.sourceDimension,a=yd[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 Mf({row:t}){const s=fd[t.sourceDimension]??t.sourceDimension,n=yd[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(hr,{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 qf({referral:t}){const s=Fe(t.share),n=t.channelGroup==="Paid Social"?"Paid":"Organic",a=sa(t.source),r=sa(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 Ef({sources:t,otherCount:s}){const n=[{key:ta,color:xd,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===la)n.push({key:la,color:Ei,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=sa(r);n.push({key:r,color:mn[a%mn.length]??Ei,label:hd(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 Df(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 Of="Search Console is not connected yet. Your Canonry team can set this up.",Ff=["7d","30d","90d","all"],Xa=500,oo=[{key:"clicks",label:"Clicks",color:ct[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:ct[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Kn.caution,format:t=>Fe(t)},{key:"position",label:"Avg position",color:ct[2],inverted:!0,format:t=>t.toFixed(1)}],dn=25,Kf="canonry:google-oauth-complete";function Gf(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],o=t.trailing[s];return i!==null&&o!==null&&i<=0&&o>0?`new in the last ${a}d`:i===null||i<=0?`no prior ${a}d to compare`:o===null?`no value in the last ${a}d`:"comparison unavailable"}return r===0?`→ no change vs prior ${a}d`:`${(n?r<0:r>0)?"↑":"↓"} ${Fe(Math.abs(r))} vs prior ${a}d`}function _f(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}`,o=`${r.startDate} to ${r.endDate}`,d=`Tile percentages compare these ${s} ${l} (${o}) 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 co(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function uo(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 mo(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Bf({projectName:t,refreshNonce:s}){const n=ws(),{isAdmin:a}=Fn(),r=Xs(),[l,i]=c.useState(!1),[o,d]=c.useState([]),[m,u]=c.useState([]),[h,g]=c.useState([]),[x,y]=c.useState(null),[p,v]=c.useState([]),[j,w]=c.useState([]),[I,k]=c.useState(null),[f,b]=c.useState(""),[S,A]=c.useState(""),[P,C]=c.useState("30"),[U,O]=c.useState(!1),[J,V]=c.useState("30d"),[H,te]=c.useState(["clicks","impressions"]),[D,$]=c.useState(!0),[Q,B]=c.useState(null),[_,M]=c.useState(0),[W,ne]=c.useState({startDate:"",endDate:"",query:"",page:""}),[ie,be]=c.useState(0),[ke,X]=c.useState(!1),[le,je]=c.useState(0),[ee,oe]=c.useState(!1),[G,ue]=c.useState(""),[se,Se]=c.useState(!0),[Ce,Ie]=c.useState(!1),[Be,qe]=c.useState(!1),[pe,F]=c.useState(!1),[Ke,T]=c.useState(!1),[ye,Ve]=c.useState(!1),[Ye,et]=c.useState(!1),[xe,ft]=c.useState(null),[ze,nt]=c.useState(!1),[as,xt]=c.useState(!1),[at,yt]=c.useState(null),[At,$t]=c.useState(null),[He,R]=c.useState([]),[Ae,me]=c.useState(new Set),[Je,Ft]=c.useState({}),[Kt,ut]=c.useState(new Set),[Z,Ge]=c.useState(""),[Te,Pe]=c.useState(null),[Gt,St]=c.useState(""),[rs,it]=c.useState(!1),[_t,cs]=c.useState(!1),[Is,Ts]=c.useState(!1),[Ls,nn]=c.useState(!1),[jt,Ss]=c.useState("indexed"),[st,zt]=c.useState(null),ds=!!(W.query.trim()||W.page.trim()||st),ps=st!==null,Cs=c.useMemo(()=>{if(!st)return h;const{key:N,dir:z}=st;return[...h].sort((de,we)=>{const lt=N===$n.CTR?Number.isFinite(de.ctr)?de.ctr:0:de[N],Ue=N===$n.CTR?Number.isFinite(we.ctr)?we.ctr:0:we[N];return z==="asc"?lt-Ue:Ue-lt})},[h,st]),Rt=Dn({rows:Cs,pageSize:zs}),Mt=ee?Rt.rows:Cs,us=Dn({rows:(at??[]).filter(N=>N.path.toLowerCase().includes(Z.trim().toLowerCase())),pageSize:zs}),[Wt,an]=c.useState([]),[Ct,is]=c.useState(null),[bt,K]=c.useState(1),ae=c.useMemo(()=>{if(Wt.length<2)return null;const N=Wt[Wt.length-1],z=Wt[Wt.length-2];return{indexed:N.indexed-z.indexed,notIndexed:N.notIndexed-z.notIndexed}},[Wt]);c.useEffect(()=>{K(1)},[xe,jt,Ct]);const Re=c.useMemo(()=>Ct?(xe?.reasonGroups??[]).find(N=>N.reason===Ct):void 0,[xe,Ct]),he=c.useMemo(()=>xe?jt==="indexed"?xe.indexed:jt==="deindexed"?xe.deindexed:jt==="notIndexed"?Ct?Re?.urls??[]:(xe.reasonGroups??[]).length===0?xe.notIndexed:[]:[]:[],[xe,jt,Ct,Re]),Le=Math.max(1,Math.ceil(he.length/dn)),Qe=Math.min(Math.max(1,bt),Le),gt=(Qe-1)*dn,Nt=c.useMemo(()=>xe?.indexed.slice(gt,gt+dn)??[],[xe,gt]),ms=c.useMemo(()=>xe?.notIndexed.slice(gt,gt+dn)??[],[xe,gt]),E=c.useMemo(()=>xe?.deindexed.slice(gt,gt+dn)??[],[xe,gt]),Ne=c.useMemo(()=>(Re?.urls??[]).slice(gt,gt+dn),[Re,gt]),[mt,Bt]=c.useState(!1),[ls,We]=c.useState(null),[wt,gs]=c.useState(null),[ca,ks]=c.useState(null);function vn(N,z){const de=dg(N),we=Df(de);we?(gs(we),We(null)):(gs(null),We(de.message||z))}const Ut=o.find(N=>N.connectionType==="gsc"),$s=(Ut?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),jn=He.length>0?He:(at??[]).map(N=>N.path),Fa=jn.filter(N=>at?.some(z=>z.path===N&&z.isSitemapsIndex)).length,da=Fa===1?"Resubmit sitemap index":Fa>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",wl=h.length>0||p.length>0||j.length>0,Ka=xu(),Nn=pu();async function Ga(N,z=!1){if(r){u([]);return}if(!N){u([]),b("");return}qe(!0);try{const{sites:de}=await n.fetchQuery({...Iu({client:Y,path:{name:t}}),staleTime:z?0:ts});u(de),b(N.propertyId??de[0]?.siteUrl??""),gs(null)}catch(de){u([]),vn(de,"Failed to load Search Console properties")}finally{qe(!1)}}async function Ms(N){T(!0);const z=N??ie;try{const de=ds?Xa:zs,we=ds?0:z,lt={limit:String(de)};W.startDate&&(lt.startDate=W.startDate),W.endDate&&(lt.endDate=W.endDate),W.query&&(lt.query=W.query),W.page&&(lt.page=W.page),we>0&&(lt.offset=String(we)),J&&J!=="all"&&!W.startDate&&(lt.window=J);const Ue=await n.fetchQuery({...bu({client:Y,path:{name:t},query:lt}),staleTime:ts}),pt=Ue.rows;ds?(X(!1),g(pt),je(pt.length),oe(!0)):(X(we+pt.length<Ue.totalMatching),g(pt),je(0),oe(!1))}catch(de){g([]),X(!1),je(0),We(de instanceof Error?de.message:"Failed to load GSC performance data")}finally{T(!1)}}async function rn(){try{const N={};W.startDate&&(N.startDate=W.startDate),W.endDate&&(N.endDate=W.endDate),J&&J!=="all"&&!W.startDate&&(N.window=J);const z=await n.fetchQuery({...yu({client:Y,path:{name:t},query:N}),staleTime:ts});y(z)}catch{y(null)}}async function ln(N=!1){Ve(!0);try{const z=G.trim()||void 0,de={limit:"20"};z&&(de.url=z);const[we,lt]=await Promise.all([n.fetchQuery({...Ru({client:Y,path:{name:t},query:de}),staleTime:N?0:ts}),n.fetchQuery({...Pu({client:Y,path:{name:t}}),staleTime:N?0:ts})]);v(we),w(lt)}catch(z){v([]),w([]),We(z instanceof Error?z.message:"Failed to load GSC inspection history")}finally{Ve(!1)}}async function _n(N=!1){nt(!0);try{const[z,de]=await Promise.all([n.fetchQuery({...Nu({client:Y,path:{name:t}}),staleTime:N?0:ts}),n.fetchQuery({...wu({client:Y,path:{name:t}}),staleTime:N?0:ts}).catch(()=>[])]);ft(z),an(de)}catch(z){ft(null),an([]),We(z instanceof Error?z.message:"Failed to load coverage data")}finally{nt(!1)}}async function Bn(N){Bt(!0),We(null);try{const z=await Al(t,{urls:N}),{succeeded:de,failed:we,total:lt}=z.summary;Oe({title:"Indexing requested",detail:we===0?`${de} URL${de!==1?"s":""} submitted for indexing.`:`${de}/${lt} submitted successfully, ${we} failed.`,tone:we===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(z){We(z instanceof Error?z.message:"Failed to request indexing")}finally{Bt(!1)}}async function ua(){Bt(!0),We(null);try{const N=await Al(t,{urls:[],allUnindexed:!0}),{succeeded:z,failed:de,total:we}=N.summary;Oe({title:"Indexing requested",detail:de===0?`${z} unindexed URL${z!==1?"s":""} submitted for indexing.`:`${z}/${we} submitted successfully, ${de} failed.`,tone:de===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(N){We(N instanceof Error?N.message:"Failed to request indexing")}finally{Bt(!1)}}async function Un(){xt(!0),We(null);try{const N=await Dr(t);n.setQueryData(Su({client:Y,path:{name:t}}),N),yt(N.sitemaps),$t(N.summary),R(N.preferredSubmissionUrls),me(new Set),Ft({}),N.sitemaps.length===0&&ks("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(N){We(N instanceof Error?N.message:"Failed to list sitemaps")}finally{xt(!1)}}async function Mr(N){const z=Ae.has(N);if(me(de=>{const we=new Set(de);return z?we.delete(N):we.add(N),we}),!(z||Je[N])){ut(de=>new Set(de).add(N));try{const de=await Dr(t,N);Ft(we=>({...we,[N]:de.sitemaps}))}catch(de){We(de instanceof Error?de.message:"Failed to load sitemap files")}finally{ut(de=>{const we=new Set(de);return we.delete(N),we})}}}async function on(N){if(!$s||N.length===0)return;const z=[...new Set(N)];cs(!0),We(null),Pe({completed:0,total:z.length});let de=0,we=0,lt=0,Ue=null;try{for(let Vt=0;Vt<z.length;Vt+=50){const ht=z.slice(Vt,Vt+50);try{const $e=await Cu(t,ht);de+=$e.summary.accepted,we+=$e.summary.failed,lt+=ht.length,Pe({completed:lt,total:z.length})}catch($e){lt+=ht.length;const qs=ht.length,Sn=z.length-lt,Vn=$e instanceof Error?$e.message:"The batch request failed",As=`${de} accepted, ${we} failed, ${qs} unconfirmed, ${Sn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Ue=`Sitemap submission stopped after a batch request failed. ${As} ${Vn}`,We(Ue),Oe({title:"Sitemap resubmission partially completed",detail:As,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const pt=z.length;Oe({title:we===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:we===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${de}/${pt} sitemap submissions; ${we} failed. Indexing is not guaranteed.`,tone:we===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),St("")}catch(pt){We(pt instanceof Error?pt.message:"Failed to submit sitemap to Google")}finally{cs(!1),Pe(null),await Un(),Ue&&We(Ue)}}async function Sl(){cs(!0);const N=at??[];try{const z=N.filter(we=>we.isSitemapsIndex),de=[];for(let we=0;we<z.length;we+=4)(await Promise.all(z.slice(we,we+4).map(async Ue=>{const pt=Je[Ue.path];if(pt)return pt;const Vt=await Dr(t,Ue.path);return Ft(ht=>({...ht,[Ue.path]:Vt.sitemaps})),Vt.sitemaps}))).forEach((Ue,pt)=>{de.push(...Ue.length>0?Ue.map(Vt=>Vt.path):[z[we+pt].path])});await on([...N.filter(we=>!we.isSitemapsIndex).map(we=>we.path),...de])}catch(z){We(z instanceof Error?z.message:"Failed to load sitemap files"),cs(!1)}}async function wn(N){it(!0),We(null);try{await ku(t,"gsc",N),await qt(n,"google"),d(z=>z.map(de=>de.connectionType==="gsc"?{...de,sitemapUrl:N}:de)),Oe({title:"Default sitemap updated",detail:N,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(z){We(z instanceof Error?z.message:"Failed to set the default sitemap")}finally{it(!1)}}async function ma(N){try{await Nn.mutateAsync({projectName:t,projectLabel:t,opts:N?{sitemapUrl:N}:void 0})}catch{}}async function ha(){Se(!0),We(null);try{const[N,z]=await Promise.all([r||!a?Promise.resolve(null):yc().catch(()=>null),n.fetchQuery({...Wi({client:Y,path:{name:t}}),staleTime:ts}).catch(()=>[])]);i(!!N?.google?.configured),d(z);const de=z.find(we=>we.connectionType==="gsc");await Promise.all([r?Promise.resolve():Ga(de),Ms(),rn(),ln(),_n(),!r&&de?.propertyId?Un():Promise.resolve()])}finally{Se(!1)}}c.useEffect(()=>{ha()},[t,s,a]),c.useEffect(()=>{be(0),B(null),ne(N=>N.startDate||N.endDate?{...N,startDate:"",endDate:""}:N),M(N=>N+1),rn()},[J]);const _a=c.useRef(!1);c.useEffect(()=>{if(!_a.current){_a.current=!0;return}be(0),Rt.setPage(1),Ms(0)},[_]);function cn(N){const z=Q===N?null:N;B(z),ne(de=>({...de,startDate:z??"",endDate:z??""})),M(de=>de+1)}const xa=c.useRef(!1);c.useEffect(()=>{if(!xa.current){xa.current=!0;return}be(0),Ms(0)},[ps]);async function Ba(){if(!l){We("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Ie(!0),We(null),ks(null);try{let N=function($e){if($e.source!==we||$e.origin!==lt||!$e.data||typeof $e.data!="object")return;const qs=$e.data;qs.type!==Kf||qs.connectionType!=="gsc"||ht(!0)};const{authUrl:z,redirectUri:de}=await ju(t,"gsc");if(!z.startsWith("https://accounts.google.com/")){We("Unexpected OAuth redirect URL. Please try again.");return}const we=window.open(z,"_blank","width=600,height=700");if(!we){window.location.assign(z);return}const lt=de?new URL(de).origin:window.location.origin;let Ue=!1,pt=null;const Vt=()=>{pt!==null&&window.clearInterval(pt),window.removeEventListener("message",N)},ht=async $e=>{if(!Ue){Ue=!0,Vt(),ks($e?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await qt(n,"google"),await ha()}finally{ks(null)}}};window.addEventListener("message",N),ks("Finish the Google consent flow in the popup. This page will refresh automatically."),pt=window.setInterval(()=>{we.closed&&ht(!1)},1e3)}catch(N){We(N instanceof Error?N.message:"Failed to start OAuth flow")}finally{Ie(!1)}}async function qr(){We(null),ks(null);try{await vu(t,"gsc"),await qt(n,"google"),d(N=>N.filter(z=>z.connectionType!=="gsc")),u([]),b("")}catch(N){We(N instanceof Error?N.message:"Failed to disconnect")}}async function Ua(){if(f){F(!0),We(null);try{await Tu(t,"gsc",f),await qt(n,"google"),d(N=>N.map(z=>z.connectionType==="gsc"?{...z,propertyId:f}:z)),Oe({title:"GSC property updated",detail:`${t} is now linked to ${f}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(N){We(N instanceof Error?N.message:"Failed to save GSC property")}finally{F(!1)}}}async function Er(){We(null),ks(null);try{await Ka.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(P,10)||void 0,full:U||void 0}}),await qt(n,"gsc")}catch{}}async function Va(){if(S.trim()){et(!0),We(null),ks(null);try{const N=await Au(t,S.trim());await qt(n,"gsc"),k(N),A(""),await ln()}catch(N){We(N instanceof Error?N.message:"Failed to inspect URL")}finally{et(!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"})]})}),wt&&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:wt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:wt.message}),(Hn(wt.enableUrl)||Hn(wt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Hn(wt.enableUrl)&&e.jsx("a",{href:Hn(wt.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 ↗"}),Hn(wt.indexingApiUrl)&&e.jsx("a",{href:Hn(wt.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:()=>gs(null),children:"×"})]})}),ls&&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:[ls,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>We(null),children:"×"})]}),ca&&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:[ca,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>ks(null),children:"×"})]}),se?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Ut?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:Ut.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",xe?.lastInspectedAt?ss(xe.lastInspectedAt):"never"]}),!r&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:tt(qr),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(re,{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(L,{type:"button",variant:"outline",size:"sm",disabled:Ce,onClick:tt(Ba),children:Ce?"Opening…":"Connect Google Search Console"}):e.jsx(L,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Bs,{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:Of})}),(Ut||wl)&&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(_e,{text:`${_f(x?.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 ${Xa.toLocaleString()} matching rows while the table shows ${zs} per page.`})]}),x?.window?.startDate&&x.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[x.window.startDate," to ",x.window.endDate,(x.window.daysSinceLatestData??0)>0&&` · latest data ${x.window.daysSinceLatestData} day${x.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ir,{windows:Ff,value:J,onChange:N=>{V(N),be(0),Rt.setPage(1)},label:"Search Console time period",formatOption:N=>N==="all"?"All":N}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:Ke,onClick:()=>{be(0),Rt.setPage(1),Ms(0),rn()},children:Ke?"Loading…":"Apply filters"})]})]}),x&&x.daily.length>0&&(()=>{const{totals:N,daily:z,trends:de,periodComparison:we}=x,Ue=oo.filter($e=>H.includes($e.key)).map($e=>({dataKey:$e.key,label:$e.label,color:$e.color,axisId:$e.key,inverted:$e.inverted,formatValue:$e.format,trend:D?de?.[$e.key]??null:null})),pt=$e=>N[$e]??null,Vt=new Map(z.map($e=>[$e.date,$e])),ht=z.length===0?[]:gu(z[0].date,z[z.length-1].date).map($e=>Vt.get($e)??{date:$e});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:oo.map($e=>{const qs=H.includes($e.key),Sn=pt($e.key),Vn=Sn===null;return e.jsxs("button",{type:"button","aria-pressed":qs,disabled:Vn,className:`rounded-md border px-3 py-2 text-left transition-colors ${qs?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Vn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{te(As=>As.includes($e.key)?As.length===1?As:As.filter(Ha=>Ha!==$e.key):[...As,$e.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:qs?$e.color:"transparent",border:`1px solid ${$e.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:$e.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Sn===null?"—":$e.format(Sn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Gf(we,$e.key,$e.inverted)})]},$e.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:D,onChange:$e=>$($e.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(sl,{data:ht,xKey:"date",series:Ue,xTickFormatter:fn,labelFormatter:Tt,onSelectX:cn,selectedX:Q})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:z.map($e=>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":Q===$e.date,onClick:()=>cn($e.date),children:[Tt($e.date),": ",$e.clicks," clicks, ",$e.impressions," impressions"]},$e.date))}),Q&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Tt(Q)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>cn(Q),children:["Show all ",N.days," days"]})]}),N.position!==null&&(N.positionDays??N.days)<N.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",N.positionDays," of ",N.days," days. The rest have no property-level position recorded."]}),(N.position===null||N.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:W.startDate,onChange:N=>ne(z=>({...z,startDate:N.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:W.endDate,onChange:N=>ne(z=>({...z,endDate:N.target.value}))}),e.jsx(pn,{value:W.query,onChange:N=>ne(z=>({...z,query:N})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(pn,{value:W.page,onChange:N=>ne(z=>({...z,page:N})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),h.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($n).map(N=>e.jsx("th",{className:"text-right","aria-sort":st?.key===N?st.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:()=>{Rt.setPage(1),zt(z=>z?.key===N?z.dir==="desc"?{key:N,dir:"asc"}:null:{key:N,dir:"desc"})},children:[fu[N],st?.key===N?st.dir==="desc"?" ↓":" ↑":""]})},N))]})}),e.jsx("tbody",{children:Mt.map((N,z)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:N.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:N.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(hr,{value:N.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:N.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.impressions.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Fe(N.ctr)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.position.toFixed(1)})]},`${N.date}:${N.query}:${N.page}:${z}`))})]})}),e.jsx(Zs,{page:ee?Rt.page:Math.floor(ie/zs)+1,pageSize:zs,visibleRows:Mt.length,totalRows:ee?le:void 0,hasNextPage:ee?void 0:ke,disabled:Ke,itemLabel:ee?"matches":"rows",onPageChange:N=>{if(ee){Rt.setPage(N);return}const z=(N-1)*zs;be(z),Ms(z)}}),ee&&le>=Xa?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Xa.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(_e,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[xe&&xe.notIndexed.length>0&&e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:mt,onClick:()=>{ua()},children:mt?"Requesting…":`Request indexing (${xe.notIndexed.length})`}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:ze,onClick:()=>{_n(!0)},children:ze?"Loading…":"Reload saved coverage"})]})]}),xe&&xe.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const N=xe.summary.indexedShare??0,z=xe.summary.notIndexedShare??0,de=54,we=2*Math.PI*de,lt=we*(1-N),Ue=we*z,pt=we*N;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:os.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:Kn.positiveDeep,strokeWidth:"14",strokeDasharray:we,strokeDashoffset:lt,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),xe.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:os.textFaint,strokeWidth:"14",strokeDasharray:`${Ue} ${we-Ue}`,strokeDashoffset:-pt,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:Fe(xe.summary.indexedShare)}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:xe.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:xe.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(xe.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(xe.reasonGroups??[]).length," ",(xe.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),xe.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:xe.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(N=>{const z=N==="indexed"?xe.indexed.length:N==="notIndexed"?xe.notIndexed.length:xe.deindexed.length,de=N==="indexed"?"Indexed":N==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":jt===N,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${jt===N?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{Ss(N),is(null)},children:[de," (",z,")"]},N)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[jt==="indexed"&&xe.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:Nt.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.crawlTime?N.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:N.isMobileFriendly===!0?"Yes":N.isMobileFriendly===!1?"No":"—"})]},N.id))})]}),jt==="notIndexed"&&!Ct&&(xe.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(xe.reasonGroups??[]).map(N=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>is(N.reason),onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),is(N.reason))},tabIndex:0,role:"button","aria-label":`View ${N.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:N.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.count})]},N.reason))})]}),jt==="notIndexed"&&!Ct&&(xe.reasonGroups??[]).length===0&&xe.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:ms.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.coverageState??"Unknown"})]},N.id))})]}),jt==="notIndexed"&&Ct&&(()=>{const N=(xe.reasonGroups??[]).find(z=>z.reason===Ct);return N?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>is(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:N.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[N.count," affected page",N.count!==1?"s":""]})]}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:mt,onClick:()=>{Bn(N.urls.map(z=>z.url))},children:mt?"Requesting…":`Request indexing (${N.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Ne.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:mt,onClick:()=>{Bn([z.url])},title:"Request indexing",children:"Index"})})]},z.id))})]})]}):null})(),jt==="deindexed"&&xe.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:E.map((N,z)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.previousState}),e.jsx("td",{className:"text-secondary",children:N.currentState}),e.jsx("td",{className:"text-secondary",children:N.transitionDate.split("T")[0]})]},`${N.url}-${z}`))})]}),(jt==="indexed"&&xe.indexed.length===0||jt==="notIndexed"&&!Ct&&xe.notIndexed.length===0||jt==="deindexed"&&xe.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Zs,{page:Qe,pageSize:dn,visibleRows:Math.min(dn,he.length-gt),totalRows:he.length,onPageChange:K,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":Ls,onClick:()=>nn(N=>!N),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Ls?"Hide snapshots":Wt.length>0?`View ${Wt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",xe.summary.indexed.toLocaleString()," indexed, ",xe.summary.notIndexed.toLocaleString()," not indexed.",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."]})]}),Ls&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:Wt.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:Wt.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:N.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:N.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.notIndexed.toLocaleString()})]},N.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:ze?"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(_e,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:as||!Ut?.propertyId,onClick:()=>{Un()},children:as?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:Gt,onChange:N=>St(N.target.value),onKeyDown:N=>N.key==="Enter"&&void on([Gt.trim()])}),e.jsx(L,{type:"button",size:"sm",disabled:!$s||_t||!Gt.trim(),onClick:()=>{on([Gt.trim()])},children:_t?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:!$s||_t||jn.length===0,onClick:()=>{on(jn)},children:_t?"Resubmitting…":da}),e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:!$s||_t||!at?.length,onClick:()=>{Sl()},children:"Resubmit all files"}),At&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",At.indexes," index",At.indexes===1?"":"es",", ",At.files," file",At.files===1?"":"s"]}),Te&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Te.completed,"/",Te.total]})]}),!$s&&Ut&&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:tt(Ba),children:"Reconnect"})]}),at&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:at.length>0?e.jsxs(e.Fragment,{children:[e.jsx(pn,{value:Z,onChange:N=>{Ge(N),us.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:us.rows.flatMap(N=>{const z=co(N),de=uo(N),we=mo(N),lt=Je[N.path]??[],Ue=Ae.has(N.path),pt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(hr,{value:N.path})}),e.jsx("td",{className:"text-secondary",children:N.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":Ue,"aria-label":`${Ue?"Collapse":"Expand"} files in ${N.path}`,onClick:()=>{Mr(N.path)},children:Kt.has(N.path)?"Loading…":`${Ue?"▾":"▸"} Index${Je[N.path]?` (${lt.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:we}),e.jsx("td",{className:"text-secondary",children:N.lastSubmitted?N.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:N.lastDownloaded?N.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:z.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:de||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!$s||_t,onClick:()=>{on([N.path])},children:N.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Ut?.sitemapUrl===N.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:rs,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{wn(N.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Nn.isPending,onClick:()=>{ma(N.path)},children:"Inspect URLs"})]})})]},N.path),Vt=N.isSitemapsIndex&&Ue?lt.map(ht=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(hr,{value:ht.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:mo(ht)}),e.jsx("td",{className:"text-secondary",children:ht.lastSubmitted?ht.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ht.lastDownloaded?ht.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:co(ht).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:uo(ht)||"—"}),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:!$s||_t,onClick:()=>{on([ht.path])},children:"Resubmit"}),Ut?.sitemapUrl===ht.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:rs,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{wn(ht.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Nn.isPending,onClick:()=>{ma(ht.path)},children:"Inspect URLs"})]})})]},`${N.path}:${ht.path}`)):[];return[pt,...Vt]})})]}),e.jsx(Zs,{page:us.page,pageSize:zs,visibleRows:us.rows.length,totalRows:us.totalRows,onPageChange:us.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:N=>A(N.target.value),onKeyDown:N=>N.key==="Enter"&&void Va()}),e.jsx(L,{type:"button",size:"sm",disabled:Ye||!Ut?.propertyId||!S.trim(),onClick:tt(Va),children:Ye?"Inspecting…":"Inspect URL"})]}),I&&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:I.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:I.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:kl(I.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:ss(I.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(L,{type:"button",variant:"outline",size:"sm",disabled:ye,onClick:()=>{ln(!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:N=>ue(N.target.value)}),e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:ye,onClick:()=>{ln(!0)},children:"Apply filter"})]}),p.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Coverage"}),e.jsx("th",{className:"text-left",children:"Mobile"}),e.jsx("th",{className:"text-left",children:"Inspected"})]})}),e.jsx("tbody",{children:p.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-neutral",children:N.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:kl(N.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:ss(N.inspectedAt)})]},N.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"})]})}),j.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:j.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:N.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:ss(N.transitionDate)})]},`${N.url}:${N.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Ut&&!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:()=>Ts(N=>!N),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${Is?"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"})]})}),Is&&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(_e,{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:Be||m.length===0,onChange:N=>b(N.target.value),children:m.length===0?e.jsx("option",{value:"",children:Be?"Loading properties…":"No properties available"}):m.map(N=>e.jsxs("option",{value:N.siteUrl,children:[N.siteUrl," · ",N.permissionLevel]},N.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:Be,onClick:()=>{Ga(Ut,!0)},children:Be?"Refreshing…":"Refresh properties"}),e.jsx(L,{type:"button",size:"sm",disabled:!f||pe,onClick:tt(Ua),children:pe?"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:P,onChange:N=>C(N.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:U,onChange:N=>O(N.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(L,{type:"button",size:"sm",disabled:Ka.isPending||!Ut.propertyId,onClick:tt(Er),children:Ka.isPending?"Queueing…":"Queue sync"}),!Ut.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Uf=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Vf({projectName:t,projectId:s}){const n=ws(),[a,r]=c.useState(null),[l,i]=c.useState(null),[o,d]=c.useState(!1),m=Me(Wi({client:Y,path:{name:t}})),u=m.data?.find(X=>X.connectionType==="gbp"),h=!!u,g=a?{locationName:a}:void 0,x=Me({...Lu({client:Y,path:{name:t}}),enabled:h}),y=Me({...$u({client:Y,path:{name:t},query:g}),enabled:h}),p=Me({...Mu({client:Y,path:{name:t},query:g}),enabled:h}),v=Me({...qu({client:Y,path:{name:t},query:g}),enabled:h}),j=Me({...Eu({client:Y,path:{name:t},query:g}),enabled:h}),w=Me({...Du({client:Y,path:{name:t},query:g}),enabled:h}),I=Me({queryKey:["gbp-section-insights",t],queryFn:()=>Ou(t),enabled:h});function k(){qt(n,"gbp")}const f=Ht({...Fu(),onSuccess:X=>{bc({id:X.runId,projectId:s,kind:gn["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Oe({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),b=c.useSyncExternalStore(vc,pr,pr),S=Object.values(b.runs).some(X=>X.kind===gn["gbp-sync"]&&X.projectId===s),A=f.isPending||S,P=Ht({...Ku(),onSuccess:()=>k()});if(c.useEffect(()=>{if(!a||!x.data)return;const X=x.data.locations.filter(le=>le.selected);(X.length<=1||!X.some(le=>le.locationName===a))&&r(null)},[a,x.data]),c.useEffect(()=>{if(!l||!x.data)return;(a?[a]:x.data.locations.filter(le=>le.selected).map(le=>le.locationName)).includes(l)||i(null)},[l,x.data,a]),m.isLoading)return null;if(!u){const X=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(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:X.map((le,je)=>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:je+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:le.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:le.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:le.note})]})]},le.title))})]})})}const C=y.data,U=x.data?.locations??[],O=U.filter(X=>X.selected),J=p.data?.keywords??[],V=v.data?.lodging??[],H=j.data?.placeActions??[],te=w.data?.places??[],D=U.length>0?U[0].accountName:u.domain,$=a?U.find(X=>X.locationName===a)?.displayName??null:null,Q=a?U.filter(X=>X.locationName===a):O,B=new Set(Q.map(X=>X.locationName)),_=V.filter(X=>B.has(X.locationName)),M=H.filter(X=>B.has(X.locationName)),W=te.filter(X=>B.has(X.locationName)),ne=new Set(O.map(X=>X.locationName)),ie=a?J:J.filter(X=>ne.has(X.locationName)),be=!a&&O.length>1,ke=(I.data??[]).filter(X=>!X.dismissed&&Uf.has(X.type)&&(!$||X.query===$||X.query===a||X.title.startsWith($)));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(_e,{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(re,{tone:"positive",children:"Connected"}),!ce()&&e.jsx(Ze,{type:"button",variant:"outline",size:"sm",disabled:A,onClick:()=>f.mutate({client:Y,path:{name:t},body:{}}),children:A?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[D?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:D})," · "]}):null,x.data?`${x.data.totalSelected} of ${x.data.totalDiscovered} locations tracked`:"Loading locations…"]}),O.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:X=>r(X.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),O.map(X=>e.jsx("option",{value:X.locationName,children:X.displayName},X.id))]})]}),O.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:[ke.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),ke.map(X=>e.jsx("div",{className:["insight-card",ay(X.severity),"rounded-r-lg border border-default bg-surface p-3 pl-4"].filter(Boolean).join(" "),children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-strong",children:[X.title,X.recommendation?.reason&&e.jsx(_e,{text:X.recommendation.reason})]})},X.id))]}),C&&e.jsx(oy,{performance:C.performance,freshness:C.freshness,timeseries:C.timeseries}),C?.profileCompleteness&&e.jsx(Hf,{summary:C.profileCompleteness}),Q.length>0&&e.jsx(Qf,{locations:Q,lodging:_,places:W,placeActions:M,expandedLocation:l,onToggleExpanded:X=>{i(le=>le===X?null:X)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),p.data&&p.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[Fe(p.data.thresholdedPct,Lt.percent)," privacy-thresholded"]})]}),ie.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"}),be&&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:ie.slice(0,25).map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:X.keyword}),be&&e.jsx("td",{className:"text-muted",children:U.find(le=>le.locationName===X.locationName)?.displayName??X.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:X.valueCount!==null?X.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",X.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[X.periodStart,"–",X.periodEnd]})]},`${X.locationName}:${X.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>d(X=>!X),"aria-expanded":o,children:[e.jsx("span",{"aria-hidden":"true",children:o?"▾":"▸"})," Manage locations (",U.length,")"]}),o&&e.jsx("div",{className:"mt-3",children:U.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"}),!ce()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:U.map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:X.displayName}),e.jsx("td",{className:"text-muted",children:X.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(re,{tone:X.selected?"positive":"neutral",children:X.selected?"Tracked":"Not tracked"})}),!ce()&&e.jsx("td",{className:"text-right",children:e.jsx(Ze,{type:"button",variant:"outline",size:"sm",disabled:P.isPending,onClick:()=>P.mutate({client:Y,path:{name:t,locationName:X.locationName},body:{selected:!X.selected}}),children:X.selected?"Untrack":"Track"})})]},X.id))})]})})]})]})})}function Hf({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:ga(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:ga(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:ga(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:ga(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:ga(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(_e,{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 ${ny(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Qf({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:l}){const i=new Map(s.map(m=>[m.locationName,m])),o=new Map(n.map(m=>[m.locationName,m])),d=new Map;for(const m of a){const u=d.get(m.locationName)??[];u.push(m),d.set(m.locationName,u)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(_e,{text:ce()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(m=>{const u=i.get(m.locationName)??null,h=o.get(m.locationName)??null,g=d.get(m.locationName)??[],x=r===m.locationName;return e.jsxs(c.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:m.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:m.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(re,{tone:m.selected?"positive":"neutral",children:m.selected?"Tracked":"Not tracked"}),m.openStatus&&m.openStatus!=="OPEN"&&e.jsx(re,{tone:m.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:bd(m.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Wf,{location:m})}),e.jsx("td",{children:e.jsx(Yf,{lodging:u})}),e.jsx("td",{children:e.jsx(Xf,{place:h,mapsUri:m.mapsUri})}),e.jsx("td",{children:e.jsx(ey,{actions:g})}),e.jsx("td",{className:"text-right",children:e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>l(m.locationName),children:x?"Hide":"Details"})})]}),x&&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(sy,{location:m,lodging:u,place:h,placeActions:g})})})]},m.id)})})]})})]})}function zf(t){return[{label:"Description",tone:Tn(t.description)?"positive":"neutral",value:Tn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Tn(t.primaryPhone)?"positive":"neutral",value:Tn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Tn(t.websiteUri)?"positive":"neutral",value:Tn(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 Wf({location:t}){const s=zf(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(re,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Yf({lodging:t}){return e.jsx(al,{...Jf(t)})}function Jf(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 Xf({place:t,mapsUri:s}){return e.jsx(al,{...Zf(t,s)})}function Zf(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 ey({actions:t}){return e.jsx(al,{...ty(t)})}function ty(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 al({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(re,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function sy({location:t,lodging:s,place:n,placeActions:a}){const r=s?iy(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Yr,{title:"Owner profile · Business Information",children:[e.jsx(Zt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Zt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Zt,{label:"Description",value:Tn(t.description)?t.description:"Not returned"}),e.jsx(Zt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Zt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Zt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Zt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Zt,{label:"Open status",value:bd(t.openStatus)}),e.jsx(Zt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Yr,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Zt,{label:"Last checked",value:ho(s.syncedAt)}),e.jsx(Zt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Zt,{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(Yr,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Zt,{label:"Places tier",value:n.tier}),e.jsx(Zt,{label:"Last checked",value:ho(n.syncedAt)}),e.jsx(Zt,{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:[Nr(l.placeActionType),l.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Nr(l.providerType),l.uri?` · ${ry(l.uri)}`:""]})]},l.placeActionLinkName))})})]})]})}function Yr({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 Zt({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 ga(t,s,n){return t===s?"positive":t===0?n:"caution"}function ny(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function ay(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Tn(t){return typeof t=="string"&&t.trim().length>0}function bd(t){return t?Nr(t):"Not returned"}function Nr(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function ry(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function ho(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function iy(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&ly(n)).map(([s])=>Nr(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function ly(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function oy({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Gu.filter(y=>(a[y]??0)>0),l=_u.filter(y=>(a[y]??0)>0),i=Object.keys(a).filter(y=>(a[y]??0)>0&&Bu(y)==="other").sort((y,p)=>(a[p]??0)-(a[y]??0)),o=Object.keys(a).filter(y=>(a[y]??0)===0).sort(),d=n.map(y=>{const p={date:y.date};for(const[v,j]of Object.entries(y.metrics))p[v]=j;return p}),m=n.find(y=>y.pending)?.date,u=n.length>0?n[n.length-1].date:void 0,h=d.length>0,g=s.dataThroughDate?`Data through ${Tt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,x=[...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})]}),!h||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(xo,{data:d,metrics:r,kind:"line",firstPending:m,lastDate:u}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:x.map(y=>e.jsxs("span",{className:"text-sm text-secondary",children:[gr(y)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[y]??0).toLocaleString()})]},y))})]})]}),h&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(xo,{data:d,metrics:l,kind:"area",firstPending:m,lastDate:u})]}),o.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",o.map(y=>gr(y)).join(", ")]})]})}function xo({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Us,{width:"100%",height:"100%",children:e.jsxs(yn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ia,{stroke:Ra,vertical:!1}),e.jsx(Vs,{dataKey:"date",tick:Qt,tickLine:!1,axisLine:{stroke:xs},tickFormatter:fn,minTickGap:24}),e.jsx(Hs,{tick:Qt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(bn,{...hs,labelFormatter:Tt,formatter:(l,i)=>[typeof l=="number"?l.toLocaleString():String(l??0),gr(String(i??""))]}),e.jsx(vr,{wrapperStyle:{fontSize:11,color:os.text},formatter:l=>gr(l)}),a&&r&&e.jsx(Ci,{x1:a,x2:r,fill:os.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:os.textDim,fontSize:10}}),s.map((l,i)=>n==="line"?e.jsx(Ys,{type:"monotone",dataKey:l,stroke:ct[i%ct.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx(hn,{type:"monotone",dataKey:l,stackId:"reach",stroke:ct[i%ct.length],fill:ct[i%ct.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},l))]})})})}function cy(t){return zc(Dt(String(t)))}function dy(t){return oa(Dt(String(t)))}function Jr({children:t,label:s="More info",placement:n="top",className:a}){const r=c.useId(),[l,i]=c.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(eg,{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 Za=zs;function Qn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Xr(t){return t.toLocaleString()}function uy(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 my(t){const s=t.filter(n=>n.kind===gn["backlink-extract"]&&!jc(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function hy(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 xy({projectName:t}){const s=Xs(),[n,a]=c.useState(null),[r,l]=c.useState(null),[i,o]=c.useState([]),[d,m]=c.useState(null),[u,h]=c.useState(null),[g,x]=c.useState(null),[y,p]=c.useState(Date.now()),[v,j]=c.useState(0),[w,I]=c.useState(!0),[k,f]=c.useState(!1),[b,S]=c.useState(null),A=c.useCallback(async()=>{I(!0),S(null);try{const[$,Q,B,_,M]=await Promise.all([Uu().catch(()=>null),Vu(t,{excludeCrawlers:!0}).catch(()=>null),Hu(t,{limit:Za,offset:v,excludeCrawlers:!0}).catch(ne=>{if(ne instanceof En&&ne.code==="NOT_FOUND")return null;throw ne}),Qu(t).catch(()=>[]),zu(t).catch(()=>[])]);m($),a(Q),l(B),o(_);const W=my(M);h(W)}catch($){S($ instanceof Error?$.message:"Failed to load backlinks")}finally{I(!1)}},[t,v]);c.useEffect(()=>{A()},[A]),c.useEffect(()=>{if(!u)return;const $=u.id;let Q=!1;const B=async()=>{try{const M=await wi($);if(Q)return;jc(M.status)?(h(null),x(M),await A()):h(W=>W?.id===M.id?{...W,...M}:W)}catch{}},_=window.setInterval(()=>{B()},3e3);return()=>{Q=!0,window.clearInterval(_)}},[u,A]),c.useEffect(()=>{if(!u)return;const $=window.setInterval(()=>p(Date.now()),1e3);return()=>window.clearInterval($)},[u]),c.useEffect(()=>{if(!g||g.status==="failed")return;const $=window.setTimeout(()=>x(null),1e4);return()=>window.clearTimeout($)},[g]);async function P(){f(!0),S(null);try{const $=await Yu(t);h($)}catch($){$ instanceof En&&$.code==="MISSING_DEPENDENCY"?S("DuckDB is not installed. Visit the Backlinks admin page to install it."):S($ instanceof Error?$.message:"Failed to trigger extract")}finally{f(!1)}}const C=c.useMemo(()=>i.slice().sort(($,Q)=>$.queriedAt.localeCompare(Q.queriedAt)).map($=>({date:$.queriedAt,linkingDomains:$.totalLinkingDomains})),[i]),U=r?.rows??[],O=r?.total??0,J=n?.excludedLinkingDomains??0,V=Math.floor(v/Za)+1;return c.useEffect(()=>{v>0&&v>=O&&j(0)},[v,O]),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"})]})}),b&&e.jsx(ve,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:b})}),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(Jp,{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(re,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[hy(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(Xp,{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:Wu(g.error)}):g.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),H()]});function H(){return w?e.jsx(ve,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):te()}function te(){const $=n!==null&&n.totalLinkingDomains>0,Q=g?.status==="failed",B=n!==null&&n.totalLinkingDomains===0&&!Q,_=d?.status==="ready",M=d?.status==="failed",W=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return $?D(e.jsxs(e.Fragment,{children:[!ce()&&!s&&e.jsxs(e.Fragment,{children:[e.jsxs(L,{type:"button",variant:"outline",size:"sm",disabled:k||u!==null,onClick:tt(P),children:[e.jsx(Yc,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":k?"Queuing…":"Re-run extract"]}),e.jsx(Jr,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ce()&&!s&&e.jsx(L,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Qn("/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(Zp,{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."}),!ce()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Qn("/backlinks"),children:"Set up backlinks"})})})]}),W&&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."]}),!ce()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(L,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Qn("/backlinks"),children:"View sync status"})})})]}),M&&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."}),!ce()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Qn("/backlinks"),children:"Go to Backlinks admin"})})})]}),_&&!W&&!B&&!Q&&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."]}),!ce()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(L,{type:"button",size:"sm",disabled:k||u!==null,onClick:tt(P),children:[e.jsx(br,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":k?"Queuing…":"Run extract"]}),e.jsx(Jr,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),Q&&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."}),!ce()&&!s&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Qn("/backlinks"),children:"Go to Backlinks admin"})})})]}),B&&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."]}),!ce()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Qn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(L,{type:"button",variant:"outline",size:"sm",disabled:k||u!==null,onClick:tt(P),children:[e.jsx(br,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":k?"Queuing…":"Re-run extract"]}),e.jsxs(Jr,{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 D($){if(!n)return null;const Q="Linking hosts",B="linking hosts",_="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:Xr(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 ",B]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Xr(n.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",B," 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:Fe(Number(n.top10HostsShare))})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",B," 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.jsx("code",{className:"text-secondary",children:n.release})," · queried ",uy(n.queriedAt),J>0&&e.jsxs(e.Fragment,{children:[" · ",J," excluded domain",J===1?"":"s"]})]}),C.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(Us,{width:"100%",height:"100%",children:e.jsxs(yn,{data:C,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:ct[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:ct[0],stopOpacity:0})]})}),e.jsx(Vs,{dataKey:"date",tick:Qt,stroke:xs,tickFormatter:cy}),e.jsx(Hs,{tick:Qt,stroke:xs,allowDecimals:!1}),e.jsx(bn,{contentStyle:hs.contentStyle,labelStyle:hs.labelStyle,itemStyle:hs.itemStyle,labelFormatter:dy}),e.jsx(hn,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:ct[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(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:Q})]})}),e.jsxs("tbody",{children:[U.map(M=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:M.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Xr(M.numHosts)})]},M.linkingDomain)),U.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:J>0&&O===0?`Every referring domain in this ${_} was a crawler/proxy host (${J} hidden).`:`No referring domains in this ${_}.`})})]})]})}),e.jsx(Zs,{page:V,pageSize:Za,visibleRows:U.length,totalRows:O,onPageChange:M=>j((M-1)*Za)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:$})]})}}const py=["non-brand","branded","unclassified"],po={"non-brand":"Non-brand",branded:"Branded",unclassified:"Unclassified"};function gy(t,s){return s<=0?"neutral":t/s*100>=70?"positive":"caution"}function fy(t,s){const n=[...new Set(t.byQuery.flatMap(i=>i.providers.map(o=>o.provider)))].sort(),a=new Map,r=i=>{const o=s(i)??"unclassified";let d=a.get(o);return d||(d={key:o,queries:0,unanswered:0,engines:n.map(m=>({provider:m,answered:0,mentioned:0,cited:0})),answers:0,competitorCited:0,competitorGaps:[],citedAndNamed:0,citedNotNamed:0,namedNotCited:0,neither:0},a.set(o,d)),d},l=new Map;for(const i of t.byQuery){const o=r(i.query);if(i.providers.length===0){o.unanswered++;continue}o.queries++;for(const u of i.providers){l.set(`${i.queryId}::${u.provider}`,i.query);const h=o.engines.find(g=>g.provider===u.provider);h.answered++,u.mentioned&&h.mentioned++,u.cited&&h.cited++,o.answers++}const d=i.providers.some(u=>u.cited),m=i.providers.some(u=>u.mentioned);d&&m?o.citedAndNamed++:d?o.citedNotNamed++:m?o.namedNotCited++:o.neither++}for(const i of t.competitorGaps){const o=l.get(`${i.queryId}::${i.provider}`);if(o===void 0)continue;const d=r(o);d.competitorCited++,d.competitorGaps.push({query:o,provider:i.provider,competitors:i.citingCompetitors})}return py.map(i=>a.get(i)).filter(i=>i!==void 0&&i.queries>0)}function yy(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 by={engine:"engine no longer configured",query:"query no longer tracked"},go={"non-brand":"non-brand queries",branded:"branded queries",unclassified:"unclassified queries"},vy="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 zn(t,s,n){return t===1?s:n}function jy({projectName:t,classify:s,hasCompetitors:n,providerScores:a=[]}){const r=c.useId(),[l,i]=c.useState("non-brand"),o=Me({...Ju({client:Y,path:{name:t}}),staleTime:Yi}),d=o.data??null,m=d?.status==="ready"?fy(d,s):[],u=m.find(p=>p.key===l)??m.at(0);let h;o.isError?h=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: ",Pt(o.error)]}),e.jsx(L,{type:"button",size:"sm",variant:"outline",onClick:()=>{o.refetch()},children:"Retry"})]}):d?d.status==="no-data"?h=e.jsx("p",{className:"text-sm text-secondary",children:d.reason==="no-queries"?"Add queries to start tracking AI citations.":Ns()?aa:"Engine results appear after the first AI Visibility sweep."}):u||(h=e.jsx("p",{className:"text-sm text-secondary",children:"No engine answers yet."})):h=e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine results…"});const g=[];if(u&&d?.status==="ready"){const p=zn(u.queries,"query","queries");g.push(e.jsxs(e.Fragment,{children:["Cited and named: ",e.jsxs("strong",{children:[u.citedAndNamed," of ",u.queries]})," ",p]})),g.push(e.jsxs(e.Fragment,{children:["Cited but not named: ",e.jsxs("strong",{children:[u.citedNotNamed," of ",u.queries]})," ",p]})),g.push(e.jsxs(e.Fragment,{children:["Named but not cited: ",e.jsxs("strong",{children:[u.namedNotCited," of ",u.queries]})," ",p]})),g.push(e.jsxs(e.Fragment,{children:["Not cited or named: ",e.jsxs("strong",{children:[u.neither," of ",u.queries]})," ",p]}));for(const I of u.engines)I.answered<u.queries&&g.push(e.jsxs(e.Fragment,{children:[dt(I.provider),": answered ",e.jsxs("strong",{children:[I.answered," of ",u.queries]})," ",p]}));u.unanswered>0&&g.push(e.jsxs(e.Fragment,{children:["No answers yet: ",e.jsx("strong",{children:u.unanswered})," ",zn(u.unanswered,"query","queries")]}));const{providersCiting:v,providersMentioning:j,providersConfigured:w}=d.summary;g.push(e.jsxs(e.Fragment,{children:["All queries: cited by ",e.jsxs("strong",{children:[v," of ",w]})," ",zn(w,"engine","engines"),", named by ",e.jsxs("strong",{children:[j," of ",w]})]}));for(const I of a)g.push(e.jsxs(e.Fragment,{children:[dt(I.provider),I.model?` (${I.model})`:""," citation rate:"," ",e.jsx("strong",{children:Fe(I.score,Lt.percent)}),", ",e.jsxs("strong",{children:[I.cited," of ",I.total]})," ",zn(I.total,"answer","answers"),", all queries"]}));for(const I of u.competitorGaps)g.push(`"${I.query}" (${dt(I.provider)}): ${I.competitors.join(", ")} cited instead of you`);for(const I of yy(d))g.push(`"${I.query}" (${dt(I.provider)}): ${I.competitors.join(", ")} cited instead of you, not counted (${by[I.reason]})`)}const x=d?.status==="ready"?d.summary.latestRunAt:null,y=(p,v)=>u?.key==="non-brand"?Aa[gy(p,v)]:"text-primary";return e.jsxs("section",{className:"overview-brief","aria-labelledby":r,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:r,className:"av-card-title",children:"By engine"}),u&&e.jsx(_e,{text:vy})]}),x||u?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[x?e.jsxs("p",{className:"av-card-meta",children:["Latest run ",Rr(x)]}):null,m.length>1?e.jsx(Ca,{label:"Query type",className:"flex-wrap",options:m.map(p=>({value:p.key,label:po[p.key]})),value:u.key,onChange:i}):u?e.jsx("span",{className:"mention-share-class",children:po[u.key]}):null]}):null]}),e.jsx("div",{className:"av-card-body",children:h??(u&&e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":`By engine, ${go[u.key]}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsxs("th",{scope:"col",children:["Of ",u.queries," ",zn(u.queries,"query","queries")]}),u.engines.map(p=>e.jsx("th",{scope:"col",children:dt(p.provider)},p.provider))]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Mentioned"}),u.engines.map(p=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(p.mentioned,p.answered)}`,children:p.mentioned})},p.provider))]}),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Cited"}),u.engines.map(p=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(p.cited,p.answered)}`,children:p.cited})},p.provider))]})]})]}),e.jsxs("p",{className:"av-card-line",children:[e.jsx("span",{className:"av-card-line-label",children:"Competitor cited instead of you"}),n?e.jsxs("span",{children:[e.jsx("span",{className:"av-n-sm text-primary",children:u.competitorCited})," ",e.jsxs("span",{className:"av-of",children:["of ",u.answers," ",zn(u.answers,"answer","answers")]}),e.jsxs("span",{className:"sr-only",children:[" · ",go[u.key]]})]}):e.jsx("span",{className:"text-[13px] text-secondary",children:"No competitors tracked"})]})]}))}),e.jsx(Ma,{items:g})]})}const Ny={[_s.queued]:{word:"queued",tone:"text-secondary"},[_s.running]:{word:"running",tone:"text-info-300"},[_s.completed]:{word:"completed",tone:"text-secondary"},[_s.partial]:{word:"partial",tone:"text-caution-400"},[_s.failed]:{word:"failed",tone:"text-negative-400"},[_s.cancelled]:{word:"cancelled",tone:"text-secondary"}};function wy({runs:t,collapsed:s=!1}){const n=c.useId(),{openRun:a}=Qi(),r=new Set(t.map(o=>o.location??"")).size>1,l=t.some(o=>o.kind!==gn["answer-visibility"]),i=t.map(o=>`${o.startedAt}: ${o.summary}.${o.statusDetail?` ${o.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(ra,{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(o=>{const d=Ny[o.status],m=o.status===_s.partial||o.status===_s.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(o.id),"aria-label":`View the ${o.startedAt} sweep`,children:o.startedAt})}),l?e.jsx("td",{className:"text-[13px] text-secondary",children:o.kindLabel}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:o.triggerLabel}),r?e.jsx("td",{className:"text-[13px] text-secondary",children:o.location??"No location"}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:o.duration}),e.jsxs("td",{children:[e.jsx("span",{className:`av-status ${d.tone}`,children:d.word}),m&&o.statusDetail?e.jsx("span",{className:"ml-2 text-[13px] text-secondary",children:o.statusDetail}):null]})]},o.id)})})]})}),e.jsx(Ma,{items:i})]})})}const Sy=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],fo="Measured answers",Cy="Close answers",Ks={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},ky={"non-brand":"non-brand queries",branded:"branded queries",unknown:"unclassified queries"},js={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."},fa={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."},Ay="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.",wr="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 Ry(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function vd(t){return t.reason==="identity-ambiguous"?Yt.ambiguous:t.reason==="not-applicable"?"Not applicable":"Not measured"}function On({value:t}){if(t.rate===null)return e.jsx("span",{className:"text-sm text-secondary",children:vd(t)});const s=Pr(t);return e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:Fe(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 yo({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 Zr(t,s){if(!t||t.state==="unavailable")return null;const n=t[s];if(n.state==="unavailable")switch(n.reason){case Or["previous-unavailable"]:return{text:js.previousUnavailable,tone:"text-secondary"};case Or["current-unavailable"]:case Or["not-applicable"]:return null}const{direction:a,magnitude:r}=wc(n.delta);switch(a){case"up":return{text:js.up(r),tone:"text-positive"};case"down":return{text:js.down(r),tone:"text-negative"};case"none":return{text:js.none,tone:"text-secondary"}}}function bo(t,s){const n=Dt(t);return s!==null&&Fl(n)===Fl(Dt(s))?zp(n):oa(n)}function Py(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 Iy(t,s){if(!t)return null;if(t.state==="unavailable"){const n=t.previousRun?bo(t.previousRun.createdAt,s):null;switch(t.reason){case Cn["no-selected-run"]:return null;case Cn["no-previous-run"]:return js.noPreviousRun;case Cn["definition-changed"]:return js.definitionChanged(n);case Cn["model-changed"]:return js.modelChanged(n);case Cn["legacy-unknown"]:return js.legacyUnknown;case Cn["partial-run"]:return js.partialRun;case Cn["scoped-run"]:return js.scopedRun}}return js.comparedWith(bo(t.previousRun.createdAt,s))}function Ty(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 ei({label:t,help:s,value:n,unit:a,classNoun:r,change:l}){const i=e.jsx("span",{className:"sr-only",children:` · ${r}`}),o=Pr(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(_e,{text:s})]}),n.rate===null?e.jsxs("dd",{className:"text-lg text-secondary",children:[vd(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:Fe(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}`}),o?e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:o}):null]})]})}const Ly={otherQueries:"Other queries"},er={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 $y(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(" · ")||Ly.otherQueries}return a.sort((r,l)=>r.marketLabel.localeCompare(l.marketLabel)||r.query.localeCompare(l.query))}function vo({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(sg,{size:16,"aria-hidden":"true"}):e.jsx(ng,{size:16,"aria-hidden":"true"}),n?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(On,{value:t}),t.reason==="evidence-incomplete"?e.jsx(_e,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function jo({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 My({group:t,queryClass:s,advanced:n,targetLabels:a,marketHeading:r,onViewAnswers:l}){const i=t.rows[0],o=h=>JSON.stringify([...h.targetKeys].sort()),d=t.rows.every(h=>o(h)===o(i)),m=t.rows.every(h=>h.location===i.location),u=h=>h===null?"No location requested":`Requested search location: ${h}`;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(hc,{showLabel:!0,queryId:i.queryId,sourceSnapshotIds:t.rows.flatMap(h=>h.sourceSnapshotIds??[]),queryClass:s==="unknown"?null:s,location:m?i.location:void 0})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 text-sm font-normal text-secondary",children:[n&&d?e.jsx(jo,{targetKeys:i.targetKeys,labels:a}):null,m?e.jsx("span",{children:u(i.location)}):null]})]})}),t.rows.map(h=>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:dt(h.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:h.model??"Model not recorded"}),n&&!d?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(jo,{targetKeys:h.targetKeys,labels:a})}):null,m?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:u(h.location)}),e.jsx(xc,{showLabel:!0,showSubjects:n,queryId:h.queryId,sourceSnapshotIds:h.sourceSnapshotIds??[],queryClass:s==="unknown"?null:s,provider:h.provider,model:h.model,location:h.location})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(vo,{value:h.mentionCoverage,singleAnswer:h.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(vo,{value:h.citationCoverage,singleAnswer:h.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(L,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${h.query} · ${h.provider}`,onClick:g=>l(h,g.currentTarget),children:[h.answerCount===1?"View answer":"View answers",e.jsx(Wc,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([h.provider,h.model,h.location])))]})}const No=[{key:"mentioned",label:"Mentioned",color:ct[1],dashed:!1},{key:"cited",label:"Cited",color:Kn.positive,dashed:!0}],wo="var(--chart-tooltip-bg)";function qy({population:t}){const s=c.useId(),[n,a]=c.useState({mentioned:!0,cited:!0}),r=No.filter(g=>n[g.key]).map(g=>g.key),l=g=>a(x=>{const y={...x,[g]:!x[g]};return y.mentioned||y.cited?y:x});let i=0;const o=t.trend.map((g,x)=>(x>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,x)=>x),m=new Set(t.trend.slice(1).map(g=>g.continuity.state)),u=[...o.length===1?["First measurement. A trend appears after another comparable run."]:[],...m.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...m.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...m.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(g=>g.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[]];if(o.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const h=t.trend.some(g=>g.mentionCoverage.rate!==null||g.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[h?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"}),No.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?wo: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":`${Ks[t.queryClass]} mention and citation trend`,children:e.jsx(Us,{width:"100%",height:"100%",children:e.jsxs(yn,{data:o,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ia,{stroke:Ra,vertical:!1}),e.jsx(Vs,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Qt,tickLine:!1,axisLine:{stroke:xs},tickFormatter:g=>new Date(Number(g)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(Hs,{domain:[0,1],tick:Qt,tickLine:!1,axisLine:!1,width:48,tickFormatter:g=>Fe(Number(g))}),e.jsx(bn,{...hs,formatter:g=>typeof g=="number"?Fe(g):"Not measured",labelFormatter:g=>new Date(Number(g)).toLocaleDateString()}),d.map(g=>e.jsxs(c.Fragment,{children:[n.mentioned?e.jsx(Ys,{type:"linear",dataKey:`mentioned-${g}`,name:"Mentioned",stroke:ct[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:ct[1]}}):null,n.cited?e.jsx(Ys,{type:"linear",dataKey:`cited-${g}`,name:"Cited",stroke:Kn.positive,strokeWidth:2,strokeDasharray:"6 4",connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:wo,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:h?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${Ks[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(On,{value:g.mentionCoverage})}),e.jsx("td",{children:e.jsx(On,{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 rl(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,l=t.populations.find(m=>m.queryClass===r);if(l)return l;const i=Di(a,s)??Di(t,s),o=t.populations.find(m=>m.queryClass===i?.queryClass);if(o)return o;const d=["non-brand","branded","unknown"].map(m=>t.populations.find(u=>u.queryClass===m));return d.find(m=>m&&(m.summary.queryCount>0||m.trend.some(u=>u.queryCount>0)))??d.find(m=>m!==void 0)??t.populations[0]}const It={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"},Ey={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},Dy="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 Oy(t,s){return t&&s?It.dateRange(t.slice(0,4)===s.slice(0,4)?Qp(t):Tt(t),Tt(s)):t?It.dateFrom(Tt(t)):s?It.dateThrough(Tt(s)):null}function Fy(t,s){const n=[];t.provider&&n.push({key:"engine",label:It.engine(t.provider),patch:{measurementProvider:void 0}}),t.model&&n.push({key:"model",label:It.model(t.model),patch:{measurementModel:void 0}}),t.location&&n.push({key:"location",label:t.location==="none"?It.noLocation:It.location(t.location),patch:{measurementLocation:void 0}});const a=Oy(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?It.resultsFrom(oa(Dt(r.createdAt))):It.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function tr(t,s,n){return s===""||t.some(a=>a.value===s)?t:[...t,{value:s,label:n}]}function Ky({report:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}){const[l,i]=c.useState(!1),o=c.useRef(null),d=c.useId(),m=`${d}-filters`,{filterOptions:u,selection:h}=t,g=h.measurement,x=rl(t,s.queryKey,s.answer),y=s.queryClass==="all"?x.queryClass:s.queryClass,p=Fy(s,t),v=s.measurementScope==="property"?s.measurementScopeKey:void 0,j=v?r?.({id:v,label:ki(t.scopeOptions,s)?.label??v}):null,w=s.provider??"",I=s.model??"",k=s.location??"",f=s.measurementRunId??"",b=()=>o.current?.focus(),S=(P,C,U,O,J)=>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}-${C}`,className:"text-sm font-medium text-heading",children:P}),J?e.jsx(_e,{text:J}):null]}),e.jsx("select",{id:`${d}-${C}`,className:wr,value:U,onChange:V=>n({[C]:V.target.value||void 0,measurementQueryKey:void 0}),children:O.map(V=>e.jsx("option",{value:V.value,children:V.label},V.value))})]}),A=(P,C,U,O)=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("label",{htmlFor:`${d}-${C}`,className:"mb-1 block text-sm font-medium text-heading",children:P}),e.jsx("input",{id:`${d}-${C}`,type:"date",className:wr,value:U?.slice(0,10)??"",onChange:J=>n({[C]:J.target.value?`${J.target.value}${O}`: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:It.queryType}),e.jsxs("select",{"aria-label":It.queryType,className:Dy,value:y,onChange:P=>n({queryClass:P.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(re,{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:oa(Dt(g.completedAt))}):null]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[e.jsx(L,{ref:o,type:"button",variant:"outline",className:"min-h-11","aria-expanded":l,"aria-controls":m,onClick:()=>i(P=>!P),children:It.filters(p.length)}),p.map(P=>e.jsxs(L,{type:"button",variant:"outline",className:"visibility-filter-token min-h-11 rounded-md text-sm","aria-label":It.removeFilter(P.label),onClick:()=>{n(P.patch),b()},children:[e.jsx("span",{className:"min-w-0 truncate",children:P.label}),e.jsx(tg,{size:16,className:"shrink-0","aria-hidden":"true"})]},P.key)),j,a?e.jsx(L,{type:"button",variant:"outline",className:"min-h-11",onClick:a,children:It.manageQueries}):null]})]}),e.jsxs("div",{id:m,role:"group","aria-label":It.panel,hidden:!l,className:"border-b border-default",onKeyDown:P=>{P.key==="Escape"&&(P.target instanceof HTMLElement&&P.target.getAttribute("aria-expanded")==="true"||(i(!1),b()))},children:[e.jsxs("div",{className:"visibility-report-filters",children:[S("Answer engine","measurementProvider",w,tr([{value:"",label:"All engines"},...u.providers.map(P=>({value:P,label:P}))],w,w)),S("Requested search location","measurementLocation",k,tr([{value:"",label:"All requested locations"},...u.locations.flatMap(P=>P.kind==="exact"?[{value:P.value,label:P.value}]:P.kind==="none"?[{value:"none",label:It.noLocation}]:[])],k,k==="none"?It.noLocation:k)),S("AI model","measurementModel",I,tr([{value:"",label:"All models"},...Array.from(new Set(u.models.filter(P=>!s.provider||P.provider===s.provider).map(P=>P.model))).map(P=>({value:P,label:P}))],I,I),"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),A("Start date (UTC)","measurementFrom",s.from,"T00:00:00.000Z"),A("End date (UTC)","measurementTo",s.to,"T23:59:59.999Z"),S("Results from","measurementRunId",f,tr([{value:"",label:"Latest saved sweep"},...[...x.trend].reverse().map(P=>({value:P.runId,label:new Date(P.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(L,{type:"button",variant:"ghost",className:"min-h-11",disabled:p.length===0,onClick:()=>{n({...Ey}),b()},children:It.clearFilters})})]})]})}function Gy({report:t,isRefreshing:s=!1,onSelectionChange:n,onPage:a,onSearch:r,search:l="",queryKey:i,answerSelection:o,evidenceReport:d,isEvidenceLoading:m=!1,evidenceError:u,onRetryEvidence:h,onEvidencePage:g}){const x=c.useRef(null),y=c.useRef(void 0),p=c.useRef(null),v=rl(t,i,o,d),j=d??t,w=j.populations.filter(C=>[...C.queries.items,...C.evidence.items].some(U=>U.queryKey===i)),I=o?[o.queryClass]:(w.length?w:m?[]:[v]).map(C=>C.queryClass),k=i?JSON.stringify([o??i,I]):void 0;c.useEffect(()=>{if(!k){s||(y.current=void 0);return}if(y.current===k)return;const C=x.current?.querySelectorAll(`[aria-label="${fo}"]`);if(C?.length){for(const U of C){const O=U.closest("details[data-query-results]");O&&(O.open=!0)}C[0].focus({preventScroll:!0}),C[0].scrollIntoView?.({block:"start"}),y.current=k}},[k,s]);const{selection:f}=t,b=Ry(f.scope),S=new Map(t.scopeOptions.filter(C=>C.kind==="property").map(C=>[C.id,C.label])),A=C=>{const U=j.populations.find(O=>O.queryClass===C.queryClass)?.evidence;return{items:U?.items.filter(O=>O.queryKey===i&&(!o||O.provider===o.provider&&O.model===o.model&&O.location===o.location&&(o.runId===null||O.runId===o.runId)))??[],nextCursor:U?.nextCursor}},P=()=>{y.current=void 0;const C=p.current;C!==null&&C.row.queryKey===i&&(!o||C.row.provider===o.provider&&C.row.model===o.model&&C.row.location===o.location)&&C?.element.isConnected?C.element.focus():x.current?.querySelector(`details[data-query-results="${v.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})};return e.jsxs("section",{ref:x,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(L,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,[v].map(C=>{const U=$y(C.queries.items,f.scope.kind==="property"&&!f.market&&C.queryClass==="non-brand"?new Map(t.scopeOptions.filter(D=>D.kind==="market").map(D=>[D.id,D.label])):void 0),O=A(C),J=O.items[0]?.query??C.queries.items.find(D=>D.queryKey===i)?.query,V=f.mode==="advanced"&&f.scope.kind!=="property",H=ky[C.queryClass],te=Iy(C.comparison,Py(f,C));return e.jsxs("section",{"aria-label":Ks[C.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:Ks[C.queryClass]}),e.jsx(_e,{text:C.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":C.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:Ty(C.summary,te)}),e.jsx(_e,{text:js.explanation})]})]}),e.jsxs("dl",{className:"report-headline mt-3","data-columns":V?3:2,"aria-label":`${Ks[C.queryClass]} headline results`,children:[e.jsx(ei,{label:V?"Answers mentioning a property":"Mentioned answers",help:f.mode==="advanced"?fa.advancedMention:fa.simpleMention,value:C.summary.mentionCoverage,unit:"answers",classNoun:H,change:Zr(C.comparison,"mentionCoverage")}),e.jsx(ei,{label:V?"Answers citing a property":"Cited answers",help:f.mode==="advanced"?fa.advancedCitation:fa.simpleCitation,value:C.summary.citationCoverage,unit:"answers",classNoun:H,change:Zr(C.comparison,"citationCoverage")}),V?e.jsx(ei,{label:"Properties mentioned",help:fa.propertyReach,value:C.summary.propertyReach,unit:"properties",classNoun:H,change:Zr(C.comparison,"propertyReach")}):null]}),e.jsx(uc,{queryClass:f.queryClass}),e.jsx(qy,{population:C}),V&&(C.breakdown.groups.length>0||C.breakdown.properties.length>0)?e.jsx(_y,{population:C,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":`${Ks[C.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:[C.summary.outcomes.total," ",C.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(([D,$])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:C.summary.outcomes[D]}),e.jsx("span",{className:"text-sm text-secondary",children:$})]},D))}),e.jsx(_e,{text:Ay})]})]}):null,e.jsxs("details",{className:"visibility-disclosure","data-query-results":C.queryClass,"aria-label":`${Ks[C.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:[C.queries.total," ",C.queries.total===1?"result":"results"," · ",b]})]}),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 ${Ks[C.queryClass]}`,placeholder:"Search queries",className:`${wr} max-w-sm`,value:l,onChange:D=>r(D.target.value)}):null,e.jsx(_e,{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":`${Ks[C.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"})})]})}),U.map((D,$)=>e.jsx(My,{group:D,queryClass:C.queryClass,marketHeading:D.marketLabel!==U[$-1]?.marketLabel?D.marketLabel:void 0,advanced:f.mode==="advanced",targetLabels:S,onViewAnswers:(Q,B)=>{p.current={row:Q,element:B},n({measurementQueryKey:Q.queryKey,measurementAnswer:JSON.stringify({queryKey:Q.queryKey,queryClass:C.queryClass,provider:Q.provider,model:Q.model,location:Q.location,runId:f.run.id,revision:f.revision})})}},D.queryKey))]})}),C.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:[U.length," ",U.length===1?"query":"queries"," · ",C.queries.items.length," ",C.queries.items.length===1?"engine result":"engine results"," shown of ",C.queries.total," results"]}),C.queries.nextCursor&&a?e.jsx(L,{variant:"outline",onClick:()=>a(C.queries.nextCursor),children:"Next queries"}):null,i&&I.includes(C.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":m,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("h3",{className:"min-w-0 flex-1 text-base font-semibold text-heading [overflow-wrap:anywhere]",children:J??"Answers"}),e.jsx(L,{variant:"ghost",className:"min-h-11",onClick:P,children:Cy})]}),m?e.jsx("p",{role:"status",className:"py-4 text-sm text-secondary",children:"Loading saved answers…"}):u?e.jsxs("div",{role:"alert",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["Saved answers unavailable: ",u]}),h?e.jsx(L,{variant:"outline",onClick:h,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[O.items.map(D=>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:D.provider}),D.model?e.jsx("span",{className:"text-[13px] text-secondary",children:D.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:D.location===null?It.noLocation:It.location(D.location)}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(D.createdAt).toLocaleDateString()}),e.jsx(re,{tone:"neutral",children:D.mentioned===null?D.mentionUnavailableReason==="identity-ambiguous"?Yt.ambiguous:"Mention not checked":D.mentioned?"Mentioned":"Not mentioned"}),e.jsx(re,{tone:"neutral",children:D.cited===null?"Citation not checked":D.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(tl,{headingLevel:4,copyable:!!D.answerText?.trim(),children:D.answerText??"Answer text unavailable."})}),D.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:[Bp," (",D.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:D.sources.map($=>e.jsx("li",{className:"min-w-0",children:e.jsx(zi,{url:$})},$))})]}):null]},D.answerId)),A(C).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:A(C).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,A(C).nextCursor&&g?e.jsx(L,{variant:"outline",onClick:()=>g(A(C).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Ks[C.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:C.competitorAvailability.state==="unavailable"?"Not available":`${C.competitors.length} measured`})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[C.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):C.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:C.competitors.map(D=>e.jsxs("tr",{children:[e.jsx("td",{children:D.domain}),e.jsx("td",{children:e.jsx(On,{value:D.mentionCoverage})}),e.jsx("td",{children:e.jsx(On,{value:D.citationCoverage})})]},D.domain))})]})}),C.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:C.observedCompetitors.map(D=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:D.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[D.answerCount," ",D.answerCount===1?"answer":"answers"]})]},D.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},C.queryClass)})]})}function _y({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const l=new Map(n.filter(h=>h.kind==="group").map(h=>[h.id,h])),i=[...l.values()].some(h=>h.parentGroupIds?.length),o=t.breakdown.groups.filter(h=>{const g=l.get(h.id)?.parentGroupIds??[];return s.kind==="project"?g.length===0:s.kind==="group"&&i?g.includes(s.id):!0}),[d,m]=c.useState(()=>s.kind==="project"&&o.length>0?"groups":"properties"),u=Dn({rows:d==="groups"?o:t.breakdown.properties,getSearchText:h=>h.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(h=>e.jsx(L,{variant:d===h?"secondary":"ghost",onClick:()=>{m(h),u.setPage(1)},children:h==="groups"?"Groups":"Properties"},h))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:u.query,onChange:h=>u.setQuery(h.target.value),className:`${wr} 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(h=>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:h.id,measurementMarketKey:a}),children:h.label})}),e.jsx("td",{children:h.queryCount}),e.jsxs("td",{children:[e.jsx(On,{value:h.mentionCoverage}),e.jsx(yo,{value:h.mentionCoverage})]}),e.jsxs("td",{children:[e.jsx(On,{value:h.citationCoverage}),e.jsx(yo,{value:h.citationCoverage})]})]},h.id))})]})}),u.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",d," match this search."]}):null,e.jsx(Zs,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:d,onPageChange:u.setPage})]})}function jd(t,s,{enabled:n}){return Me({...mr({client:Y,path:{name:t},query:Si(s)}),enabled:n,staleTime:Nc,retry:!1,placeholderData:Ar})}function Nd(t,s){return s&&t.selection.mode==="simple"&&t.selection.measurement.state==="not-measured"}function By({projectName:t,selection:s,onSelectionChange:n,fallback:a,showUnmeasuredFallback:r=!1}){const[l,i]=c.useState(),[o,d]=c.useState(""),[m,u]=c.useState(),h=ws(),g=c.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]),x=Me({...mr({client:Y,path:{name:t},query:{...Si(s),cursor:l,search:o||void 0}}),staleTime:Nc,retry:!1,placeholderData:Ar}),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??x.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??x.data?.selection.revision??s.revision,limit:50},p=JSON.stringify(y),v=Me({...mr({client:Y,path:{name:t},query:{...y,cursor:m?.selection===p?m.cursor:void 0}}),enabled:!!s.queryKey&&!!x.data&&!x.isPlaceholderData,retry:!1});if(c.useEffect(()=>{if(s.queryClass!=="all"||!x.data||x.isPlaceholderData||x.isFetching||x.isError||x.data.selection.availability.state==="unsupported"||x.data.populations.length===0||s.queryKey&&!s.answer&&!Di(x.data,s.queryKey)&&!v.data)return;const j=rl(x.data,s.queryKey,s.answer,v.data);if(!l&&!o){const{queryKey:w}=mr({client:Y,path:{name:t},query:Si({...s,queryClass:j.queryClass})});h.setQueryData(w,{...x.data,selection:{...x.data.selection,queryClass:j.queryClass},populations:[j]},{updatedAt:x.dataUpdatedAt})}n({queryClass:j.queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}},{replace:!0})},[s.queryClass,s.queryKey,s.answer,x.data,x.dataUpdatedAt,x.isPlaceholderData,x.isFetching,x.isError,v.data,n,h,t,g,l,o]),x.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:a});if(x.data&&Nd(x.data,r))return e.jsx(e.Fragment,{children:a});if(x.error){const j=Cc(kc(x.error)),w=j?.reason===em["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:w?er.retiredMarket:j?er.retiredScope:fr(x.error)}),w?e.jsx(L,{variant:"outline",onClick:()=>{i(void 0),n({measurementMarketKey:void 0})},children:er.showAllMarkets}):j?e.jsx(L,{variant:"outline",onClick:()=>{i(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:er.showWholeSite}):e.jsx(L,{variant:"outline",onClick:()=>{i(void 0),x.refetch()},children:"Retry"})]})}return x.data?e.jsx("div",{"aria-busy":x.isFetching,children:e.jsx(Gy,{report:x.data,isRefreshing:x.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:v.data,isEvidenceLoading:v.isFetching||!!s.queryKey&&v.isPending,evidenceError:v.error?fr(v.error):void 0,onRetryEvidence:()=>{v.refetch()},onEvidencePage:v.isFetching?void 0:j=>u({selection:p,cursor:j}),search:o,onSearch:j=>{d(j),i(void 0)},onPage:x.isFetching?void 0:i,onSelectionChange:j=>{(!("measurementQueryKey"in j)||Object.keys(j).some(w=>w!=="measurementQueryKey"&&w!=="measurementAnswer"))&&i(void 0),u(void 0),n(j)}})}):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 Uy({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,fallback:l,showUnmeasuredFallback:i=!1}){const o=jd(t,s,{enabled:!0}),d=o.error?void 0:o.data,m=!o.isPlaceholderData&&d?.selection.availability.state==="available"?d.selection.run.id:null;return Zu(m,d?.selection.revision),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsx(Sc,{})}),d&&d.selection.availability.state==="available"&&!Nd(d,i)?e.jsx(Ky,{report:d,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}):null,e.jsx(By,{projectName:t,selection:s,onSelectionChange:n,fallback:l,showUnmeasuredFallback:i},`${t}:${JSON.stringify({...s,queryKey:void 0,answer:void 0})}`)]})}const Vy=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Hy=[{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."}],il=ct[2],Qy=ct[4],zy="var(--chart-tooltip-bg)",Wy={up:"text-positive-400",down:"text-negative-400",none:"text-muted"};function wd({direction:t,magnitude:s}){switch(t){case"up":return`up ${s} points`;case"down":return`down ${s} points`;case"none":return"no change"}}function Yy(t){return t.direction==="none"?"no change over the period":`${wd(t)} over the period`}function Jy(t){return t===qa||t===Ea||t===en}function Sd(t){return t===qa?"Cited":t===Ea?"Mentioned":t===en?"Mention share":dt(t)}function va(t,s){return t===qa?Kn.positive:t===Ea?ct[1]:t===en?il:Hp(La(t),s)}function ll(t){return t==="non-brand"?"non-brand answers":"all answers"}function Oi(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function ol(t,s){return t==="mentionShare"?`Mention share in ${ll(s)}`:Oi(t)}function Xy(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 Cd(t){return t==="cited"?"citationRate":"mentionRate"}function cl(t,s){return s==="cited"?t.cited:t.mentionedCount}function kd(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 Zy(t,s){if(s==="mentionShare"){const{projectMentionSnapshots:n,competitorMentionSnapshots:a}=t.mentionShare;return`${n} of ${n+a} tracked-brand mentions`}return`${cl(t,s)} of ${t.total} answers`}function eb(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Ad(t){const s=id(t);return s===null?[]:Object.entries(s).sort(([n],[a])=>La(n).localeCompare(La(a))).map(([n,a])=>`${dt(n)}: ${$a(a)}`)}function Rd(t,s){return new Date(t).toDateString()===new Date(s).toDateString()}function So(t){return`${t} ${t===1?"query":"queries"}`}function dl(t){const{added:s,removed:n}=t;return[...s.length>0?[`${So(s.length)} added`]:[],...n.length>0?[`${s.length>0?n.length:So(n.length)} removed`]:[]].join(", ")}function Pd(t,s){const n=Qs(t),a=Da(t),r=ud(t,s);if(!n||!a||!r)return null;const l=of(r.moves),i=Rd(n.start,n.end),o=d=>Rr(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:o(n.start)})," sweep and the ",e.jsx("strong",{children:o(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 tb(t,s,n){const a=Pd(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(c.Fragment,{children:[l>0?", ":"",dl(r)," ",e.jsx("strong",{children:Ta(Dt(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 Co(t){return t.replace(/ /g," ")}function Sr({state:t,from:s=!1}){return e.jsx("span",{className:s?"av-model av-model-from":"av-model",children:$a(t)})}function sb(t,s){return t.reroute?"Same preset, answered with a different model.":jr(t.provider,t.to)?t.served?`Preset picks its own model. Answered with ${$a(t.served.to)} (was ${$a(t.served.from)}).`:s&&s.length>0?`Preset picks its own model. Answered with ${s.join(", ")}.`:"Preset picks its own model.":null}function nb({buckets:t,queryChanges:s,modelRows:n,served:a,pointerNotices:r,truncated:l,incompleteHistory:i,queryName:o,sweepTimes:d}){const m=t.at(-1),u=f=>Ta(f),h=new Map;for(const[f,b]of r){const S=n.find(A=>A.provider===f&&!A.reroute&&A.to.status==="known"&&b.modelIds.includes(A.to.model));S&&h.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:dl(f)}),toHelp:null}))});const x=[...new Set(n.map(f=>f.provider))].sort((f,b)=>dt(f).localeCompare(dt(b)));for(const f of x){const S=a[f]?.latestServedModelIds??null,A=n.filter(P=>P.provider===f);g.push({key:f,label:dt(f),rows:A.map((P,C)=>{const U=h.get(f)===P?r.get(f).text:null,O=[sb(P,C===0?S:null),U].filter(Boolean).join(" ");return{key:`${f}-${P.at}-${P.reroute?"served":"set"}`,at:P.at,onOrBefore:P.onOrBefore,from:e.jsx(Sr,{state:P.from,from:!0}),to:e.jsx(Sr,{state:P.to}),toHelp:O||null}})})}const y=g.reduce((f,b)=>f+b.rows.length,0),p=[];for(const f of s)f.added.length>0&&p.push(e.jsxs(e.Fragment,{children:["Added ",e.jsx("strong",{children:u(f.at)}),": ",f.added.map(o).join(", ")]})),f.removed.length>0&&p.push(e.jsxs(e.Fragment,{children:["Removed ",e.jsx("strong",{children:u(f.at)}),": ",f.removed.map(o).join(", ")]}));const v=m?Da(m):null;for(const[f,b]of Object.entries(m?id(m)??{}:{}).sort(([S],[A])=>S.localeCompare(A)))b.status==="mixed"&&v&&p.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:v})," point mixes ",dt(f)," models: ",Bg(b)]}));const j=new Map;for(const f of n.filter(b=>b.onOrBefore)){const b=f.anchorAt?u(f.anchorAt):"";j.set(b,[...new Set([...j.get(b)??[],dt(f.provider)])])}for(const[f,b]of j)p.push(f?e.jsxs(e.Fragment,{children:["Changed before this date range, after the ",e.jsx("strong",{children:f})," sweep: ",ka(b)]}):`Changed before this date range: ${ka(b)}`);for(const f of l)p.push(`${dt(f.provider)}: most recent ${f.shown} of ${f.total} changes`);for(const f of i)p.push(`${dt(f)}: may be missing older changes`);for(const[f,b]of r)h.has(f)||p.push(e.jsxs("span",{className:"inline-flex items-center gap-1",children:[dt(f),": no model updates on record",e.jsx(_e,{text:b.text})]}));if(y===0&&p.length===0)return null;for(const[f,b]of Object.entries(a).sort(([S],[A])=>dt(S).localeCompare(dt(A)))){const S=b.latestServedModelIds??[],A=S.length>0?S.join(", "):$a(b.latestObservation.state);p.push(e.jsxs(e.Fragment,{children:[dt(f)," last answered with ",e.jsx("strong",{children:A})," on ",e.jsx("strong",{children:u(Dt(b.latestObservation.observedAt))})]}))}const w=g.flatMap(f=>f.rows.map(b=>b.at));let I="First sweep on the new model or query set.";if(w.length>0){const f=u(w.reduce((U,O)=>Date.parse(O)>Date.parse(U)?O:U)),b=[...new Set(w.filter(U=>u(U)===f))].sort(),S=b.map(U=>Rr(U,U));I+=` ${f} = the ${ka(S)} ${S.length===1?"sweep":"sweeps"}.`;const A=n.flatMap(U=>U.anchorAt?[U.anchorAt]:[]),P=A.length>0?A.reduce((U,O)=>Date.parse(O)>Date.parse(U)?O:U):null,C=nf(b[0],d,t,P);C&&(I+=` Sweep before: ${u(C)}.`)}const k=sf({latest:m,queryChanges:s,modelRows:n})??"No changes in this date range";return e.jsxs("details",{className:"av-wc",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"av-card-title",children:"What changed"}),e.jsx("span",{className:"av-wc-summary av-wc-when-closed",children:k}),e.jsxs("span",{className:"av-wc-toggle",children:[e.jsxs("span",{className:"av-wc-when-closed",children:[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(_e,{text:I})]})}),e.jsx("th",{scope:"col",children:"From"}),e.jsx("th",{scope:"col",children:"To"})]})}),g.map(f=>e.jsx("tbody",{children:f.rows.map((b,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:b.onOrBefore?`on or before ${Co(u(b.at))}`:Co(u(b.at))}),b.from===null?null:e.jsx("td",{children:b.from}),e.jsx("td",{colSpan:b.from===null?2:void 0,children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[b.to,b.toHelp?e.jsx(_e,{text:b.toHelp}):null]})})]},b.key))},f.key))]})}),e.jsx(Ma,{items:p})]}):e.jsx("ul",{className:"av-details-list",children:p.map((f,b)=>e.jsx("li",{children:f},b))})})]})}function ab({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:dt(s)}),e.jsxs("span",{className:"text-secondary",children:["selected ",e.jsx(Sr,{state:n.configured})," · answered ",e.jsx(Sr,{state:n.served})]}),e.jsx("span",{className:"av-status text-caution-400",children:"substituted"})]},s))})}function rb({active:t,label:s,payload:n,metric:a,mode:r,buckets:l,basketChanges:i}){if(!t)return null;const o=eb(l,s);if(!o)return null;const d=Qs(o),m=d!==null&&Rd(d.start,d.end)?d.start:null,u=cd(o,i),h=Ad(o),g=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-tooltip-label",children:nl(o)}),u.map(p=>e.jsxs("p",{className:"trend-tooltip-detail trend-tooltip-note",children:[dl(p)," ",Rr(p.at,m)]},p.at))]}),x=h.length>0&&e.jsx("p",{className:"trend-tooltip-detail trend-tooltip-models",children:h.map((p,v)=>e.jsxs(c.Fragment,{children:[v>0?"; ":"",e.jsx("span",{className:"whitespace-nowrap",children:p})]},v))});if(a==="mentionShare"){const p=o.mentionShare.projectMentionSnapshots,v=o.mentionShare.competitorMentionSnapshots,j=p+v;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:il},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:ol("mentionShare",o.mentionShare.scope)}),e.jsx("span",{className:"trend-tooltip-value",children:Fe(o.mentionShare.rate)})]}),e.jsx("p",{className:"trend-tooltip-detail",children:j>0?`You ${p} of ${j} tracked-brand mentions. Competitors ${v}.`:"No tracked-brand mentions in this point"}),x]})}const y=r==="byProvider"?(n??[]).filter(p=>p.dataKey!==void 0):[{dataKey:a==="cited"?qa:Ea}];return e.jsxs("div",{className:"trend-tooltip",children:[g,y.map((p,v)=>{const j=String(p.dataKey??p.name??""),w=r==="byProvider"?kd(o,j,a):null,I=w?.count??cl(o,a),k=w?.total??o.total,f=w?w.rate:o[Cd(a)],b=p.color??va(j,v);return e.jsx("div",{className:"trend-tooltip-block",children:e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:b},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Sd(j)}),e.jsx("span",{className:"trend-tooltip-value",children:Fe(f)}),e.jsxs("span",{className:"trend-tooltip-count",children:[I," of ",k]})]})},`${j}-${v}`)}),x]})}function ib({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:[ol(s,r)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Point"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(l=>{let i;if(s==="mentionShare"){const d=l.mentionShare.projectMentionSnapshots,m=l.mentionShare.competitorMentionSnapshots,u=d+m,h=ll(l.mentionShare.scope);i=u>0?`${Fe(l.mentionShare.rate)} mention share in ${h}, ${d} of ${u} tracked-brand mentions were you`:`mention share undefined in ${h}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(d=>{const m=kd(l,d,s);return m?`${dt(d)} ${Fe(m.rate)} ${Oi(s).toLowerCase()}, ${m.count} of ${m.total} answers`:`${dt(d)} no data`}).join("; "):i=`${Fe(l[Cd(s)])} ${Oi(s).toLowerCase()}, ${cl(l,s)} of ${l.total} answers`;const o=Ad(l);return o.length>0&&(i+=`; models: ${o.join("; ")}`),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:nl(l)}),e.jsx("td",{children:i})]},l.startDate)})})]})})}function lb({projectName:t,competitorDomains:s=[],analyticsRevision:n="none",queryTexts:a=[],classifyQuery:r,sweepTimes:l=[]}){const[i,o]=c.useState("all"),[d,m]=c.useState("mentioned"),[u,h]=c.useState("byProvider"),g=c.useId(),x=c.useMemo(()=>Eg(s),[s]),y=Me({queryKey:["analytics-metrics",t,i,x,n],queryFn:()=>Xu(t,i),staleTime:Yi}),p=y.data??null,v=y.error,j=d==="mentionShare"?"overall":u,w=c.useMemo(()=>p?zg(p,d,j):null,[p,d,j]),I=p?Fg(p):null,k=c.useMemo(()=>Vg(I??{}),[I]),f=c.useMemo(()=>Hg(I??{}),[I]),b=c.useMemo(()=>Object.entries(I??{}).filter(([,Ce])=>Ce.anchorUnavailable).map(([Ce])=>Ce).sort(),[I]),S=c.useMemo(()=>p?Kg(p):{},[p]),A=c.useMemo(()=>p?Xg(Gg(p)):[],[p]),P=c.useMemo(()=>p?od(p):[],[p]),C=c.useMemo(()=>p?Zg(p):[],[p]),U=c.useMemo(()=>tf(I??{},S),[I,S]),O=c.useMemo(()=>p?_g(p):{},[p]),J=c.useMemo(()=>Rl(O,{engineName:dt}),[O]),V=c.useMemo(()=>{const Ce=new Map;for(const[Ie,Be]of Object.entries(O).sort(([qe],[pe])=>qe.localeCompare(pe))){const qe=Rl({[Ie]:Be},{engineName:dt});qe?.kind==="no-known-change"&&Ce.set(Ie,{text:`${qe.text} ${qe.detail}`,modelIds:Be.modelIds??[]})}return Ce},[O]),H=c.useMemo(()=>{const Ce=new Map(a.map(Ie=>[na(Ie),Ie]));return Ie=>Ce.get(na(Ie))??Ie},[a]),te=d!=="mentionShare"&&j==="byProvider",D=p?.buckets??[],$=D[D.length-1]?.mentionShare.scope??p?.mentionShareScope??"pooled",Q=ol(d,$),B=te?os.textDim:d==="cited"?Kn.positive:d==="mentionShare"?il:ct[1],_=c.useMemo(()=>{const Ce=new Map(D.map(Ie=>[Ie.startDate,qg(Ie)]));return Ie=>Ce.get(String(Ie))??""},[D]),M=d==="mentionShare"?D.filter(Ce=>typeof Ce.mentionShare.rate=="number"&&Number.isFinite(Ce.mentionShare.rate)):D,W=M.at(-1),ie=(p?Wg(p,d):[]).at(-1)??null,be=p?Yg(p,d):null,ke=lf(M,P),X=Hl(ke,d,$,r),le=ie!==null&&be!==null?wc(be.delta):null,je=le!==null&&!X,ee=s.length,oe=[];if(W&&be!==null&&ke&&!X&&oe.push(tb(ke,W,P)),W&&M.length===1){const Ce=Pd(W,P);Ce&&!Hl(ud(W,P),d,$,r)&&oe.push(Ce)}if(le!==null&&M[0]){const Ce=Da(M[0]);Ce&&oe.push(e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:Ce})," point"]}))}te&&ie!==null&&oe.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:Fe(ie)})," pools all answers; not an average of engines"]}));const G=[...new Set([...k.buckets.map(Ce=>Ce.bucketStartDate),...D.filter(Ce=>cd(Ce,P).length>0).map(Ce=>Ce.startDate)])].sort(),ue=ie!==null&&W&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:B},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:Q}),e.jsx("span",{className:"visibility-trend-current-value",children:Fe(ie)}),le!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${je?"text-muted":Wy[le.direction]}`,children:[wd(le),je?" (not the same queries)":""]}),e.jsxs("span",{className:"visibility-trend-current-detail",children:["· ",Zy(W,d)]})]}),se=e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Ca,{options:Hy,value:d,onChange:m,label:"Metric",className:"visibility-trend-metric-control"}),d!=="mentionShare"&&e.jsx(Ca,{options:Vy,value:u,onChange:h,label:"Series"}),e.jsx(Ca,{options:Sy,value:i,onChange:o,label:"Time window",className:"sm:ml-auto"})]});let Se;if(v)Se=e.jsx("p",{className:"text-sm text-negative-400",children:fr(v)});else if(y.isLoading&&!p)Se=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(d==="mentionShare"&&ee===0)Se=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!p||!w)Se=null;else{const{rows:Ce,series:Ie,hasData:Be}=w;if(!Be)Se=e.jsx("p",{className:"text-sm text-secondary",children:d==="mentionShare"?`No answer-text brand mentions for you or tracked competitors in ${ll($)} in this window yet.`:Ns()?aa:"Run a sweep to start tracking citations and mentions over time."});else if(te&&Ie.length===0)Se=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=`${Q} rate across ${Ce.length} ${Ce.length===1?"sweep":"sweeps"}. Latest ${Fe(ie)}${le!==null?`, ${Yy(le)}${je?", not the same queries":""}`:""}.`;Se=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:qe}),e.jsx(ib,{buckets:D,metric:d,mode:j,series:Ie,mentionShareScope:$}),te&&Ie.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:Ie.map((pe,F)=>{const Ke=Jg(p,pe,d);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:va(pe,F)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:Sd(pe)}),Ke!==null&&e.jsx("span",{className:"trend-legend-value",children:Fe(Ke)})]},pe)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${Q} trend chart over ${Ce.length} ${Ce.length===1?"point":"points"}`,children:e.jsx(Us,{width:"100%",height:"100%",children:e.jsxs(yn,{data:Ce,margin:{top:8,right:20,bottom:0,left:0},children:[e.jsx(Ia,{stroke:Ra,vertical:!1}),e.jsx(Vs,{dataKey:"date",tick:Qt,tickLine:!1,axisLine:{stroke:xs},tickFormatter:_,minTickGap:24}),e.jsx(Hs,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:pe=>Fe(pe,Lt.percent),tick:Qt,tickLine:!1,axisLine:!1,width:40}),e.jsx(bn,{cursor:{stroke:xs,strokeWidth:1},content:e.jsx(rb,{metric:d,mode:j,buckets:D,basketChanges:P})}),G.map(pe=>e.jsx(ug,{x:pe,stroke:Qy,strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`setup-change-${pe}`)),Ie.map((pe,F)=>e.jsx(Ys,{type:"monotone",dataKey:pe,name:pe,stroke:va(pe,F),strokeDasharray:pe===en?"5 4":void 0,strokeWidth:Jy(pe)?2.5:2,dot:pe===en?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:va(pe,F),strokeWidth:1.5}:{r:2.5,fill:va(pe,F),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:zy},connectNulls:pe!==en,isAnimationActive:!1},pe))]})})}),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(_e,{text:Xy($)})]}),W?e.jsx("p",{className:"av-card-meta",children:nl(W)}):null]}),e.jsxs("div",{className:"visibility-trend-body",children:[J?.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:J.text}),ue,se,Se]}),e.jsx(Ma,{items:oe})]}),p&&!v?e.jsxs(e.Fragment,{children:[e.jsx(nb,{buckets:D,queryChanges:C,modelRows:U,served:S,pointerNotices:V,truncated:f,incompleteHistory:b,queryName:H,sweepTimes:l}),e.jsx(ab,{substitutions:A})]}):null]})}const ko=new Set([Sa.queued,Sa.running]),Xt={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 Ao({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:l,scopeError:i,onRetryScope:o,templates:d=[],viewerResearchConfig:m=null}){const u=ws(),{account:h,canWrite:g}=Fn(),x=h?.role==="viewer"&&m!==null,y=!g,p=Xs(),[v,j]=c.useState(""),[w,I]=c.useState(""),[k,f]=c.useState(null),[b,S]=c.useState([]),A=c.useRef(null),P=c.useRef(!1),[C,U]=c.useState(0),O=Me({...tm({client:Y,path:{name:t}}),staleTime:6e4}),J=Me({...sm({client:Y}),enabled:!y&&!p,staleTime:6e4}),V={client:Y,path:{name:t},query:{limit:20}},H=dc({...nm(V),initialData:void 0,initialPageParam:V,getNextPageParam:G=>G.nextCursor?{path:V.path,query:{...V.query,cursor:G.nextCursor}}:void 0,refetchInterval:G=>G.state.data?.pages.some(ue=>ue.runs.some(se=>ko.has(se.status)))?3e3:!1}),te=H.isError&&!H.isFetchNextPageError,D=H.data?.pages.at(-1),$=te?[]:[...new Map((H.data?.pages.flatMap(G=>G.runs)??[]).map(G=>[G.id,G])).values()],Q=D?.access?.canRun??(g||x),B=D?.access?D.access.dailyRunLimit:x?m.viewerDailyRunLimit:null;c.useEffect(()=>{!k&&$[0]&&f($[0].id)},[$,k]);const _=$.find(G=>G.id===k)??null,M=Me({...am({client:Y,path:{name:t,runId:k??""}}),enabled:!te&&!!k,refetchInterval:_&&ko.has(_.status)?3e3:!1}),W=te||M.isError?null:M.data??null,ne=O.data?.locations??[],ie=c.useMemo(()=>{if(y)return(D?.providers??[]).map(ue=>({...ue,catalog:ue}));const G=new Map((J.data?.providerCatalog??[]).map(ue=>[ue.name,ue]));return(J.data?.providers??[]).filter(ue=>ue.configured&&G.get(ue.name)?.mode==="api").map(ue=>({...ue,catalog:{...G.get(ue.name),defaultModel:ue.model||G.get(ue.name).defaultModel}}))},[y,D?.providers,J.data]),be=!(y?H.isPending:J.isPending)&&ie.length===0,ke=ie.find(G=>G.name===v)??null;c.useEffect(()=>{if(!v&&O.data&&!O.isError&&!J.isError){const G=O.data.providers.find(ue=>ie.some(se=>se.name===ue));j(G??ie[0]?.name??"")}},[v,ie,O.data,O.isError,J.isError]);const X=ke?.catalog.modelConfigurable??!1,le=y?ke?.catalog.defaultModel:(ke?O.data?.providerModels[ke.name]:"")||ke?.catalog.defaultModel,je=(X?w.trim():"")||le,ee=ke?[...new Map([{id:ke.catalog.defaultModel,displayName:ke.catalog.defaultModel},...w.trim()?[{id:w.trim(),displayName:w.trim()}]:[],...ke.catalog.knownModels].map(G=>[G.id,G])).values()]:[],oe=Ht({...rm(),onSuccess:async G=>{A.current=null,U(ue=>ue+1),S(G.runs),f(G.runs[0]?.id??null),await fb(u),Oe({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(ue=>ue.id).join(":")}`,dedupeMode:"replace"})},onError:G=>{Oe({title:"Could not start research",detail:G instanceof Error?G.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{P.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[p?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(ob,{projectName:t,canWrite:g,researchAllowed:Q&&!te,limitedAccess:y,isEmbed:ce(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:l,scopeError:i,onRetryScope:o,templates:d,locations:ne,defaultLocation:O.data?.defaultLocation??null,providerOptions:ie,provider:v,onProviderChange:G=>{j(G),I("")},resolvedModel:je,visibilityModel:le,configurableModel:X,model:w,onModelChange:I,modelOptions:ee,settingsReady:y?!H.isPending&&!te:!J.isPending&&!J.isError&&!J.isFetching,projectReady:!O.isPending&&!O.isError&&!O.isFetching,isPending:oe.isPending,errorMessage:oe.isError?"The request could not be confirmed.":void 0,onSubmit:(G,ue)=>{!Q||te||ce()||P.current||(A.current?.fingerprint!==ue&&(A.current={fingerprint:ue,key:crypto.randomUUID()}),P.current=!0,oe.mutate({client:Y,path:{name:t},body:{...G,idempotencyKey:A.current.key}}))}},`${t}:${C}`),B!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",B," destination runs per project per day."]}),!y&&J.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(L,{variant:"outline",onClick:()=>{J.refetch()},children:"Retry providers"})]}):null,O.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(L,{variant:"outline",onClick:()=>{O.refetch()},children:"Retry locations"})]}):null,!(y?te:J.isError)&&be&&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."}),b.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",b.map((G,ue)=>e.jsxs("span",{children:[ue>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:Xt.historyTitle})}),H.isFetching&&e.jsx(re,{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(L,{variant:"outline",onClick:()=>{H.refetch()},children:"Retry history"})]}):H.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):$.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:Xt.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:$.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:xb(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(re,{tone:Id(G.status),children:G.status})})]},G.id))})]})}),H.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:Xt.historyMoreError}),H.hasNextPage&&e.jsx(L,{className:"mt-3",variant:"outline",disabled:H.isFetching,onClick:()=>{H.fetchNextPage()},children:H.isFetchingNextPage?Xt.historyLoading:Xt.historyMore})]})]}),!te&&M.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(L,{variant:"outline",onClick:()=>{M.refetch()},children:"Retry results"})]}):te?null:e.jsx(mb,{detail:W,isLoading:M.isFetching,onReviewForTracking:p?void 0:s})]})}const Gs="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",Zn="__none__";function ob(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:l}=t,i=ws(),[o,d]=c.useState("once"),[m,u]=c.useState(""),[h,g]=c.useState(""),[x,y]=c.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[p,v]=c.useState(null),[j,w]=c.useState([]),[I,k]=c.useState(""),[f,b]=c.useState({}),[S,A]=c.useState(null),[P,C]=c.useState([]),[U,O]=c.useState(null),[J,V]=c.useState(!1),[H,te]=c.useState(!1),[D,$]=c.useState(""),[Q,B]=c.useState(""),_=c.useRef(null),M=c.useRef(!1),W=c.useRef(null),ne=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";c.useEffect(()=>{y(ne),A(null)},[ne]);const ie=t.scopeOptions.filter(R=>R.kind==="market"||R.kind==="property"),be=o==="markets"?"market":"property",ke=ie.filter(R=>R.kind===be),X=R=>({kind:R.kind,key:R.id,label:R.label,planRevision:l??t.initialScope?.planRevision??0}),le=R=>R===Zn?null:n.find(Ae=>Ae.label===R),je=p??t.defaultLocation??Zn,ee=ie.find(R=>`${R.kind}:${R.id}`===x),oe=ee?X(ee):null,G=o==="once"?[{scope:oe,location:le(je)}]:o==="locations"?j.map(R=>({scope:null,location:le(R)})):j.map(R=>ke.find(Ae=>`${Ae.kind}:${Ae.id}`===R)).map(R=>R?{scope:X(R),location:le(f[`${R.kind}:${R.id}`]??Zn)}:null),ue=[...new Map([...P,...t.templates].map(R=>[R.id,R])).values()],se=S?ue.find(R=>R.id===S.id):null,Se=S!==null&&se?.version!==S.version,Ce=o==="once"?m:h,Ie=Ce.split(/\r?\n/).filter(R=>R.trim()),Be=Pl(Ie),qe=[...new Set([...h.matchAll(/\{([^{}]+)\}/g)].map(R=>R[1]))],pe=/[{}]/.test(h.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),F=[];Ie.length||F.push(o==="once"?"Enter at least one query.":"Enter at least one query pattern."),Ie.some(R=>R.length>4e3)&&F.push("Keep each query under 4,001 characters."),o!=="once"&&pe&&F.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),G.length||F.push(o==="locations"?"Select at least one location.":"Select at least one destination."),G.some(R=>!R||R.location===void 0)&&F.push("A selected destination or location is no longer available. Update your selection.");const Ke=o==="once"&&x!=="project"||o==="markets"||o==="properties";Ke&&(t.scopePending||t.scopeError||!l||G.some(R=>!R?.scope))&&F.push("Load the current published markets and properties before running scoped research.");const T=(o==="once"?Be.length:Ie.length)*G.length;if(G.length>Qa&&F.push(`Select at most ${Qa} destinations.`),T>Kr&&F.push(`${T} queries selected. Reduce the selection to ${Kr} or fewer.`),Se&&F.push("This saved pattern changed. Select its current version from Saved patterns."),o!=="once"&&!pe){for(const R of G)if(!(!R||R.location===void 0))try{Fr(S??{pattern:h,variables:qe},R.scope,R.location)}catch{F.push(`Choose a location for {location}, or use only variables available for ${o==="markets"?"markets":o==="properties"?"properties":"locations"}.`);break}}const ye=JSON.stringify({mode:o,source:Ce,contexts:G,provider:a,resolvedModel:r,template:S,...Ke?{planRevision:l}:{}}),Ve=U!==null&&U.signature!==ye,Ye=o==="once"?Be.map((R,Ae)=>({id:String(Ae),query:R,scope:oe,location:G[0]?.location??null})):U?.rows??[],et=ub(Ye),xe=[];o!=="once"&&U&&(Ve&&xe.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),Ye.some(R=>!R.query.trim()||R.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(R.query))&&xe.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),Ye.some(R=>R.location&&!n.some(Ae=>JSON.stringify(Ae)===JSON.stringify(R.location)))&&xe.push("A preview location changed. Regenerate the preview."),et.some(R=>Pl(R.queries).length!==R.queries.length)&&xe.push("Remove duplicate queries within each destination and location."),et.length>Qa&&xe.push(`The preview exceeds ${Qa} runs.`));const ft=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!F.length&&!xe.length&&(o==="once"||U!==null),ze=()=>({runs:et.map(R=>({queries:R.queries,provider:a,model:r,location:R.location,...R.scope?{scope:{kind:R.scope.kind,key:R.scope.key,expectedPlanRevision:R.scope.planRevision}}:{},...R.template?{template:R.template}:{}}))}),nt=()=>{if(V(!0),F.length)return;const R=G.flatMap((Ae,me)=>Ie.map((Je,Ft)=>({id:`${me}:${Ft}`,scope:Ae.scope,location:Ae.location,...S?{template:{templateId:S.id,templateVersion:S.version,bindingLocation:Ae.location}}:{},query:Fr({pattern:Je,variables:[...new Set([...Je.matchAll(/\{([^{}]+)\}/g)].map(Kt=>Kt[1]))]},Ae.scope,Ae.location).output})));O({signature:ye,rows:R})},as=R=>{d(R),w([]),A(null),k(""),V(!1)},xt=R=>{if(B(""),o==="once")try{u(Fr(R,oe,le(je)).output)}catch{B("Select a matching market, property, or location before using this pattern.");return}else g(R.pattern);A(R)},at=R=>{const Ae=W.current,me=Ae?.selectionStart??h.length,Je=Ae?.selectionEnd??me;g(`${h.slice(0,me)}{${R}}${h.slice(Je)}`),A(null),requestAnimationFrame(()=>{Ae?.focus(),Ae?.setSelectionRange(me+R.length+2,me+R.length+2)})},yt=Ht({...lm(),onSuccess:async R=>{const Ae={id:R.id,version:R.updatedAt,label:R.name,pattern:R.pattern,variables:R.variables};C(me=>[...me.filter(Je=>Je.id!==R.id),Ae]),A(Ae),te(!1),$(""),B(""),_.current=null,await i.invalidateQueries({queryKey:im({client:Y,path:{name:s}})}),Oe({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>B("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{M.current=!1}}),At=()=>{if(!t.canWrite||t.isEmbed||M.current)return;const R=o==="once"?m:h,Ae=o==="once"?[]:qe;if(!D.trim()||!R.trim()||R.length>4e3||o!=="once"&&pe){B("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const me={name:D.trim(),pattern:R,variables:Ae},Je=JSON.stringify(me);_.current?.fingerprint!==Je&&(_.current={fingerprint:Je,id:crypto.randomUUID()}),M.current=!0,yt.mutate({client:Y,path:{name:s,templateId:_.current.id},body:me})},$t=[...new Set([...J||Ce.trim()?F:[],...xe])],He=ue.filter(R=>{const Ae=o==="once"?Il(oe,le(je)):Il(o==="markets"?{kind:"market",label:"Market"}:o==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return R.variables.every(me=>Ae[me]!==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||yt.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:Gs,value:o,disabled:t.isPending,onChange:R=>as(R.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!ie.some(R=>R.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!ie.some(R=>R.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),o==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(ie.length>0||x!=="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:Gs,value:x,onChange:R=>{y(R.target.value),A(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),x!=="project"&&!ee&&e.jsx("option",{value:x,disabled:!0,children:"Selected destination unavailable"}),ie.map(R=>e.jsxs("option",{value:`${R.kind}:${R.id}`,children:[R.label," (",R.kind,")"]},`${R.kind}:${R.id}`))]})]}),e.jsx(Fi,{label:"Answer engine location",value:je,locations:n,onChange:R=>{v(R),A(null)}})]}),o!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:o==="locations"?"Select locations":`Select ${o}`}),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:Gs,placeholder:`Search ${o}`,value:I,onChange:R=>k(R.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(o==="locations"?n.map(R=>({key:R.label,label:R.label})):ke.map(R=>({key:`${R.kind}:${R.id}`,label:R.label}))).filter(R=>R.label.toLocaleLowerCase().includes(I.toLocaleLowerCase())).map(R=>{const Ae=j.includes(R.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:Ae,onChange:()=>w(me=>Ae?me.filter(Je=>Je!==R.key):[...me,R.key])}),R.label]}),Ae&&o!=="locations"&&e.jsx(Fi,{label:`Answer engine location for ${R.label}`,value:f[R.key]??Zn,locations:n,onChange:me=>b(Je=>({...Je,[R.key]:me}))})]},R.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[j.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(L,{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:o==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:o==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${o==="markets"?"market":o==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:W,className:`${Gs} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:Ce,placeholder:o==="once"?Xt.queryPlaceholder:o==="markets"?"Best apartments in {market}":o==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:R=>{o==="once"?u(R.target.value):(g(R.target.value),A(null))}}),o!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(L,{size:"sm",variant:"outline",onClick:()=>at(o==="markets"?"market":o==="properties"?"property":"location"),children:["Insert ",o==="markets"?"market":o==="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:[T," / ",Kr," queries",o==="once"?"":` across ${G.length} destinations`]})]}),o!=="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."}),He.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:He.map(R=>e.jsx(L,{size:"sm",variant:"outline",onClick:()=>xt(R),children:R.label},R.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(L,{size:"sm",variant:"outline",onClick:()=>te(!H),children:H?"Cancel save":"Save as a pattern"}),H&&e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("label",{className:"min-w-48 flex-1 text-sm text-heading",children:["Pattern name",e.jsx("input",{className:Gs,value:D,maxLength:120,onChange:R=>$(R.target.value)})]}),e.jsx(L,{size:"sm",disabled:yt.isPending||!D.trim()||!Ce.trim(),onClick:At,children:yt.isPending?"Saving…":"Save pattern"})]})]}),Q&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:Q})]})]}),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:Gs,value:a,onChange:R=>t.onProviderChange(R.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose an answer engine"}),t.providerOptions.map(R=>e.jsx("option",{value:R.name,children:R.displayName??R.name},R.name))]})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Model",t.limitedAccess?e.jsxs("select",{className:Gs,value:t.model,disabled:!a||!t.configurableModel,onChange:R=>t.onModelChange(R.target.value),children:[e.jsxs("option",{value:"",children:["Use AI Visibility model · ",t.visibilityModel]}),t.modelOptions.map(R=>e.jsx("option",{value:R.id,children:R.displayName},R.id))]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{"aria-label":"Model",className:Gs,list:"research-known-models",placeholder:r??"Choose an answer engine",value:t.model,disabled:!a||!t.configurableModel,onChange:R=>t.onModelChange(R.target.value)}),e.jsx("datalist",{id:"research-known-models",children:t.modelOptions.map(R=>e.jsx("option",{value:R.id,children:R.displayName},R.id))})]})]})]}),$t.length>0&&e.jsx(db,{errors:$t}),o!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(L,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:nt,children:[e.jsx(Pa,{size:14}),U?Xt.refreshPreview:"Preview queries"]}),U&&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:[Ye.length," query executions in ",et.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(cb,{rows:Ye,locations:n,onChange:(R,Ae)=>O(me=>me&&{...me,rows:me.rows.map(Je=>Je.id===R?{...Je,...Ae}:Je)})})]})]}),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(L,{size:"sm",disabled:!ft,onClick:()=>{if(ft){const R=ze();t.onSubmit(R,JSON.stringify({projectName:s,...R}))}},children:[e.jsx(br,{size:14}),t.isPending?"Starting…":Xt.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[o==="once"?`${Be.length} queries`:`${Ye.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function Fi({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:Gs,value:s,onChange:r=>a(r.target.value),children:[e.jsx("option",{value:Zn,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function cb({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:`${Gs} 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(Fi,{label:`Location for query ${r+1}`,value:a.location?.label??Zn,locations:s,onChange:l=>n(a.id,{location:s.find(i=>i.label===l)??null})})]},a.id))})}function db({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 ub(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 mb({detail:t,isLoading:s,onReviewForTracking:n}){const[a,r]=c.useState(null);c.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":Xt.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 ${pb(t.id)}`:Xt.resultsEmpty})]}),t&&e.jsx(re,{tone:Id(t.status),children:t.status})]}),t&&e.jsxs("div",{className:"mt-3 space-y-3 text-sm text-secondary",children:[e.jsxs("dl",{className:"flex flex-wrap gap-x-6 gap-y-2 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Answer engine"}),e.jsx("dd",{children:t.provider})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Requested model"}),e.jsx("dd",{className:"font-mono",children:t.requestedModel??t.resolvedModel})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Location"}),e.jsx("dd",{children:t.location?.label??"No location"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Destination"}),e.jsx("dd",{children:t.scope?.label??"Whole site"})]})]}),t.template&&e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:Xt.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,o])=>`${i}: ${o}`).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:Xt.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:Xt.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(re,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?Xt.brandedQuery:i.queryClass==="non-brand"?Xt.discoveryQuery:Xt.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(re,{tone:gb(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(re,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===Mn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===Mn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(re,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===Mn.failed?"negative":"caution",children:i.citationState===null?i.status===Mn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(hb,{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 hb({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})]}),!ce()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(Ze,{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(tl,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===Mn.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(zi,{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 xb(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 pb(t){return t.length>8?t.slice(0,8):t}function Id(t){return t===Sa.completed?"positive":t===Sa.partial?"caution":t===Sa.failed?"negative":"neutral"}function gb(t){return t===Mn.completed?"positive":t===Mn.failed?"negative":"neutral"}async function fb(t){await qt(t,"researchRuns")}const Ki=new Set(["queued","seeding","probing"]);function yb({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:l={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:o,onTrackingQueryIdChange:d}){const{account:m}=Fn(),[u,h]=c.useState("tracked"),[g,x]=c.useState("find"),[y,p]=c.useState(null),v=m?.role==="viewer"?Ac():null,j=ed(m?.role,v),I=td(s??u,j),k=a??g,f=A=>{s===void 0&&h(A),n?.(A)},b=A=>{a===void 0&&x(A),r?.(A)},S=(A,P)=>{const C=P===void 0?{...l}:{...l,measurementScope:P?.kind??"project",measurementScopeKey:P?.key};p({...A,trackingSelection:C}),P!==void 0&&i?.({measurementScope:C.measurementScope,measurementScopeKey:C.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(Cr,{active:I==="tracked",label:"Tracked",onClick:()=>f("tracked")}),j?e.jsx(Cr,{active:I==="research",label:"Research",onClick:()=>f("research")}):null]}),e.jsx("div",{className:"mt-4",children:I==="tracked"?e.jsx(Ob,{projectName:t,selection:l,onSelectionChange:i,trackingQueryId:o,onTrackingQueryIdChange:d,pendingTrackingSource:y,onPendingTrackingSourceHandled:()=>p(null)}):e.jsx(bb,{projectName:t,selection:l,mode:k,onModeChange:b,onReviewSavedSource:S,onSelectionChange:i,viewerResearchConfig:v})})]})}function Cr({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 bb({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:l}){const{canWrite:i}=Fn(),o=!i||n==="test",d=Me({...Ji({client:Y,path:{name:t}}),enabled:o,staleTime:6e4}),m=Me({...Rc({client:Y,path:{name:t}}),enabled:o,staleTime:6e4}),u=c.useMemo(()=>{const x=d.data;if(!x)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const y=new Map(x.targets.map(v=>[v.stableKey,[]]));for(const v of x.groups)for(const j of v.targetKeys)y.get(j)?.push(v.stableKey);const p=new Map(x.markets.map(v=>[v.stableKey,new Set]));for(const v of x.markets)for(const j of v.usageEdges)for(const w of y.get(j.targetKey)??[])p.get(v.stableKey)?.add(w);return[{id:"project",label:"Whole site",kind:"project",targetCount:x.targets.length},...x.groups.map(v=>({id:v.stableKey,label:v.label,kind:"group",targetCount:v.targetKeys.length,...v.parentGroupKey?{parentGroupIds:[v.parentGroupKey]}:{}})),...x.markets.map(v=>{const j=[...p.get(v.stableKey)??[]];return{id:v.stableKey,label:v.label,kind:"market",targetCount:0,...j.length?{parentGroupIds:j}:{}}}),...x.targets.map(v=>({id:v.stableKey,label:v.label,kind:"property",targetCount:1,...y.get(v.stableKey)?.length?{parentGroupIds:y.get(v.stableKey)}:{}}))]},[d.data]),h=c.useMemo(()=>(m.data?.templates??[]).map(x=>({id:x.id,version:x.updatedAt,label:x.name,pattern:x.pattern,variables:x.variables})),[m.data]),g={projectName:t,scopeOptions:u,planRevision:d.data?.active?.revision??null,selectedScope:(()=>{const x=u.find(p=>p.kind===s.measurementScope&&p.id===s.measurementScopeKey),y=d.data?.active?.revision;return x&&y&&(x.kind==="market"||x.kind==="property")?{kind:x.kind,key:x.id,label:x.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:h};return i?e.jsxs("div",{children:[e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(Cr,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(Cr,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(Fb,{projectName:t,onReviewDiscoveryProbe:x=>r({source:"discovery",discoveryProbeId:x})}):e.jsx(Ao,{...g,onReviewForTracking:({researchRunQueryId:x,scope:y})=>r({source:"research",researchRunQueryId:x},y??null)})})]}):e.jsx(Ao,{...g,viewerResearchConfig:l})}function vb({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:o,preview:d,isPreviewing:m,isCommitting:u,onPreview:h,onCommit:g}){const[x,y]=c.useState(null),[p,v]=c.useState(()=>xr(s)),[j,w]=c.useState(null),I=c.useRef(null),k=c.useRef(null),f=sd(t,s),b=c.useMemo(()=>Sb(t.tracked,s,t.mode),[s,t.mode,t.tracked]),S=Dn({rows:b,getSearchText:H=>`${H.queryText} ${H.provenance?.source??"legacy"} ${H.assignments.map(te=>te.queryClass??"unknown").join(" ")}`});c.useEffect(()=>{if(f)return;if(!a){k.current=null;return}const H=`${a}:${ni(s)}`;if(k.current===H)return;const te=t.tracked.find(D=>D.queryId===a);te&&(k.current=H,y({kind:"edit",row:te,audience:t.mode==="advanced"?ti(s):void 0,scopeLabel:si(s,t)}),v(Ro(te,s)),w(null))},[s,a,f,t]),c.useEffect(()=>{if(f||!l)return;const H=xr(l.trackingSelection??s);y({kind:"add"}),v(l.source==="research"?{...H,source:"research",researchRunQueryId:l.researchRunQueryId}:{...H,source:"discovery",discoveryProbeId:l.discoveryProbeId}),w(null),i()},[i,l,s,f]),c.useEffect(()=>{f&&(y(null),w(null),a!==void 0&&r?.(void 0))},[r,a,f]),c.useEffect(()=>{if(!x||x.kind==="remove")return;const H=I.current;H&&(H.scrollIntoView?.({block:"start"}),H.focus({preventScroll:!0}))},[x]);function A(H="manual"){y({kind:"add"}),v({...xr(s),source:H}),w(null),r?.(void 0)}function P(H){k.current=`${H.queryId}:${ni(s)}`,y({kind:"edit",row:H,audience:t.mode==="advanced"?ti(s):void 0,scopeLabel:si(s,t)}),v(Ro(H,s)),w(null),r?.(H.queryId)}function C(H){k.current=`${H.queryId}:${ni(s)}`,y({kind:"remove",row:H,audience:t.mode==="advanced"?ti(s):void 0,scopeLabel:si(s,t)}),w(null),r?.(H.queryId)}function U(){y(null),w(null),r?.(void 0)}const O=x?jb(x,p,t.mode):null,J=x!==null&&x.kind==="add"&&t.mode==="advanced"&&!ul(p),V=O!==null&&(!J||p.contexts.length>0)&&!m;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(L,{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(Cb,{selection:s,onSelectionChange:n}):null,e.jsx(pn,{value:S.query,onChange:S.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!ce()&&e.jsxs(Ze,{type:"button",size:"sm",onClick:()=>A(),children:[e.jsx(ag,{"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(H=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:H.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(Ab,{row:H,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Pb,{row:H})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:kb(H)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Ib,{row:H,outsidePlan:t.mode==="advanced"&&H.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!ce()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(Ze,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${H.queryText}`,onClick:()=>P(H),children:[e.jsx(rg,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(Ze,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${H.queryText}`,onClick:()=>C(H),children:[e.jsx(Jc,{"aria-hidden":"true",size:13})," Remove"]})]})})]},H.queryId))})]})}),e.jsx(Zs,{page:S.page,pageSize:S.pageSize,visibleRows:S.rows.length,totalRows:S.totalRows,itemLabel:"queries",onPageChange:S.setPage})]}),x&&!ce()&&e.jsx(Tb,{workspace:t,templates:o,action:x,draft:p,onDraftChange:H=>{v(H),w(null)},onClose:U,canReview:V,isPreviewing:m,editorHeadingRef:I,onReview:()=>{O&&(w(O),h(O))}}),d&&j&&x&&e.jsx(qb,{preview:d,workspace:t,isCommitting:u,onConfirm:()=>{g({...j,expectedWorkspaceVersion:d.workspaceVersion,previewToken:d.previewToken,reviewedAt:d.reviewedAt})}})]})}function xr(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 Ro(t,s){return{...xr(s),text:t.queryText,queryClass:"keep"}}function jb(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=Nb(s);if(!a||Gi(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=wb(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!ul(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function Nb(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 wb(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 ul(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function Gi(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function ti(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 si(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 ml(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 Sb(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=>ml(r,s)))}function Cb({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 ni(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function kb(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 Td(t,s,n){const a=new Map(s.targets.map(p=>[p.stableKey,p.label])),r=new Map(s.groups.map(p=>[p.stableKey,p.label])),l=new Map(s.markets.map(p=>[p.stableKey,p.label])),i=new Set(t.assignments.map(p=>p.targetKey));if(i.size===0)return"Whole site";const o=n?t.assignments.filter(p=>ml(p,n)):t.assignments,d=new Set(o.map(p=>p.targetKey));if(n?.measurementScope==="group"){const p=d.size,v=Math.max(0,i.size-p);return[`${p} ${p===1?"property":"properties"} in this group`,...v?[`Shared with ${v} other ${v===1?"property":"properties"}`]:[]].join(" · ")}const m=new Set,u=new Set;for(const p of o)p.groupKeys.forEach(v=>m.add(v)),p.marketKeys.forEach(v=>u.add(v));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`],x=m.size===1?r.get([...m][0])??[...m][0]:null,y=u.size===1?l.get([...u][0])??[...u][0]:null;return x&&y&&x===y?g.push(`${x} (group and market)`):(x?g.push(`Group: ${x}`):m.size>1&&g.push(`${m.size} groups`),y?g.push(`Market: ${y}`):u.size>1&&g.push(`${u.size} markets`)),g.join(" · ")}function Ab({row:t,workspace:s,selection:n}){const a=Rb(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:Td(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 Rb(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])),o=t.assignments.filter(d=>ml(d,n)).map(d=>{const m=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),h=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[m,u.length?`Groups: ${u.join(", ")}`:null,h.length?`Markets: ${h.join(", ")}`:null].filter(g=>g!==null).join(" · ")});return[...new Set(o)].length?[...new Set(o)]:["Whole site"]}function Pb({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(re,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function Ib({row:t,outsidePlan:s=!1}){return s?e.jsx(re,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(re,{tone:"positive",children:"Measured"}):e.jsx(re,{tone:"caution",children:"Awaiting sweep"})}function Tb({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:l,canReview:i,isPreviewing:o,editorHeadingRef:d,onReview:m}){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(ai,{canReview:i,isPreviewing:o,onCancel:l,onReview:m})]}):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(L,{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:h=>r({...a,text:h.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:h=>r({...a,queryClass:h.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(ai,{canReview:i,isPreviewing:o,onCancel:l,onReview:m})]}):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(L,{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:h=>r({...a,text:h.target.value})})]}):null,a.source==="template"?e.jsx(Lb,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(Po,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(h=>({id:h.researchRunQueryId,label:h.queryText,detail:h.researchRunId})),onChange:h=>r({...a,researchRunQueryId:h})}):null,a.source==="discovery"?e.jsx(Po,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(h=>({id:h.discoveryProbeId,label:h.queryText,detail:h.discoverySessionId})),onChange:h=>r({...a,discoveryProbeId:h})}):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:h=>r({...a,source:h.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(Mb,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!ul(a)?e.jsx("div",{className:"mt-4",children:e.jsx($b,{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:h=>r({...a,queryClass:h.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(ai,{canReview:i,isPreviewing:o,onCancel:l,onReview:m})]})}function Lb({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":Gi(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]}),Gi(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 Po({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 hl(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function ja(t){return JSON.stringify({providers:[...t.providers].sort(),models:Object.fromEntries(Object.entries(t.models).sort(([s],[n])=>s.localeCompare(n))),location:t.location})}function Ld(t){return[...new Map(t.map(s=>[ja(s),s])).values()]}function xl(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 $b({workspace:t,draft:s,onDraftChange:n}){const a=c.useMemo(()=>Ld([...t.defaultContexts.map(hl),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?ja(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=>ja(d)===l.target.value),o=l.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:o})},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:ja(l),children:xl(l)},ja(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 Mb({workspace:t,draft:s,onDraftChange:n}){const[a,r]=c.useState(""),[l,i]=c.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),o=c.useMemo(()=>[...t.targets.map(x=>({kind:"target",key:x.stableKey,label:x.label,detail:"Property"})),...t.groups.map(x=>({kind:"group",key:x.stableKey,label:x.label,detail:"Group"})),...t.markets.map(x=>({kind:"market",key:x.stableKey,label:x.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),d=a.trim().toLocaleLowerCase(),m=d?o.filter(x=>`${x.label} ${x.detail}`.toLocaleLowerCase().includes(d)):o,u=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function h(x,y,p){const v=x==="target"?"targetKeys":x==="group"?"groupKeys":"marketKeys",j=s[v];n({...s,wholeSite:!1,[v]:p?[...j,y]:j.filter(w=>w!==y)})}function g(x,y){return(x==="target"?s.targetKeys:x==="group"?s.groupKeys:s.marketKeys).includes(y)}if(!l){const x=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: ",x?.label??s.targetKeys[0]]}),e.jsx(L,{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:x=>{n({...s,wholeSite:x.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(pn,{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:m.length===0?e.jsx("p",{className:"px-1 py-2 text-sm text-muted",children:"No assignment matches that search."}):m.map(x=>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":`${x.label}, ${x.detail}`,checked:g(x.kind,x.key),onChange:y=>h(x.kind,x.key,y.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:x.label}),e.jsx("span",{className:"text-xs text-muted",children:x.detail})]},`${x.kind}:${x.key}`))})]})}function ai({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(Ze,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(L,{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 qb({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=c.useRef(null);c.useEffect(()=>{const o=r.current;o&&(typeof o.scrollIntoView=="function"&&o.scrollIntoView({block:"start"}),o.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(o=>o.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(re,{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(o=>e.jsx(Io,{label:o.label,rows:o.rows,workspace:s,tracked:t.tracked},o.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(Io,{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(Ze,{type:"button",size:"sm",disabled:!l||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function Io({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`:Db(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(Eb,{row:a.find(l=>l.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function Eb({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",o=a.contexts.map(d=>xl(hl(d))).join("; ");return e.jsx("li",{children:[l,i,o].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function Db(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=Ld(a.assignments.flatMap(i=>i.contexts).map(hl)),l=r.length===1?xl(r[0]):r.length>1?`${r.length} contexts`:null;return[Td(a,n),l].filter(i=>i!==null).join(" · ")}function Ob({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i}){const o=ws(),[d,m]=c.useState(null),u=Me({...Ji({client:Y,path:{name:t}})}),h=Me({...Rc({client:Y,path:{name:t}}),staleTime:6e4}),g=Ht({...cm(),onSuccess:y=>m(y),onError:async y=>{m(null),await o.invalidateQueries({queryKey:om({client:Y,path:{name:t}})}),Oe({title:"Could not review tracking changes",detail:y instanceof Error?y.message:"Update the draft and review it again.",tone:"negative"})}}),x=Ht({...dm(),onSuccess:async y=>{m(null),r?.(void 0),await Tl(o,t),Oe({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=>{m(null),await Tl(o,t),Oe({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(L,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{u.refetch()},children:"Try again"})]}):e.jsx(vb,{workspace:u.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:h.data?.templates??[],preview:d,isPreviewing:g.isPending,isCommitting:x.isPending,onPreview:y=>{m(null),g.mutate({client:Y,path:{name:t},body:{...y,expectedWorkspaceVersion:u.data.workspaceVersion}})},onCommit:y=>x.mutate({client:Y,path:{name:t},body:y})})}function Fb({projectName:t,onReviewDiscoveryProbe:s}){const n=ws(),[a,r]=c.useState(null),[l,i]=c.useState(""),[o,d]=c.useState("100"),m=Me({...um({client:Y,path:{name:t},query:{limit:"10"}}),refetchInterval:w=>w.state.data?.some(k=>Ki.has(k.status))?3e3:!1}),u=m.data??[];c.useEffect(()=>{!a&&u[0]&&r(u[0].id)},[a,u]);const h=u.find(w=>w.id===a)??null,g=Me({...mm({client:Y,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:h&&Ki.has(h.status)?3e3:!1}),x=g.data??null,y=Ht({mutationFn:()=>{const w={},I=l.trim();I&&(w.icpDescription=I);const k=Number.parseInt(o,10);return Number.isFinite(k)&&k>0&&(w.maxProbes=k),hm(t,w)},onSuccess:async w=>{r(w.sessionId),i(""),await Bb(n,t,w.sessionId),Oe({title:"Discovery started",detail:`Run ${ri(w.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${w.sessionId}`,dedupeMode:"replace"})},onError:w=>{Oe({title:"Discovery failed to start",detail:w instanceof Error?w.message:"Could not start discovery.",tone:"negative"})}}),p=x??h,v=c.useMemo(()=>(x?.probes??[]).slice(0,30),[x?.probes]);async function j(){try{const w=await m.refetch();if(w.error)throw w.error;const I=w.data?.length??0;Oe({title:"Discovery sessions refreshed",detail:`${I} recent session${I===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(w){Oe({title:"Discovery refresh failed",detail:w instanceof Error?w.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:ce()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(L,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{j()},children:[e.jsx(Pa,{className:`size-3.5 ${m.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(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(re,{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:w=>i(w.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:o,onChange:w=>d(w.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."})]}),!ce()&&e.jsxs(Ze,{type:"button",size:"sm",disabled:y.isPending,onClick:()=>y.mutate(),children:[e.jsx(br,{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"})]}),m.isFetching&&e.jsx(re,{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(w=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===w.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(w.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:ri(w.id)}),e.jsx(re,{tone:To(w.status),children:w.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",w.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",w.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",w.wastedCount??0]})]})]},w.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:p?ri(p.id):"No run selected"})]}),p&&e.jsx(re,{tone:To(p.status),children:p.status})]}),p?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(sr,{label:"Questions tested",value:p.probeCount??0}),e.jsx(sr,{label:"Cited queries",value:p.citedCount??0,tone:"positive"}),e.jsx(sr,{label:"Worth tracking",value:p.aspirationalCount??0,tone:"caution"}),e.jsx(sr,{label:"Skip",value:p.wastedCount??0,tone:"negative"})]}),p.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:p.error}),p.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:p.warning}),p.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:p.icpDescription})]}),p.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:p.competitorMap.slice(0,8).map(w=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[w.domain," ",e.jsx("span",{className:"text-muted",children:w.hits})]},w.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),p?.status==="completed"&&e.jsxs(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(re,{tone:"neutral",children:"Loading"})]}),v.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Tracking review"})})]})}),e.jsx("tbody",{children:v.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:w.query}),e.jsx("td",{children:e.jsx(re,{tone:Kb(w.bucket),children:_b(w.bucket)})}),e.jsx("td",{className:"text-secondary",children:w.citedDomains.length>0?w.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!ce()&&s&&(w.bucket==="cited"||w.bucket==="aspirational")&&e.jsx(Ze,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(w.id),children:"Review for tracking"})})]},w.id))})]})})]})]})]})]})}function sr({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 To(t){return t==="completed"?"positive":t==="failed"?"negative":Ki.has(t)?"caution":"neutral"}function Kb(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Gb={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function _b(t){return t?Gb[t]:"Not classified"}function ri(t){return t.length>8?t.slice(0,8):t}async function Bb(t,s,n){await Promise.all([qt(t,"discovery"),t.invalidateQueries({queryKey:xm({client:Y})})])}function Ub({projectName:t}){const[s,n]=c.useState("changes"),[a,r]=c.useState(null),[l,i]=c.useState(null),o=Me({...pm({client:Y,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=Me({...gm({client:Y,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),m=(d.data??[]).filter(v=>(v.status==="completed"||v.status==="partial")&&v.trigger!=="probe").reverse(),u=l??m[0]?.id??"",h=a??m.find(v=>v.id!==u)?.id??"",g=!!(h&&u&&h!==u),x=Me({...fm({client:Y,path:{name:t},query:{run1:h,run2:u}}),enabled:s==="compare"&&g}),y=o.data??[],p=x.data?.diff.filter(v=>v.changed||v.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([v,j])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===v,className:`filter-chip ${s===v?"filter-chip-active":""}`,onClick:()=>n(v),children:j},v))}),s==="changes"?e.jsx(xg,{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."})]}),o.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!o.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:Ns()?aa:"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(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(v.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[v.mentionedPairs,"/",v.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Fe(v.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[v.citedPairs,"/",v.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Fe(v.overallCitedRate)})]},v.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:h,onChange:v=>r(v.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:m.map(v=>e.jsx("option",{value:v.id,children:new Date(v.createdAt).toLocaleString()},v.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:u,onChange:v=>i(v.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:m.map(v=>e.jsx("option",{value:v.id,children:new Date(v.createdAt).toLocaleString()},v.id))})]})]}),d.isLoading||x.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!d.isLoading&&m.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:Ns()?aa:"Run another answer visibility sweep before comparing historical evidence."})]}):null,x.data&&p.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,p.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:p.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:v.query??"Archived query"}),e.jsx("td",{children:e.jsxs(re,{tone:v.changed?"caution":"neutral",children:[v.run1State??"none"," → ",v.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(re,{tone:v.visibilityChanged?"caution":"neutral",children:[v.run1MentionState??"none"," → ",v.run2MentionState??"none"]})})]},v.queryId??v.query??"unknown"))})]})}):null]}):null]})}const Lo={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},Vb={contract:null,assessment:null,googleAds:Lo,gtm:Lo,snapshots:[]};function Hb(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Yb(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Qb(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 zb(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 Wb(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 $d(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"&&Jb(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 Yb(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Jb(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Md(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 Xb(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 Zb(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 An(t){return t.length<=12?t:`…${t.slice(-10)}`}function ev(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 tv(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 ii={"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 $o(t){return t.outcome==="pass"?{label:ii[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:ii[t.code],tone:"negative",outcome:"Fail"}:{label:ii[t.code],tone:"caution",outcome:"Unknown"}}function sv(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function nv(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 av(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function Mo({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const l=Md(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(re,{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 ${ss(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(Ze,{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 rv="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.",iv="Available once Google Ads and Tag Manager are connected.",lv="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 ov({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:l}){const i=t.googleAds.state==="connected",o=t.gtm.state==="connected",d=t.googleAds.state==="unavailable",m=t.gtm.state==="unavailable",u=d||m||t.gtm.state==="unavailable",h={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},g=!i&&!o,x=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:d?h:zb(t)},{title:"Tag Manager",state:t.gtm.state,ready:o,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:m?h:Wb(t)}],y=i&&o&&!u?$d(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(_e,{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:lv}):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(_e,{text:rv})]}),y&&s?e.jsx(Ze,{type:"button",disabled:r,onClick:()=>s(y.id),children:r?"Working…":y.label}):e.jsx("p",{className:"text-sm text-secondary",children:iv})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:x.map(p=>{const v=p.ready?{label:"Ready",tone:"positive"}:Md(p.state),j=p.action;return e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-heading",children:p.title}),e.jsx(re,{tone:v.tone,children:v.label}),p.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:p.summary}):null,j&&s?j.id==="retry-connection-status"?e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(j.id),children:r?"Working…":j.label}):e.jsx(Ze,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(j.id),children:r?"Working…":j.label}):null,p.summary&&p.onChange?e.jsx(Ze,{type:"button",variant:"ghost",size:"sm","aria-label":p.changeLabel,disabled:r,onClick:p.onChange,children:"Change"}):null]},p.title)})}),l?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:l}):null]})]})}function cv({workspace:t=Vb,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:l=null,onSelectContract:i,contractError:o=null,onRetryContracts:d,onRetryEvidence:m,onChangeGoogleAdsSelection:u,onChangeGtmSelection:h,onAddContract:g}){const x=Hb(t),y=Qb(x),p=$d(t),v=t.assessment?.findings??[],j=v.filter(f=>f.outcome!=="pass"),w=v.filter(f=>f.outcome==="pass"),I=j.some(f=>f.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&o===null?e.jsx(ov,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:u,onChangeGtmSelection:h,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(re,{tone:y.tone,children:y.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",ss(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:[av(f)," ",f.kind,", captured ",ss(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?p.id==="review-findings"||p.id==="review-runtime-verification"||p.id==="retry-connection-status"||p.id==="select-contract"||p.id==="retry-integrity"||p.id==="waiting-for-integrity"?e.jsx(L,{type:"button",disabled:n||p.id==="waiting-for-integrity",onClick:()=>s(p.id),children:n?"Working…":p.label}):e.jsx(Ze,{type:"button",disabled:n,onClick:()=>s(p.id),children:n?"Working…":p.label}):p.id==="review-findings"?e.jsx(L,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):x==="runtime-unverified"?e.jsx(L,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:p.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),r.length>0&&g?e.jsx(Ze,{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:ev(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:tv(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:An(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:An(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:An(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:An(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."}),o?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:o}),d?e.jsx(L,{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]}),j.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(re,{tone:I,children:[j.length," ",j.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:j.map(f=>{const b=$o(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:b.label}),e.jsx(re,{tone:b.tone,children:b.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(_e,{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 b=Xb(f.key,x);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 ${b==="positive"?"bg-positive-fill":b==="caution"?"bg-caution-fill":b==="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(re,{tone:b,children:Zb(f.key,x)})]},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:[Mo({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:u}:{},actionPending:n}),Mo({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:h}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&m?e.jsx(L,{type:"button",variant:"outline",className:"mt-3",onClick:m,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(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:ss(f.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:An(f.id)})]},f.id))})]})})]}):null,w.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[w.length," ",w.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:w.map(f=>{const b=$o(f);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:b.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(re,{tone:b.tone,children:b.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:f.subject})]},`${f.code}:${f.subject}`)})})]})})]}):null,x==="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 ",sv(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:An(t.contract.gtm.tagId)})," fires with ",nv(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:An(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const Rn=3e4,qo={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Jt="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",vs="text-sm font-medium text-secondary";function Eo(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:Pt(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function nr(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function dv(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 uv(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function mv(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:uv(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 hv(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:nr(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:nr(t.triggerIds),variableIds:nr(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:nr(t.productionHosts)}}}function Do(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 ar(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 rr(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function ir({id:t,label:s,value:n,onChange:a,children:r,disabled:l=!1}){return e.jsxs("label",{htmlFor:t,className:vs,children:[s,e.jsx("select",{id:t,className:Jt,value:n,onChange:i=>a(i.target.value),disabled:l,children:r})]})}function Wn({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 Oo({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=c.useState(!1),[l,i]=c.useState(!1),[o,d]=c.useState(null),m=c.useRef(null),u=c.useRef(null),h=c.useRef(!1);c.useEffect(()=>{const p=h.current;h.current=a,a?u.current?.focus():p&&m.current?.querySelector("button")?.focus()},[a]);function g(){d(null),r(!0)}function x(){d(null),r(!1)}async function y(){i(!0),d(null);try{await n()}catch(p){d(Pt(p)),i(!1)}}return e.jsx("div",{ref:m,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(L,{ref:u,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:l,onClick:x,children:"Keep connected"}),e.jsx(Ze,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||l,onClick:()=>{y()},children:l?"Disconnecting…":`Disconnect ${t}`})]}),o?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:o}):null]}):e.jsxs(Ze,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:g,children:["Disconnect ",t]})})}function Fo({id:t,label:s,options:n,synced:a,loading:r,failed:l,onRetry:i,emptyHint:o,value:d,onChange:m}){const u=n.some(p=>p.id===d),[h,g]=c.useState(!1),x=h||d!==""&&!u&&n.length>0,y=e.jsx("label",{htmlFor:t,className:vs,children:s});return r?e.jsxs("div",{children:[y,e.jsx("select",{id:t,className:Jt,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):l?e.jsxs("div",{children:[y,e.jsx("input",{id:t,required:!0,className:Jt,value:d,onChange:p=>m(p.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:i,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[y,e.jsx("input",{id:t,required:!0,className:Jt,value:d,onChange:p=>m(p.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":o})]}):e.jsxs("div",{children:[y,x?e.jsx("input",{id:t,required:!0,className:Jt,value:d,onChange:p=>m(p.target.value)}):e.jsxs("select",{id:t,required:!0,className:Jt,value:d,onChange:p=>m(p.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(p=>e.jsxs("option",{value:p.id,children:[p.name,p.detail?` (${p.detail})`:"",p.active?"":" — inactive"]},p.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{g(!x),m("")},children:x?"Choose from synced list":"Enter an ID manually"})]})}function xv({projectId:t,projectName:s}){const n=Fn(),[a,r]=c.useState(null),[l,i]=c.useState(null),[o,d]=c.useState(!1),[m,u]=c.useState(""),[h,g]=c.useState(null),[x,y]=c.useState(!1),[p,v]=c.useState(!1),[j,w]=c.useState(""),[I,k]=c.useState(""),[f,b]=c.useState(""),[S,A]=c.useState(""),[P,C]=c.useState(""),[U,O]=c.useState(!1),[J,V]=c.useState(qo),[H,te]=c.useState(null),D=c.useRef(null),$=Me({...ym({client:Y,path:{name:s}}),staleTime:Rn}),Q=Me({...bm({client:Y,path:{name:s}}),staleTime:Rn}),B=Me({...vm({client:Y,path:{name:s}}),staleTime:Rn}),_=Me({...jm({client:Y,path:{name:s}}),staleTime:Rn}),M=_.data,W=Me({...Nm({client:Y,path:{name:s},query:{limit:5}}),staleTime:Rn}),ne=Me({...wm({client:Y,path:{name:s},query:{limit:5}}),staleTime:Rn}),ie=B.data??[],ke=(H?ie.find(E=>E.id===H)??null:null)??(ie.length===1?ie[0]??null:null),X=ie.length>1&&!ke,le=Me({...Sm({client:Y,path:{name:s,contractId:ke?.id??""}}),enabled:!!ke,staleTime:Rn}),je=Me({...Cm({client:Y,path:{name:s}}),enabled:h==="google-ads"&&$.data?.connected===!0,staleTime:0}),ee=Me({...km({client:Y,path:{name:s}}),enabled:h==="gtm"&&Q.data?.connected===!0,staleTime:0}),oe=Me({...Am({client:Y,path:{name:s,accountId:f}}),enabled:h==="gtm"&&!!f,staleTime:0}),G=Me({...Rm({client:Y,path:{name:s,accountId:f,containerId:S}}),enabled:h==="gtm"&&!!f&&!!S,staleTime:0}),ue=Ht(Pm({client:Y})),se=Ht(Im({client:Y})),Se=Ht(Tm({client:Y})),Ce=Ht(Lm({client:Y})),Ie=Ht($m({client:Y})),Be=Ht(Mm({client:Y})),qe=Ht(qm({client:Y})),pe=Ht(Em({client:Y})),F=Ht(Dm({client:Y}));c.useEffect(()=>{if(h!=="google-ads"||x||!$.isSuccess)return;const E=$.data.connection?.selection;w(E?.customerId??""),k(E?.loginCustomerId??""),y(!0)},[x,$.data,$.isSuccess,h]),c.useEffect(()=>{if(h!=="gtm"||p||!Q.isSuccess)return;const E=Q.data.selection;b(E?.accountId??""),A(E?.containerId??""),C(E?.workspaceId??""),v(!0)},[p,Q.data,Q.isSuccess,h]),c.useEffect(()=>{!H||!B.data||B.data.some(E=>E.id===H)||te(null)},[B.data,H]);const Ke=c.useMemo(()=>{const E=W.data?.snapshots??[],Ne=ne.data?.snapshots??[],mt=[...E.map(wt=>({id:wt.id,provider:"google-ads",kind:wt.kind,capturedAt:wt.capturedAt})),...Ne.map(wt=>({id:wt.id,provider:"gtm",kind:wt.kind,capturedAt:wt.capturedAt}))].sort((wt,gs)=>gs.capturedAt.localeCompare(wt.capturedAt)).slice(0,5),Bt=[],ls=le.data?.googleAdsSnapshot,We=le.data?.gtmSnapshot;return ls&&Bt.push({id:ls.id,provider:"google-ads",kind:ls.kind,capturedAt:ls.capturedAt}),We&&Bt.push({id:We.id,provider:"gtm",kind:We.kind,capturedAt:We.capturedAt}),{contract:le.data?.assessment.contract??ke,assessment:le.data?.assessment??null,contractSelectionRequired:X,assessmentState:ke?le.isError?"unavailable":le.isLoading?"loading":void 0:void 0,assessmentError:le.isError?Pt(le.error):null,googleAds:dv($.data,Eo(W.data?.total??0,W.isLoading,W.isError,W.error),$.isError),gtm:mv(Q.data,Eo(ne.data?.total??0,ne.isLoading,ne.isError,ne.error),Q.isError),snapshots:mt,assessmentEvidenceSnapshots:Bt}},[ke,X,W.data,W.error,W.isError,W.isLoading,$.data,$.isError,ne.data,ne.error,ne.isError,ne.isLoading,Q.data,Q.isError,le.data,le.error,le.isError,le.isLoading]),T=c.useSyncExternalStore(vc,pr,pr),ye=Object.values(T.runs).some(E=>E.projectId===t&&(E.kind===gn["google-ads-sync"]||E.kind===gn["gtm-sync"])),Ve=ue.isPending||se.isPending||Se.isPending||Ce.isPending||Ie.isPending||Be.isPending||qe.isPending||pe.isPending||F.isPending||ye;async function Ye(){await Promise.all([$.refetch(),Q.refetch(),B.refetch(),W.refetch(),ne.refetch(),_.refetch(),ke?le.refetch():Promise.resolve()])}async function et(E){await Ye();for(let Ne=0;Ne<10&&!E();Ne+=1)await new Promise(mt=>setTimeout(mt,1500)),await Ye()}function xe(){const E=document.activeElement;D.current=E instanceof HTMLElement?E:null}function ft(E){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(E);return}globalThis.setTimeout(E,0)}function ze(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function nt(E){if(!E)return;!E.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!E.hasAttribute("tabindex")&&(E.tabIndex=-1),E.focus({preventScroll:!0})}function as(E,Ne=E){const mt=document.getElementById(E);mt instanceof HTMLDetailsElement&&(mt.open=!0);const Bt=mt?.scrollIntoView;typeof Bt=="function"&&Bt.call(mt,{behavior:ze()?"auto":"smooth",block:"start"}),nt(document.getElementById(Ne)??mt)}function xt(E,Ne){xe(),ft(()=>as(E,Ne))}function at(){const E=D.current;D.current=null,E&&ft(()=>{E.isConnected&&E.focus({preventScroll:!0})})}function yt(){r(null),d(!1),at()}function At(){r(null),g(null),at()}function $t(){r(null),O(!1),at()}function He(){r(null),g(null),d(!0),xt("google-ads-connect-panel","google-ads-connect-title")}function R(){r(null),w(""),k(""),y(!1),g("google-ads"),d(!1),xt("google-ads-selection-panel","google-ads-selection-title")}function Ae(){r(null),b(""),A(""),C(""),v(!1),g("gtm"),d(!1),xt("gtm-selection-panel","gtm-selection-title")}function me(){r(null),O(!0),xt("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Je(E,Ne){bc({id:E.id,projectId:E.projectId,kind:E.kind,projectLabel:s,sourceAction:Ne}),Oe({title:Ne==="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:${E.id}`,dedupeMode:"replace"})}async function Ft(){Ds(n),r(null);try{const E=await ue.mutateAsync({path:{name:s},body:{provider:"google-ads",...m.trim()?{developerToken:m.trim()}:{}}});u(""),d(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Do(E.authorizationUrl,()=>{Ye(),i(null),at()})}catch(E){r(Pt(E))}}async function Kt(){Ds(n),r(null);try{const E=await se.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."),Do(E.authorizationUrl,()=>{Ye(),i(null),at()})}catch(E){r(Pt(E))}}async function ut(){if(Ds(n),!j){r("Select a Google Ads customer before saving.");return}r(null);try{await Se.mutateAsync({path:{name:s},body:{customerId:j,...I.trim()?{loginCustomerId:I.trim()}:{}}}),g(null),at(),await et(()=>$.data?.selectedCustomer!=null)}catch(E){r(Pt(E))}}async function Z(){if(Ds(n),!f||!S){r("Select a Tag Manager account and container before saving.");return}r(null);try{await Ce.mutateAsync({path:{name:s},body:{accountId:f,containerId:S,...P?{workspaceId:P}:{}}}),g(null),at(),await et(()=>Q.data?.status==="connected")}catch(E){r(Pt(E))}}async function Ge(){Ds(n),r(null),await qe.mutateAsync({path:{name:s}}),g(null),d(!1),w(""),k(""),y(!1),i(null),await Ye(),Oe({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),D.current=null,ft(()=>nt(document.getElementById("conversion-integrity-title")))}async function Te(){Ds(n),r(null),await pe.mutateAsync({path:{name:s}}),g(null),b(""),A(""),C(""),v(!1),i(null),await Ye(),Oe({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),D.current=null,ft(()=>nt(document.getElementById("conversion-integrity-title")))}async function Pe(){Ds(n),r(null);try{const E=await Ie.mutateAsync({path:{name:s}});Je(E,"google-ads-sync")}catch(E){r(Pt(E))}}async function Gt(){Ds(n),r(null);try{const E=await Be.mutateAsync({path:{name:s}});Je(E,"gtm-sync")}catch(E){r(Pt(E))}}async function St(){Ds(n),r(null);try{const E=await Promise.allSettled([Ie.mutateAsync({path:{name:s}}),Be.mutateAsync({path:{name:s}})]),[Ne,mt]=E;Ne.status==="fulfilled"&&Je(Ne.value,"google-ads-sync"),mt.status==="fulfilled"&&Je(mt.value,"gtm-sync");const Bt=E.find(ls=>ls.status==="rejected");if(Bt?.status==="rejected")throw Bt.reason}catch(E){r(Pt(E))}}async function rs(){Ds(n);const E=$.data?.connection?.selection.customerId,Ne=Q.data?.selection;if(!E||!Ne?.accountId||!Ne.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const mt=await F.mutateAsync({path:{name:s},body:hv(J,E,{accountId:Ne.accountId,containerId:Ne.containerId})});V(qo),O(!1),at(),(await B.refetch()).data?.some(ls=>ls.id===mt.id)&&te(mt.id)}catch(mt){r(Pt(mt))}}function it(E){switch(E){case"connect-google-ads":He();return;case"connect-gtm":xe(),Kt();return;case"select-google-ads":R();return;case"select-gtm":Ae();return;case"sync-google-ads":Pe();return;case"sync-gtm":Gt();return;case"sync-static-evidence":St();return;case"declare-contract":me();return;case"review-findings":xt("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":xt("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Ye();return;case"select-contract":xt("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":le.refetch();return;case"waiting-for-integrity":return}}const _t=je.data?.customers??[],cs=ee.data?.accounts??[],Is=oe.data?.containers??[],Ts=G.data?.workspaces??[],Ls=!!j&&!_t.some(E=>E.customerId===j),nn=!!f&&!cs.some(E=>E.id===f),jt=!!S&&!Is.some(E=>E.id===S),Ss=!!P&&!Ts.some(E=>E.id===P),st=Ls&&je.isSuccess&&je.data.truncated===!1,zt=nn&&ee.isSuccess&&ee.data.truncated===!1,ds=jt&&oe.isSuccess&&oe.data.truncated===!1,ps=Ss&&G.isSuccess&&G.data.truncated===!1,Cs=zt||ds||ps,Rt=zt?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":ds?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":ps?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,Mt=rr(st,je.data,je.isError),us=rr(zt,ee.data,ee.isError),Wt=rr(ds,oe.data,oe.isError),an=rr(ps,G.data,G.isError),Ct=je.isError?Pt(je.error):null,is=ee.isError?Pt(ee.error):oe.isError?Pt(oe.error):G.isError?Pt(G.error):null,bt=h==="google-ads"?Ct:h==="gtm"?is:null,K=ar("customer",je.data,_t.length),ae=ar("account",ee.data,cs.length),Re=ar("container",oe.data,Is.length),he=ar("draft workspace",G.data,Ts.length),Le=ee.isError||oe.isError||G.isError&&!!P,Qe=o||h!==null||U;function gt(){je.refetch()}function Nt(){if(ee.isError){ee.refetch();return}if(oe.isError){oe.refetch();return}G.isError&&G.refetch()}return $.isLoading||Q.isLoading||B.isLoading?e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("div",{"aria-hidden":"true",className:"mt-5 grid gap-4 sm:grid-cols-2",children:[0,1].map(E=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"skeleton-text-sm w-full"}),e.jsx("div",{className:"skeleton-text-sm w-3/4"})]},E))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):B.isError&&!B.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: ",Pt(B.error)]}),e.jsx(L,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{B.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(cv,{workspace:Ke,onPrimaryAction:it,actionPending:Ve,actionError:Qe?null:a,contracts:ie,selectedContractId:ke?.id??null,onSelectContract:E=>te(E||null),contractError:B.isError?Pt(B.error):null,onRetryContracts:()=>{B.refetch()},onRetryEvidence:()=>{Promise.all([W.refetch(),ne.refetch()])},onChangeGoogleAdsSelection:R,onChangeGtmSelection:Ae,onAddContract:()=>it("declare-contract")}),l?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:l}):null,o?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:tt(async E=>{E.preventDefault(),await Ft()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:vs,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:m,onChange:E=>u(E.target.value),className:Jt,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(Ze,{type:"submit",disabled:ue.isPending,children:ue.isPending?"Starting…":"Continue to Google"}),e.jsx(L,{type:"button",variant:"outline",onClick:yt,children:"Cancel"})]})]})]}):null,h==="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"})]})}),bt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:bt}),e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:gt,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,st?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(ir,{id:"google-ads-customer",label:"Customer account",value:j,onChange:E=>{y(!0),w(E);const Ne=_t.find(mt=>mt.customerId===E);k(Ne?.parentCustomerId??"")},disabled:je.isLoading,children:[e.jsx("option",{value:"",children:je.isLoading?"Loading accessible customers…":"Select a customer"}),Ls?e.jsxs("option",{value:j,disabled:st,children:["Saved customer ",j," (",Mt,")"]}):null,_t.map(E=>e.jsx("option",{value:E.customerId,children:E.descriptiveName??`Customer ${E.customerId}`},E.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:vs,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Jt,value:I,onChange:E=>{y(!0),k(E.target.value)},placeholder:"Use only when a manager context is required"})]})]}),K?e.jsx("p",{role:"status",className:`mt-3 text-sm ${je.data?.truncated?"text-caution":"text-secondary"}`,children:K}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ze,{type:"button",disabled:Se.isPending||je.isLoading||je.isError||st||!j,onClick:tt(ut),children:Se.isPending?"Saving…":"Save customer selection"}),e.jsx(L,{type:"button",variant:"outline",onClick:At,children:"Cancel"})]}),$.data?.connected?e.jsx(Oo,{providerLabel:"Google Ads",disabled:Ve,onDisconnect:Ge}):null]}):null,h==="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"})]})}),bt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:bt}),e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:Nt,children:ee.isError?"Retry account list":oe.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Rt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Rt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(ir,{id:"gtm-account",label:"Account",value:f,onChange:E=>{v(!0),E!==f&&(A(""),C("")),b(E)},disabled:ee.isLoading,children:[e.jsx("option",{value:"",children:ee.isLoading?"Loading accounts…":"Select an account"}),nn?e.jsxs("option",{value:f,disabled:zt,children:["Saved account ",f," (",us,")"]}):null,cs.map(E=>e.jsx("option",{value:E.id,children:E.name},E.id))]}),e.jsxs(ir,{id:"gtm-container",label:"Container",value:S,onChange:E=>{v(!0),E!==S&&C(""),A(E)},disabled:!f||oe.isLoading,children:[e.jsx("option",{value:"",children:oe.isLoading?"Loading containers…":"Select a container"}),jt?e.jsxs("option",{value:S,disabled:ds,children:["Saved container ",S," (",Wt,")"]}):null,Is.map(E=>e.jsx("option",{value:E.id,children:E.name},E.id))]}),e.jsxs(ir,{id:"gtm-workspace",label:"Draft workspace (optional)",value:P,onChange:E=>{v(!0),C(E)},disabled:!S||G.isLoading,children:[e.jsx("option",{value:"",children:G.isLoading?"Loading workspaces…":"No draft workspace"}),Ss?e.jsxs("option",{value:P,disabled:ps,children:["Saved draft workspace ",P," (",an,")"]}):null,Ts.map(E=>e.jsx("option",{value:E.id,children:E.name},E.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:ee.data?.truncated?"text-caution":"text-secondary",children:ae}):null,Re?e.jsx("p",{role:"status",className:oe.data?.truncated?"text-caution":"text-secondary",children:Re}):null,he?e.jsx("p",{role:"status",className:G.data?.truncated?"text-caution":"text-secondary",children:he}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ze,{type:"button",disabled:Ce.isPending||ee.isLoading||oe.isLoading||G.isLoading&&!!P||Le||Cs||!f||!S,onClick:tt(Z),children:Ce.isPending?"Saving…":"Save container selection"}),e.jsx(L,{type:"button",variant:"outline",onClick:At,children:"Cancel"})]}),Q.data?.connected?e.jsx(Oo,{providerLabel:"Tag Manager",disabled:Ve,onDisconnect:Te}):null]}):null,U?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:tt(async E=>{E.preventDefault(),await rs()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:vs,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Jt,value:J.name,onChange:E=>V(Ne=>({...Ne,name:E.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:vs,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Jt,value:J.eventName,onChange:E=>V(Ne=>({...Ne,eventName:E.target.value})),placeholder:"booking_complete"})]}),e.jsx(Fo,{id:"contract-conversion-action",label:"Google Ads conversion action",options:M?.googleAds.conversionActions??[],synced:M?.googleAds.syncedAt!=null,loading:_.isLoading,failed:_.isError,onRetry:()=>{_.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:J.conversionActionId,onChange:E=>V(Ne=>({...Ne,conversionActionId:E}))}),e.jsx(Fo,{id:"contract-gtm-tag",label:"Tag Manager tag",options:M?.gtm.tags??[],synced:M?.gtm.syncedAt!=null,loading:_.isLoading,failed:_.isError,onRetry:()=>{_.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:J.tagId,onChange:E=>V(Ne=>({...Ne,tagId:E}))})]}),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:vs,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Jt,value:J.conversionId,onChange:E=>V(Ne=>({...Ne,conversionId:E.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:vs,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Jt,value:J.conversionLabel,onChange:E=>V(Ne=>({...Ne,conversionLabel:E.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:vs,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Jt,value:J.triggerIds,onChange:E=>V(Ne=>({...Ne,triggerIds:E.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:vs,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Jt,value:J.variableIds,onChange:E=>V(Ne=>({...Ne,variableIds:E.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:vs,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Jt,value:J.campaignIds,onChange:E=>V(Ne=>({...Ne,campaignIds:E.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:vs,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Jt,value:J.productionHosts,onChange:E=>V(Ne=>({...Ne,productionHosts:E.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(Wn,{id:"contract-primary-action",checked:J.requirePrimaryAction,onChange:E=>V(Ne=>({...Ne,requirePrimaryAction:E})),children:"Google Ads action is primary"}),e.jsx(Wn,{id:"contract-biddable-goal",checked:J.requireBiddableGoal,onChange:E=>V(Ne=>({...Ne,requireBiddableGoal:E})),children:"Google Ads goal is biddable"}),e.jsx(Wn,{id:"contract-runtime-verification",checked:J.verificationRequired,onChange:E=>V(Ne=>({...Ne,verificationRequired:E})),children:"Runtime proof is required"}),e.jsx(Wn,{id:"contract-transaction-id",checked:J.requireTransactionId,onChange:E=>V(Ne=>({...Ne,requireTransactionId:E})),children:"Transaction ID is required"}),e.jsx(Wn,{id:"contract-value",checked:J.requireValue,onChange:E=>V(Ne=>({...Ne,requireValue:E})),children:"Conversion value is required"}),e.jsx(Wn,{id:"contract-currency",checked:J.requireCurrency,onChange:E=>V(Ne=>({...Ne,requireCurrency:E})),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(Ze,{type:"submit",disabled:F.isPending,children:F.isPending?"Saving…":"Save conversion contract"}),e.jsx(L,{type:"button",variant:"outline",onClick:$t,children:"Cancel"})]})]})]}):null]})}const pv=6e4,gv=["7d","14d","30d"],pl="not available",fv='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%.',yv="No Google Ads snapshot stored yet",bv="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.",vv="No closed days yet",jv="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.",Nv={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},un=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),li=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),wv=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Yn(t,s){return t===null||!Number.isFinite(t)?pl:s===null?wv.format(t/1e6):gg(t,s)}function oi(t){return t===null||!Number.isFinite(t)?pl:Fe(t)}function Sv(t,s){return t===null||!Number.isFinite(t)?`${pl} vs prior ${s}d`:t===0?`no change vs prior ${s}d`:`${t>0?"↑":"↓"} ${Fe(Math.abs(t))} vs prior ${s}d`}function Cv(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function kv(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function Av(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 Rv({projectName:t}){const[s,n]=c.useState("14d"),[a,r]=c.useState(()=>new Set(["costMicros","conversions"])),l=Me({...Om({client:Y,path:{name:t},query:{window:s}}),staleTime:pv}),i=l.data,o=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(_e,{text:fv})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Tt(i.startDate)," to ",Tt(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(Ir,{windows:gv,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:[o,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:[o,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",Pt(l.error)]}),e.jsx(L,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{l.refetch()},children:"Retry performance"})]});const{totals:d,daily:m,campaigns:u,comparison:h,comparisonUnavailableReason:g,source:x}=i;if(!x){const f=g==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[o,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?vv:yv}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:f?jv:bv})]})]})}const y=x.currencyCode,p=x.campaignsInInventory>0&&x.campaignsQueried<x.campaignsInInventory?{queried:x.campaignsQueried,inInventory:x.campaignsInInventory}:null,v=d.costMicros>0&&d.conversions===0,j=[{key:"spend",comparable:!0,label:"Spend",value:Yn(d.costMicros,y),change:h?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:li.format(d.conversions),change:h?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:v?"no conversions":Yn(d.costPerConversionMicros,y),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:oi(d.conversionRate),change:h?.change.conversionRate??null,direction:"up-good",seriesKey:null}],w=[{key:"clicks",label:"Clicks",value:un.format(d.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:un.format(d.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:oi(d.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:Yn(d.cpcMicros,y),seriesKey:null}],I={costMicros:{label:"Spend",color:ct[1],axisId:"spend",formatValue:f=>Yn(f,y)},conversions:{label:"Conversions",color:ct[0],axisId:"conversions",formatValue:f=>li.format(f)},clicks:{label:"Clicks",color:ct[2],axisId:"clicks",formatValue:f=>un.format(f)},impressions:{label:"Impressions",color:ct[3],axisId:"impressions",formatValue:f=>un.format(f)}},k=[...a].map(f=>({dataKey:f,...I[f]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[o,p!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",un.format(p.queried)," of"," ",un.format(p.inInventory)," campaigns, so they are a subset of the account."]}):null,x.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,!h&&g==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:Nv["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:j.map(f=>{const b=f.seriesKey!==null&&a.has(f.seriesKey),S=b&&a.size===1,A=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:b?I[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}),h&&f.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${Av(f.change,f.direction)}`,children:Sv(f.change,h.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:A},f.key):e.jsx("button",{type:"button","aria-pressed":b,disabled:S,onClick:()=>r(P=>{const C=new Set(P);return C.has(f.seriesKey)?C.delete(f.seriesKey):C.add(f.seriesKey),C.size===0?P:C}),className:`rounded-md border px-3 py-2 text-left transition-colors ${b?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${S?"cursor-default":""}`,children:A},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:w.map(f=>{const b=f.seriesKey!==null&&a.has(f.seriesKey),S=b&&a.size===1,A=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:b?I[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:A},f.key):e.jsx("button",{type:"button","aria-pressed":b,disabled:S,onClick:()=>r(P=>{const C=new Set(P);return C.has(f.seriesKey)?C.delete(f.seriesKey):C.add(f.seriesKey),C.size===0?P:C}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${S?"cursor-default":"hover:bg-surface-hover"}`,children:A},f.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(sl,{data:m,xKey:"date",series:k,xTickFormatter:fn,labelFormatter:Tt}),e.jsx("ul",{className:"sr-only",children:m.map(f=>e.jsxs("li",{children:[Tt(f.date),":"," ",k.map(b=>`${b.label} ${I[b.dataKey].formatValue(f[b.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(re,{tone:Cv(f.status),children:kv(f.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:un.format(f.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:un.format(f.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Yn(f.totals.costMicros,y)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:li.format(f.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:oi(f.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:f.totals.costMicros>0&&f.totals.conversions===0?e.jsx(re,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:Yn(f.totals.costPerConversionMicros,y)})})]},f.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",oa(Dt(x.capturedAt))," · ","customer ",x.customerId," · ","latest closed day ",Tt(x.asOfDate),x.openDate?e.jsxs(e.Fragment,{children:[" · ",Tt(x.openDate)," still open, excluded"]}):null,x.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",x.timeZone]}):null]})]})]})}const ci=20,Ws=50,Pv=50,Iv=50;function gl(t){return t==="viewer"}function fl(t){return t?.status==="unavailable"}function qd(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Ed(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 lr(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 Tv(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 di(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 Ko(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Go(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 or(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 _i(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function ui(t){return _i(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function Bi({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[l,i]=c.useState(""),[o,d]=c.useState(!1),m=l.trim().toLocaleLowerCase(),u=m?t.filter(y=>y.label.toLocaleLowerCase().includes(m)):t,h=o?u:u.slice(0,Pv),g=h.length<u.length;function x(){const y=new Set([...s,...h.map(p=>p.id)]);n(t.filter(p=>y.has(p.id)).map(p=>p.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:l,onChange:y=>i(y.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h.length===0,onClick:x,children:"Select all shown"}),e.jsx(L,{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 ",h.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:h.map(y=>{const p=s.includes(y.id);return e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-sm text-primary",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{"aria-label":`Select ${y.label}`,checked:p,type:"checkbox",onChange:v=>n(qd(s,y.id,v.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(L,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function yl(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(re,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function bl({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(re,{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 Lv({value:t}){const[s,n]=c.useState(0),[a,r]=c.useState(0),[l,i]=c.useState(null),o=t.preview,d=o?.counts.needsAttention??0,m=o?.rows.filter(S=>S.status==="matched")??[],u=o?.rows??[],h=u.filter(S=>S.status!=="matched"),g=Math.max(1,Math.ceil(u.length/Ws)),x=Math.min(s,g-1),y=u.slice(x*Ws,(x+1)*Ws),p=Math.max(1,Math.ceil(h.length/Ws)),v=Math.min(a,p-1),j=h.slice(v*Ws,(v+1)*Ws),w=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,I=m.length>0&&!t.isApplying,k=o!==null&&l===o.previewChecksum,f=h.length>0&&v===p-1;c.useEffect(()=>{n(0),r(0),i(null)},[o?.previewChecksum]);async function b(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=>{b(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(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!w,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]}),o?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:[o.counts.matchedRows," matched · ",o.counts.groupsReady," group",o.counts.groupsReady===1?"":"s"," ready",d>0?` · ${d} need${d===1?"s":""} attention`:""]}),o.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:o.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,o.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 (",o.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(re,{tone:Ko(S.status),children:Go(S.status)}),or(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:or(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 ",x+1," of ",g," · ",o.rows.length," rows"]}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:x===0,onClick:()=>n(S=>Math.max(0,S-1)),children:"Previous 50 rows"}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:x===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:j.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(re,{tone:Ko(S.status),children:Go(S.status)}),or(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:or(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 ",v+1," of ",p]}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:v===0,onClick:()=>r(S=>Math.max(0,S-1)),children:"Previous 50 exceptions"}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:v===p-1,onClick:()=>r(S=>Math.min(p-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?o.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(L,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!I||!k,onClick:()=>{t.onApply(m.map(S=>S.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${m.length} matched row${m.length===1?"":"s"}`})]}):e.jsx(L,{type:"button",className:"mt-3 min-h-11",disabled:!I,onClick:()=>{t.onApply(m.map(S=>S.dataRow))},children:t.isApplying?"Creating groups…":`Create ${o.counts.groupsReady} group${o.counts.groupsReady===1?"":"s"} with ${m.length} membership${m.length===1?"":"s"}`})]}):null]})}const $v="—";function Mv({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:l=!1,isBusy:i=!1,canContinue:o=!0,onSelectedQueryIdsChange:d,onApplySelectedQueries:m,onClearQueryAssignments:u,onRemoveQuery:h,onCreateQueries:g,onCreateAndPairQuestions:x,isCreatingQueries:y=!1,createQueriesError:p=null,onManageProjectQueries:v,groups:j,audience:w,onAudienceChange:I,assignmentImpact:k=null,isPreviewingAssignmentImpact:f=!1,assignmentImpactError:b=null,onRetryAssignmentImpact:S,assignmentNotice:A=null,onReplaceAssignments:P,isReplacingAssignments:C=!1,onBack:U,onContinue:O}){const[J,V]=c.useState(""),[H,te]=c.useState(!1),[D,$]=c.useState(!1),[Q,B]=c.useState(""),[_,M]=c.useState(""),[W,ne]=c.useState(null);if(fl(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(bl,{message:s.message})});const ie=gl(t),be=w,ke=I,X=lr(be,n,j),le=X.length,je=le>0&&r.length>0&&!l&&!i&&!f&&k!==null&&b===null,ee=u??h,oe=J.trim().toLocaleLowerCase(),G=oe?a.filter(T=>ui(T).toLocaleLowerCase().includes(oe)):a,ue=G.filter(T=>(T.propertyIds?.length??0)===0),se=D?ue:G,Se=H?se:se.slice(0,Iv),Ce=Se.filter(T=>!_i(T)),Ie=[...new Set(Q.split(`
4
- `).map(T=>T.trim()).filter(Boolean))],Be=[..._.matchAll(/\{([a-z][\w-]*)\}/gi)].map(T=>T[1]),qe=n.filter(T=>X.includes(T.id)),pe=Be.length===0||_.trim()===""?[]:qe.map(T=>({propertyId:T.id,text:Be.reduce((ye,Ve)=>ye.replaceAll(`{${Ve}}`,T.label),_.trim())})),F=[...new Set(pe.map(T=>T.text))];function Ke(){const T=new Set([...r,...Ce.map(ye=>ye.id)]);d(a.filter(ye=>T.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."})]})}),ie?e.jsx(yl,{}):null,ie?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:be.kind==="all"?"all":be.kind==="specific"?"specific":`group:${be.groupIds[0]??""}`,onChange:T=>{const ye=T.currentTarget.value;ye==="all"?ke({kind:"all"}):ye==="specific"?ke({kind:"specific",propertyIds:[]}):ye.startsWith("group:")&&ke({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]}),j.length>0?e.jsx("optgroup",{label:"Groups",children:j.map(T=>{const ye=lr({kind:"groups",groupIds:[T.id]},n,j).length;return e.jsx("option",{value:`group:${T.id}`,disabled:ye===0,children:di(T,n)},T.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),be.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:be.groupIds.map(T=>{const ye=j.find(Ve=>Ve.id===T);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:[di(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 Ve=be.groupIds.filter(Ye=>Ye!==ye.id);ke(Ve.length>0?{kind:"groups",groupIds:Ve}:{kind:"all"})},children:"×"})]},ye.id):null})}),j.some(T=>!be.groupIds.includes(T.id)&&lr({kind:"groups",groupIds:[T.id]},n,j).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:T=>{T.currentTarget.value&&ke({kind:"groups",groupIds:[...be.groupIds,T.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"}),j.filter(T=>!be.groupIds.includes(T.id)).map(T=>{const ye=lr({kind:"groups",groupIds:[T.id]},n,j).length;return e.jsx("option",{value:T.id,disabled:ye===0,children:di(T,n)},T.id)})]})]}):null,le===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,be.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(Bi,{legend:"Specific Properties",properties:n,selectedPropertyIds:be.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:T=>{ke({kind:"specific",propertyIds:T})}})}):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."})]}),ie||!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:Q,onChange:T=>B(T.currentTarget.value),placeholder:`best apartments in dallas
5
- luxury apartments atlanta
6
- pet friendly apartments austin`}),p?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:p}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ie.length===0||y||i,onClick:()=>{Promise.resolve(g(Ie)).then(()=>B(""),()=>{})},children:y?"Adding…":`Add ${Ie.length||""} ${Ie.length===1?"query":"queries"}`.replace(" "," ")}),v?e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:v,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:_,onChange:T=>M(T.target.value),placeholder:"apartments near {property}"}),_.trim()===""?null:Be.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:[F.length," ",F.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:F.slice(0,3).map(T=>e.jsx("li",{className:"text-sm text-strong",children:T},T))}),F.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",F.length-3," more"]}):null]}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:pe.length===0||y||i||!x,onClick:()=>{x&&Promise.resolve(x(pe)).then(()=>M(""),()=>{})},children:y?"Adding…":`Add ${pe.length||""} ${pe.length===1?"query":"queries"}`.replace(" "," ")}),pe.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"," ",pe.length," assignment",pe.length===1?"":"s","."]}):null]})]})]}),ie?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(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:Ce.length===0,onClick:Ke,children:"Select all shown queries"}),e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>d([]),children:"Clear query selection"}),e.jsx(L,{type:"button",size:"sm",className:"min-h-11",disabled:!je,onClick:()=>{m({queryIds:r,propertyIds:X,...be.kind==="groups"?{groupIds:be.groupIds}:{}})},children:l?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${Tv(be,j,le)}`.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",be.kind==="groups"?` · ${k.resolvedPropertyCount} unique ${k.resolvedPropertyCount===1?"Property":"Properties"}${k.overlapCount>0?`, ${k.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):b?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:b}),S?e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:S,children:"Retry impact"}):null,U?e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:U,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",le," Properties = ",r.length*le," assignments"]})]}),A?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:A}):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:J,onChange:T=>{V(T.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 ",Se.length," of ",se.length," queries,"," ",G.length-ue.length," of ",G.length," applied"]}),ie||ue.length===0?null:e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{$(T=>!T),te(!1)},children:D?"Show all queries":`Show the ${ue.length} not applied`})]})]}):null,Se.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:[ie?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),ie?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:Se.map(T=>{const ye=_i(T),Ve=ui(T),Ye=r.includes(T.id),et=(T.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[ie?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 ${Ve}`,checked:Ye,type:"checkbox",onChange:xe=>d(qd(r,T.id,xe.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:Ve})}),e.jsx("td",{className:"text-secondary",children:Ed(T.propertyIds??[],n)}),ie?null:e.jsx("td",{className:"text-right",children:et?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[P?e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||C,onClick:()=>ne({queryId:T.id,propertyIds:[...T.propertyIds??[]]}),"aria-label":`Replace query assignments for ${Ve}`,children:"Replace assignments"}):null,e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{ee(T.id)},"aria-label":`Clear query assignments for ${Ve}`,children:"Clear assignments"})]}):null})]},T.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,ie||!W?null:(()=>{const T=a.find(Ye=>Ye.id===W.queryId),ye=T?ui(T):"this query",Ve=W.propertyIds.filter(Ye=>n.some(et=>et.id===Ye));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(Bi,{legend:"Properties for this query",properties:n,selectedPropertyIds:Ve,onSelectedPropertyIdsChange:Ye=>ne(et=>et&&{...et,propertyIds:[...Ye]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:C||i,onClick:()=>ne(null),children:"Keep current assignments"}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ve.length===0||C||i||!P,onClick:()=>{P&&Promise.resolve(P({queryId:W.queryId,propertyIds:Ve}))},children:C?"Replacing assignments…":`Replace with ${Ve.length} ${Ve.length===1?"Property":"Properties"}`})]})]})})(),Se.length<se.length?e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>te(!0),children:"Show all queries"}):null,ie?null:e.jsxs(e.Fragment,{children:[o?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 ${U?"justify-between":"justify-end"}`,children:[U?e.jsx(L,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:U,children:"Back"}):null,e.jsx(L,{type:"button",variant:je?"outline":"default",className:"min-h-11",disabled:!o||i,onClick:O,children:"Continue"})]})]})]})}function qv({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:l=!1,onGroupDraftChange:i,onSaveGroup:o,onEditGroup:d,onRemoveGroup:m,onClearGroupDraft:u,membershipImport:h,onBack:g,onContinue:x}){if(fl(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(bl,{message:s.message})});const y=gl(t),p=r.name.trim().length>0&&r.propertyIds.length>0&&!l,v=n.filter(k=>r.propertyIds.includes(k.id)).length,j=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,w=!y&&(d!==void 0||m!==void 0);function I(){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(yl,{}):null,y||!h?null:e.jsx(Lv,{value:h}),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:[v," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(Bi,{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(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!p,onClick:()=>{o(r)},children:l?"Saving group…":"Save group"}),e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!j,onClick:I,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."})]}),j?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"}),w?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:Ed(k.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:k.competitors.length>0?k.competitors.join(", "):"None"}),w?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[d?e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${k.name}`,onClick:()=>d(k),children:"Edit"}):null,m?e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${k.name}`,onClick:()=>{m(k.id)},children:"Remove"}):null]})}):null]},k.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,y?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${g?"justify-between":"justify-end"}`,children:[g?e.jsx(L,{type:"button",variant:"outline",className:"min-h-11",onClick:g,children:"Back"}):null,e.jsx(L,{type:"button",className:"min-h-11",disabled:j,onClick:x,children:a.length===0&&!j?"Continue without groups":"Continue"})]})]})}function Ev({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:l,onReviewChanges:i,isReviewing:o=!1,canReviewChanges:d=!0,reviewedChanges:m,reviewChangesError:u,canPublish:h,isPublishing:g=!1,onPublish:x}){const[y,p]=c.useState(ci),[v,j]=c.useState(ci),[w,I]=c.useState(ci);if(fl(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(bl,{message:s.message})});const k=gl(t),f=r?.items??[],b=r?.coverageItems??[],S=f.slice(0,y),A=b.slice(0,v),P=a.slice(0,w),C=i!==void 0,U=m!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),k?e.jsx(yl,{}):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(O=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:O.url}),e.jsx("p",{className:"mt-1 text-secondary",children:O.reason})]},`${O.url}-${O.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(L,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>p(O=>O+Ws),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,")"]}),A.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[A.map(O=>e.jsxs("section",{"aria-label":`${O.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:O.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:O.savedUrls.map(J=>e.jsx("li",{className:"break-all text-secondary",children:J},J))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),O.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:O.currentSitemapUrls.map(J=>e.jsx("li",{className:"break-all text-secondary",children:J},J))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},O.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",A.length," of ",b.length]}),A.length<b.length?e.jsx(L,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>j(O=>O+Ws),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(L,{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??$v})]})})]})}),n.providerCalls===void 0?e.jsx("p",{className:"supporting-copy",children:"Review changes to see how many provider requests one run will make."}):null,n.assignments!==void 0&&n.assignments>n.queries?e.jsxs("p",{className:"supporting-copy",children:[n.queries," ",n.queries===1?"query":"queries"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a query aimed at a market is measured on every Property in it."]}):null,m?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:m.title}),m.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:m.items.map((O,J)=>e.jsx("li",{children:O},`${O}-${J}`))}):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:P.map(O=>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:O.title}),O.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:O.detail}):null]}),e.jsx(re,{tone:O.tone??"caution",children:"Needs attention"})]},O.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",P.length," of ",a.length]}),P.length<a.length?e.jsx(L,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>I(O=>O+Ws),children:"Show next 50 exceptions"}):null]})]})]}),k?null:e.jsxs(e.Fragment,{children:[C&&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(L,{type:"button",variant:"outline",className:"min-h-11",onClick:l,children:"Back"}):null,i!==void 0&&!U?e.jsx(L,{type:"button",className:"min-h-11",disabled:o||!d,onClick:()=>{i()},children:o?"Reviewing changes…":"Review changes"}):e.jsx(L,{type:"button",className:"min-h-11",disabled:!h||g,onClick:()=>{x()},children:g?"Publishing setup…":"Publish setup"})]})]})]})}const Dv={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function Ov(t){return t.trim().toLocaleLowerCase()}function Fv(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function Kv({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 Gv({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 o(d,m){n({...s,[d]:m})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":r==="reviewing",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-import-heading",className:"text-lg font-semibold text-heading",children:"Import Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review sitemap entries before choosing the Properties to measure."})]}),t?null:e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm text-secondary",children:[e.jsx(re,{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=>o("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=>o("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=>o("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=>o("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=>o("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=>o("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=>o("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(L,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function _v({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:l,onSelectedPropertyIdsChange:i,onContinue:o,isContinuing:d=!1,onRetryProperties:m,onReturnToImport:u,maxVisibleProperties:h,onShowAllProperties:g}){const x=Ov(a),y=s.filter(P=>Fv(P,x)),p=Math.max(1,h??y.length),v=y.slice(0,p),j=new Set(l),w=s.filter(P=>j.has(P.id)).map(P=>P.id),I=v.length<y.length;function k(P){const C=new Set(P);i(s.filter(U=>C.has(U.id)).map(U=>U.id))}function f(P,C){if(!t||d)return;const U=new Set(w);C?U.add(P):U.delete(P),k(U)}function b(){!t||d||k([...w,...v.map(P=>P.id)])}function S(){!t||d||i([])}function A(){!t||d||w.length===0||o(w)}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(L,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:m,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(L,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:m,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(L,{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:P=>r(P.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(L,{type:"button",variant:"outline",size:"sm",disabled:d,onClick:b,children:"Select all shown"}),e.jsx(L,{type:"button",variant:"ghost",size:"sm",disabled:d||w.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(L,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",v.length," of ",y.length," Properties"]}),e.jsxs("p",{children:[w.length," of ",s.length," selected"]})]}),e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"w-full min-w-150 text-left text-sm","aria-label":"Properties to review",children:[e.jsx("thead",{className:"bg-surface-subtle text-xs font-medium uppercase tracking-wide text-secondary",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-3 py-2",children:"Property"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"URL"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"State"}),t?e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Include"}):null]})}),e.jsx("tbody",{children:v.map(P=>{const C=Dv[P.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:P.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(Kv,{property:P})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(re,{tone:C.tone,children:C.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 ${P.name}`,checked:w.includes(P.id),disabled:d,onChange:U=>f(P.id,U.target.checked),className:"size-6 accent-accent"})})}):null]},P.id)})})]})}),I&&g?e.jsx(L,{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(L,{type:"button",variant:"ghost",disabled:d,onClick:u,children:"Back"}),e.jsx(L,{type:"button",disabled:d||w.length===0,onClick:A,children:d?"Saving Properties…":"Continue"})]}):null]}):null]})}function Bv(t){return t.activeStep==="import"?e.jsx(Gv,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(_v,{...t})}const Uv=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function Vv({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:l}){const i=c.useRef(null),o=c.useRef(null),d=c.useRef(null),m=c.useRef(null),u=c.useRef(!1),[h,g]=c.useState(!1);return c.useEffect(()=>{s||g(!1)},[s]),c.useEffect(()=>{const x=u.current;u.current=h,h?d.current?.focus():x&&m.current?.focus()},[h]),c.useEffect(()=>{const x=i.current;if(i.current=t,x===null||x===t)return;const y=o.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(re,{tone:"caution",children:"Unpublished changes"}),n&&a?h?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(L,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>g(!1),children:"Keep editing"}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(L,{ref:m,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:Uv.map(x=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===x.id?"step":void 0,onClick:()=>r(x.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===x.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:x.label}):e.jsx("span",{"aria-current":t===x.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===x.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:x.label})},x.id))})}),e.jsx("div",{ref:o,children:l})]})}function Hv(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Bv,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(Mv,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(qv,{...t.groups,access:s}):"review"in t?e.jsx(Ev,{...t.review,access:s}):null}function cr(t){return e.jsx(Vv,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Hv(t)})}function Dd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function es(t){return{"If-Match":t,"Idempotency-Key":Dd()}}function Pn(t){return t instanceof En&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function bs(t,s){return t instanceof En?s:(t instanceof Error?t.message.trim():"")||s}function Qv(t){const s="Could not calculate assignment impact.";if(!(t instanceof En)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const zv={loadSetup:t=>kt(()=>ih({client:Y,path:{name:t}})),loadDraft:t=>kt(()=>rh({client:Y,path:{name:t}})),createDraft:(t,s)=>kt(()=>ah({client:Y,path:{name:t},headers:{"Idempotency-Key":Dd()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>kt(()=>nh({client:Y,path:{name:t},headers:es(s),body:n})),applySitemapSelection:(t,s,n,a)=>kt(()=>sh({client:Y,path:{name:t},headers:es(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>kt(()=>th({client:Y,path:{name:t},body:s})),applyAssignments:(t,s,n)=>kt(()=>eh({client:Y,path:{name:t},headers:es(s),body:n})),replaceAssignments:(t,s,n)=>kt(()=>Zm({client:Y,path:{name:t},headers:es(s),body:n})),applyPairedAssignments:(t,s,n)=>kt(()=>Xm({client:Y,path:{name:t},headers:es(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>kt(()=>Jm({client:Y,path:{name:t},headers:es(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>kt(()=>Ym({client:Y,path:{name:t},headers:es(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>kt(()=>Wm({client:Y,path:{name:t},headers:es(s),body:{target:n}})),upsertGroup:(t,s,n)=>kt(()=>zm({client:Y,path:{name:t},headers:es(s),body:{group:n}})),removeGroup:(t,s,n)=>kt(()=>Qm({client:Y,path:{name:t},headers:es(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>kt(()=>Hm({client:Y,path:{name:t},headers:es(s),body:n})),removeCompetitor:(t,s,n,a)=>kt(()=>Vm({client:Y,path:{name:t},headers:es(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>kt(()=>Um({client:Y,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>kt(()=>Bm({client:Y,path:{name:t},headers:es(s),body:n})),compilePreview:t=>kt(()=>_m({client:Y,path:{name:t}})),diffPreview:t=>kt(()=>Gm({client:Y,path:{name:t}})),publish:(t,s,n)=>kt(()=>Km({client:Y,path:{name:t},headers:es(s),body:n})),discard:(t,s)=>kt(()=>Fm({client:Y,path:{name:t},headers:es(s)}))},_o={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},ya={name:"",propertyIds:[],competitorDomains:""},Bo=50;function Na(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Wv(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 Uo(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 Yv(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,o=i.startsWith("*"),d=i.endsWith("*"),m=i.slice(o?1:0,d?-1:void 0).trim();if(!m)throw new Error("Ignored URL patterns must include text besides *.");const u=o&&d?"contains":o?"suffix":d?"prefix":"exact",h=`${u}:${m}`;n.has(h)||(n.add(h),s.push({kind:u,value:m}))}return s}function Jv(t){const s=Wv(t.sitemapUrl),n=t.examplePropertyUrl.trim()?Na(t.examplePropertyUrl):null,a=Na(t.preferredHost)??n??Na(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=Na(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 o=Yv(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:Uo(t)},...r?{aliases:[{host:r,pathTemplate:Uo({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...o.length>0?{excludedSlugPatterns:o}:{}}}}function Xv(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 Zv(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 Vo(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function ej(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function mi(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function Ui(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function Ho(t){return Na(t)}function Od(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 Fd(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 Kd(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Gd(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function tj(t,s){const n=Od(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 sj(t,s){const n=Fd(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=Gd(t.authoring,n.targetKeys[r]);return`${n.label} — ${l}`}return n.label}function nj(t,s){const n=Kd(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${Gd(t.authoring,n.targetKey)} — ${a}`}function aj(t,s){return s.path[0]==="identities"?"Project domain":tj(t,s)??sj(t,s)??nj(t,s)}function Qo(t,s,n){const a=Kd(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 rj(t,s){const n=aj(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,Qo(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,Qo(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 dr(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function _d(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 ij(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${dr(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${dr(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${dr(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${dr(n,"item")} need review.`:s}})()}${_d(a)}`}function lj(t,s){const n=new Map;for(const a of t){const r=rj(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:ij(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function hi(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function xi(t,s,n){const a=Od(n,t.path),r=Fd(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,o=a?.label??r?.label,d=_d(o?[o]:[]),m={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...m,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${d}`};case"excluded-target-has-assignments":return{...m,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${d}`};case"group-unknown-target":return{...m,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${d}`};case"measurement.discovery.proposed_new_target":{const u=hi(a)??"the proposed Property";return{...m,title:"Review a new Property",detail:`Review ${u}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const u=hi(a)??"the proposed Property",h=i?.label??"an existing Property";return{...m,title:"Review a moved Property",detail:`Review ${u}. It may be the same Property as ${h}.`}}case"measurement.discovery.rebind_ambiguous":{const u=hi(a)??"the proposed Property",h=i?.label??"an existing Property";return{...m,title:"Choose an existing Property",detail:`Review ${u}. It may match ${h}; choose the correct Property.`}}default:return{...m,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function oj(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 Fs(t){return[...new Set(t)]}function xn(t){return Fs(t).sort()}function cj(t,s,n){return t.kind==="groups"?{groupKeys:xn(t.groupIds),queryIds:xn(n)}:{targetKeys:xn(t.kind==="all"?s:t.propertyIds),queryIds:xn(n)}}function dj(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 zo(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function uj(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(zo).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(zo).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:Ui(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function mj({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:l,canEdit:i=!0,onCreateQueries:o,onManageProjectQueries:d,onPublished:m,service:u=zv}){const[h,g]=c.useState(null),[x,y]=c.useState(null),[p,v]=c.useState("import"),[j,w]=c.useState(!0),[I,k]=c.useState(null),[f,b]=c.useState(null),[S,A]=c.useState([]),[P,C]=c.useState({..._o}),[U,O]=c.useState("idle"),[J,V]=c.useState(""),[H,te]=c.useState(Bo),[D,$]=c.useState([]),[Q,B]=c.useState([]),[_,M]=c.useState({kind:"all"}),[W,ne]=c.useState(null),[ie,be]=c.useState(null),[ke,X]=c.useState(!1),[le,je]=c.useState(null),[ee,oe]=c.useState(0),[G,ue]=c.useState(null),[se,Se]=c.useState({...ya}),[Ce,Ie]=c.useState(null),[Be,qe]=c.useState(""),[pe,F]=c.useState(null),[Ke,T]=c.useState(!1),[ye,Ve]=c.useState(!1),[Ye,et]=c.useState(null),[xe,ft]=c.useState(null),[ze,nt]=c.useState(null),[as,xt]=c.useState(null),[at,yt]=c.useState(null),At=c.useRef(0),$t=c.useRef(0),He=x?.draft??null,R=x?.etag??null,Ae=c.useMemo(()=>!i&&l?{baseActiveRevision:l.revision,authoring:uj(l)}:null,[i,l]),me=He??Ae;async function Je(K){const ae=++At.current;w(!0),k(null);try{let[Re,he]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);if(!he.draft&&K&&i&&(await u.createDraft(t,Re.activeRevision),[Re,he]=await Promise.all([u.loadSetup(t),u.loadDraft(t)])),ae!==At.current)return;g(Re),y(he),v(Xv(he.draft));const Le=mi(he.draft);$(Le)}catch(Re){if(ae!==At.current)return;k(bs(Re,"Could not load advanced measurement setup."))}finally{ae===At.current&&w(!1)}}c.useEffect(()=>(Je(!0),()=>{At.current+=1}),[t,i,u]),c.useEffect(()=>{!j&&!He&&Ae&&v("properties")},[He,j,Ae]);async function Ft(){const K=await u.loadDraft(t);return y(K),K}async function Kt(K){yt(null);try{const[ae,Re]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);g(ae),y(Re);const he=mi(Re.draft);$(he),v(Le=>Zv(Re.draft,Le)),b(K)}catch(ae){b(bs(ae,K))}}async function ut(K,ae,Re,he={}){const{preserveBusyAction:Le=!1}=he;if(!i||!R||ze&&!Le)return null;Le||nt(K),b(null),yt(null);try{const Qe=await ae(R),gt=await Ft();return A((Qe.warnings??[]).map((Nt,ms)=>xi(Nt,ms,gt.draft?.authoring))),gt}catch(Qe){return Pn(Qe)?await Kt("This setup changed in another session. The latest draft is loaded; review your changes again."):b(bs(Qe,Re)),null}finally{Le||nt(null)}}const Z=c.useMemo(()=>(me?.authoring.targets??[]).map(K=>{const ae=Vo(K);return{id:K.stableKey,name:K.label,url:ae[0]??"No URL",urls:ae,state:ej(K.status)}}),[me]),Ge=c.useMemo(()=>me?.authoring.targets.filter(K=>K.status==="included")??[],[me]),Te=c.useMemo(()=>Ge.map(K=>({id:K.stableKey,label:K.label,urlCount:Vo(K).length})),[Ge]),Pe=me?.authoring.assignments.length??0,Gt=c.useMemo(()=>{if(!me)return[];const K=new Set(s.map(he=>he.id)),ae=s.map(he=>({id:he.id,text:he.query,source:"saved-project-queries",propertyIds:Fs(me.authoring.assignments.filter(Le=>Le.queryId===he.id).map(Le=>Le.targetKey))})),Re=Fs(me.authoring.assignments.map(he=>he.queryId).filter(he=>!K.has(he))).map(he=>({id:he,source:"unavailable-tracked-query",state:"missing",propertyIds:Fs(me.authoring.assignments.filter(Le=>Le.queryId===he).map(Le=>Le.targetKey))}));return[...ae,...Re]},[s,me]),St=c.useMemo(()=>(me?.authoring.groups??[]).map(K=>({id:K.stableKey,name:K.label,propertyIds:K.targetKeys,competitors:K.competitors.map(ae=>ae.domain)})),[me]),rs=c.useMemo(()=>{if(Q.length===0)return null;const K=cj(_,Te.map(Re=>Re.id),Q);return(K.groupKeys?.length??K.targetKeys?.length??0)>0?K:null},[_,Te,Q]),it=rs?JSON.stringify(rs):"";c.useEffect(()=>{const K=rs,ae=++$t.current;if(!i||!He||!R||!K){ne(null),be(null),je(null),X(!1);return}ne(null),be(null),je(null),X(!0);const Re=window.setTimeout(()=>{u.previewAssignments(t,K).then(he=>{if(ae===$t.current){if(he.draftEtag!==R){ne(null),be(null),je("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}ne(he),be(it)}}).catch(he=>{ae===$t.current&&(ne(null),be(null),je(Qv(he)))}).finally(()=>{ae===$t.current&&X(!1)})},250);return()=>{window.clearTimeout(Re),$t.current+=1}},[rs,it,ee,i,He,R,t,u]);const _t=c.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"}]:[],...me?.authoring.assignments.some(K=>K.queryClass==="unclassified")&&!(Ae&&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,Ae,l,S,me]),cs=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 Is(K){let ae;try{ae=Jv(K)}catch(he){b(bs(he,"Check the sitemap details and try again."));return}C(K),O("reviewing");const Re=await ut("import",he=>u.importSitemap(t,he,ae),"Could not review this sitemap.");if(Re?.draft){const he=Re.draft.authoring.targets.filter(Qe=>Qe.status==="proposed").map(Qe=>Qe.stableKey),Le=Re.draft.authoring.targets.filter(Qe=>Qe.status==="included").map(Qe=>Qe.stableKey);$([...Le,...he]),V(""),te(Bo),v("properties"),O("idle")}else O("error")}async function Ts(K){if(!o||K.length===0||ze)return[];nt("create-queries"),xt(null);try{return await o(K)}catch(ae){throw xt(Pt(ae)),ae}finally{nt(null)}}async function Ls(K){if(!He||!R||ze)return;const ae=new Set(K),he=He.authoring.targets.filter(Qe=>Qe.status==="proposed"&&Qe.discoveryIdentity).map(Qe=>({discoveryIdentity:Qe.discoveryIdentity,action:ae.has(Qe.stableKey)?"create":"ignore"})),Le=he.length>0||He.authoring.targets.some(Qe=>Qe.status!=="proposed"&&Qe.status==="included"!==ae.has(Qe.stableKey));nt("properties"),b(null),yt(null);try{if(!Le){$([...ae]),M({kind:"all"}),v("groups");return}await u.applySitemapSelection(t,R,he,[...ae]);const Qe=await Ft(),gt=mi(Qe.draft);$(gt),M({kind:"all"}),v("groups")}catch(Qe){Pn(Qe)?await Kt("This setup changed in another session. The latest Properties are loaded."):b(bs(Qe,"Could not save the selected Properties."))}finally{nt(null)}}async function nn(K){const ae=K.groupIds&&K.groupIds.length>0?{groupKeys:xn(K.groupIds),queryIds:xn(K.queryIds)}:{targetKeys:xn(K.propertyIds),queryIds:xn(K.queryIds)};if(!W||ie!==JSON.stringify(ae)||!R||W.draftEtag!==R){b("Review the latest assignment impact before assigning queries.");return}await ut("assignments",he=>u.applyAssignments(t,he,ae),"Could not apply these queries.")&&(B([]),ue(`${W.assignments.added} new assignment${W.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function jt(K){if(K.propertyIds.length===0)return;await ut("replace-assignments",Re=>u.replaceAssignments(t,Re,{targetKeys:Fs(K.propertyIds),queryIds:[K.queryId]}),"Could not replace this query assignment.")&&(B(Re=>Re.filter(he=>he!==K.queryId)),ue("Query assignments replaced."))}async function Ss(K,ae=!1){if(K.length===0)return;if(!await ut("paired-assignments",he=>u.applyPairedAssignments(t,he,[...K]),"Could not assign these queries.",{preserveBusyAction:ae}))throw new Error("Could not assign these queries.")}async function st(K){if(!(!i||!o||K.length===0||ze)){nt("create-and-pair-questions"),xt(null);try{let ae;try{ae=await o(Fs(K.map(Le=>Le.text)))}catch(Le){throw xt(Pt(Le)),Le}const Re=new Map(ae.map(Le=>[Le.query,Le.id])),he=K.map(Le=>({targetKey:Le.propertyId,queryId:Re.get(Le.text)})).filter(Le=>Le.queryId!==void 0);if(he.length!==K.length){const Le=new Error("The created queries could not be matched to their Properties.");throw xt("The queries were added, but could not be paired with every Property. Try again to pair them."),Le}try{await Ss(he,!0)}catch(Le){throw xt("The queries were added, but could not be assigned to their Properties. Try again to pair them."),Le}}finally{nt(null)}}}async function zt(K){if(!He)return;const ae=Fs(He.authoring.assignments.filter(he=>he.queryId===K).map(he=>he.targetKey));if(ae.length===0)return;await ut(`remove-${K}`,he=>u.removeAssignment(t,he,ae,K),"Could not clear this query assignment.")&&B(he=>he.filter(Le=>Le!==K))}async function ds(K){if(!He||!R||ze)return;const ae=K.name.trim();if(!ae)return;const Re=Ce??Ui(ae,"group"),he=He.authoring.groups.find(Nt=>Nt.stableKey===Re);if(he&&Ce===null){b(`A group named "${he.label}" already exists. Edit it or choose a different name.`);return}const Le=K.competitorDomains.split(/[\s,]+/).map(Nt=>Nt.trim()).filter(Boolean),Qe=Le.find(Nt=>Ho(Nt)===null);if(Qe){b(`"${Qe}" is not a valid competitor domain.`);return}const gt=Fs(Le.map(Nt=>Ho(Nt)));nt("group"),b(null),yt(null);try{const Nt=await u.upsertGroup(t,R,{stableKey:Re,label:ae,targetKeys:Fs(K.propertyIds),competitors:gt.map(E=>he?.competitors.find(Ne=>Ne.domain===E)??{stableKey:Ui(E,"competitor"),label:E,domain:E,aliases:[]})}),ms=await Ft();A(Nt.warnings.map((E,Ne)=>xi(E,Ne,ms.draft?.authoring))),Se({...ya}),Ie(null)}catch(Nt){Pn(Nt)?await Kt("This setup changed in another session. The latest groups are loaded."):b(bs(Nt,"Could not save this group."))}finally{nt(null)}}function ps(K){const ae=He?.authoring.groups.find(Re=>Re.stableKey===K);ae&&(Ie(K),Se({name:ae.label,propertyIds:[...ae.targetKeys],competitorDomains:ae.competitors.map(Re=>Re.domain).join(", ")}))}async function Cs(K){await ut("remove-group",Re=>u.removeGroup(t,Re,K),"Could not remove this group.")&&(M(Re=>Re.kind==="groups"&&Re.groupIds.includes(K)?{kind:"all"}:Re),Ce===K&&(Ie(null),Se({...ya})))}function Rt(K){qe(K),F(null),et(null),ft(null)}async function Mt(){if(!(!i||!Be.trim()||Ke||ye)){T(!0),et(null),ft(null);try{F(await u.previewGroupMembership(t,{csv:Be}))}catch(K){F(null),et(bs(K,"Could not review this CSV."))}finally{T(!1)}}}async function us(K){if(!(!i||!R||!pe||K.length===0||ze)){if(pe.draftEtag!==R){et("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}Ve(!0),nt("group-import"),et(null),ft(null),yt(null);try{const ae=await u.applyGroupMembership(t,R,{csv:Be,sourceChecksum:pe.sourceChecksum,previewChecksum:pe.previewChecksum,acceptedRows:Fs(K.map(String)).map(Number)}),Re=await Ft();A(ae.warnings.map((he,Le)=>xi(he,Le,Re.draft?.authoring))),qe(""),F(null),ft(`${ae.addedMemberships} membership${ae.addedMemberships===1?"":"s"} added${ae.unchangedMemberships>0?`; ${ae.unchangedMemberships} already present`:""}.`)}catch(ae){Pn(ae)?(await Kt("This setup changed in another session. The latest draft is loaded; review the CSV again."),et("The setup changed while this CSV was open. Review the latest CSV before applying it.")):et(bs(ae,"Could not apply this CSV."))}finally{nt(null),Ve(!1)}}}async function Wt(){if(!(!He||!R||ze||Pe===0)){nt("review"),b(null),yt(null);try{const[K,ae]=await Promise.all([u.compilePreview(t),u.diffPreview(t)]),Re=[...K.checks,...ae.checks],he=Re.some(Le=>Le.ruleId==="active-revision-schema-v1");if(A(lj(Re.filter(Le=>Le.ruleId!=="active-revision-schema-v1"),{authoring:me?.authoring,queries:s})),!K.ok||!ae.ok)return;if(ae.diff.activeRevision!==He.baseActiveRevision){await Kt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(K.compiledChecksum!==ae.compiledChecksum){b("The setup changed while it was being reviewed. Review the latest changes again.");return}yt({etag:R,baseActiveRevision:He.baseActiveRevision,compiledChecksum:K.compiledChecksum,changes:oj(ae.diff,he),providerCalls:K.plan.executionNodes.reduce((Le,Qe)=>Le+Qe.expectedSnapshots,0)})}catch(K){b(bs(K,"Could not review this setup."))}finally{nt(null)}}}async function an(){if(!(!He||!R||!at||ze)){if(R!==at.etag||He.baseActiveRevision!==at.baseActiveRevision){yt(null),b("The setup changed after review. Review the latest changes before publishing.");return}nt("publish"),b(null);try{await u.publish(t,R,{expectedActiveRevision:at.baseActiveRevision,expectedCompiledChecksum:at.compiledChecksum}),y({draft:null,etag:null}),yt(null),m?.()}catch(K){Pn(K)?await Kt("The setup changed before it could be published. Review the latest draft and publish again."):b(bs(K,"Could not publish this setup."))}finally{nt(null)}}}async function Ct(){if(!(!R||ze)){nt("discard"),b(null);try{await u.discard(t,R),y({draft:null,etag:null}),yt(null),m?.()}catch(K){Pn(K)?await Kt("This setup changed in another session. The latest draft is loaded."):b(bs(K,"Could not discard these changes."))}finally{nt(null)}}}async function is(){if(!(!He||!R||!h||ze)){nt("restart"),b(null),yt(null);try{await u.discard(t,R),await u.createDraft(t,h.activeRevision),C({..._o}),V(""),$([]),B([]),M({kind:"all"}),ne(null),je(null),ue(null),Se({...ya}),Ie(null),qe(""),F(null),et(null),ft(null),await Je(!1)}catch(K){Pn(K)?await Kt("The setup changed again. Reloaded the latest draft and published setup."):b(bs(K,"Could not restart this setup."))}finally{nt(null)}}}if(j)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(I)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:I}),e.jsx(L,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Je(!0)},children:"Try again"})]})]});if(!me||i&&!R)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&&He&&h&&He.baseActiveRevision!==h.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(L,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:ze==="restart",onClick:()=>{is()},children:ze==="restart"?"Restarting…":"Discard draft and restart"})]}),f?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:f}):null]});const bt=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(L,{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:[h?.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,bt,p==="import"||p==="properties"?e.jsx(cr,{currentStep:p,hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:v,onDiscard:()=>{Ct()},importProperties:{importDraft:P,onImportDraftChange:K=>{C(K),O("idle"),b(null)},onReviewSitemap:K=>{Is(K)},reviewState:U,properties:Z,propertiesState:"ready",propertiesSearch:J,onPropertiesSearchChange:V,maxVisibleProperties:H,onShowAllProperties:()=>te(Z.length),selectedPropertyIds:D,onSelectedPropertyIdsChange:K=>$([...K]),onContinue:K=>{Ls(K)},isContinuing:ze==="properties",onRetryProperties:()=>{Ft()},onReturnToImport:()=>v("import")}}):p==="queries"?e.jsx(cr,{currentStep:"queries",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:v,onDiscard:()=>{Ct()},onManageProjectQueries:d,queries:{onCreateQueries:o?K=>Ts(K):void 0,isCreatingQueries:ze==="create-queries"||ze==="create-and-pair-questions",isBusy:ze!==null,createQueriesError:as,availability:cs,properties:Te,queries:Gt,selectedQueryIds:Q,isApplying:ze==="assignments"||ze==="paired-assignments",onSelectedQueryIdsChange:K=>B([...K]),onApplySelectedQueries:K=>nn(K),groups:St,audience:_,onAudienceChange:K=>{M(K),ue(null)},assignmentImpact:W&&ie===it&&W.draftEtag===R?dj(W):null,isPreviewingAssignmentImpact:ke,assignmentImpactError:le,onRetryAssignmentImpact:()=>oe(K=>K+1),assignmentNotice:G,onReplaceAssignments:jt,isReplacingAssignments:ze==="replace-assignments",onCreateAndPairQuestions:i&&o?st:void 0,onClearQueryAssignments:zt,onRemoveQuery:zt,canContinue:Pe>0,onBack:()=>v("groups"),onContinue:()=>v("review")}}):p==="groups"?e.jsx(cr,{currentStep:"groups",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:v,onDiscard:()=>{Ct()},groups:{properties:Te,groups:St,groupDraft:se,isSaving:ze==="group",onGroupDraftChange:Se,onSaveGroup:ds,onEditGroup:K=>ps(K.id),onRemoveGroup:Cs,onClearGroupDraft:()=>{Ie(null),Se({...ya})},membershipImport:{csv:Be,preview:pe,isReviewing:Ke,isApplying:ye,error:Ye,notice:xe,onCsvChange:Rt,onReview:Mt,onApply:us},onBack:()=>{v("properties")},onContinue:()=>v("queries")}}):e.jsx(cr,{currentStep:"review",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:v,onDiscard:()=>{Ct()},review:{counts:{properties:Ge.length,queries:new Set(me.authoring.assignments.map(K=>K.queryId)).size,groups:me.authoring.groups.length,assignments:me.authoring.assignments.length,providerCalls:at?.providerCalls},flaggedExceptions:_t,reviewedChanges:at?.changes,isReviewing:ze==="review",canReviewChanges:Pe>0&&!ze,onReviewChanges:Wt,onBack:()=>v("queries"),canPublish:at!==null&&!ze,isPublishing:ze==="publish",onPublish:an}})]})}const hj=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function Wo(t){return t.label!=="Complete"}const In="__all_properties__",xj=50,Bd=50,pj=20,gj=50,fj=250,yj=5,bj=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],vj={"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"},Ud={plan_v1:"Setup update required.",no_completed_run:"Not measured yet.",no_population:"No matching queries.",evidence_incomplete:"Evidence incomplete.",identity_ambiguous:`${Ll}.`,"identity-ambiguous":`${Ll}.`,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."},jj={numerator:null,denominator:null,reason:"plan_v1"};function ea(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 Nj(t){return ea(t)?`${t.numerator} of ${t.denominator} (${Fe(t.numerator/t.denominator)})`:"N/A"}function Vd(t){if(ea(t))return"";const s=t.reason??"unavailable";return Ud[s]??s}function Yo(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 wj(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function Sj(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function Cj(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function wa({metric:t,compact:s=!1}){const n=s?ea(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":ea(t)?"text-lg font-semibold text-heading":"text-lg font-semibold text-secondary",a=ea(t)?Pr(t):null;return e.jsxs("span",{className:"inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums",...ea(t)?{}:{title:Vd(t)},children:[e.jsx("span",{className:n,children:Nj(t)}),a?e.jsx("span",{className:"text-xs text-secondary",children:a}):null]})}function vl({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(L,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Jo({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,l]=c.useState(Bd),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((o,d)=>e.jsx("li",{className:a,children:o},`${o}:${d}`))}),e.jsx(vl,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>l(Number.MAX_SAFE_INTEGER)})]})]})}function kj({evidence:t,state:s="ready",onRetry:n}){const[a,r]=c.useState(Bd),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(L,{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(re,{tone:i.tone,children:vj[i.kind]}),i.historical?e.jsx(re,{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(vl,{shown:l.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function Aj({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Jo,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Jo,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(kj,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function Rj({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(wa,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function Xo({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function l(i){if(r)return;const o=n.findIndex(u=>u.value===s);let d=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?d=(o+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?d=(o-1+n.length)%n.length:i.key==="Home"?d=0:i.key==="End"&&(d=n.length-1),d===null)return;i.preventDefault();const m=n[d];a(m.value),i.currentTarget.querySelectorAll('[role="radio"]')[d].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:l,children:n.map(i=>{const o=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":o,tabIndex:o?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${o?"segmented-option-active":""}`,children:i.label},i.value)})})}function Pj({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(_e,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function Ij({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:l=!1,isViewLoading:i=!1,isLoadingMore:o=!1,isLoadMoreError:d=!1,viewSearch:m,onViewChange:u,onLoadMore:h,onPropertyExpand:g,onRetryEvidence:x,renderPropertyLink:y}){const p=t.currentView!=null,v=t.classReporting==="available"&&(p||t.classScopes!=null),[j,w]=c.useState(t.currentView?.queryClass??"all"),[I,k]=c.useState(t.currentView?.scope.key??In),[f,b]=c.useState(m??""),[S,A]=c.useState(xj),[P,C]=c.useState(pj),[U,O]=c.useState(t.currentView?.sort??"label-asc"),[J,V]=c.useState(null),H=c.useRef(m??""),te=v&&!p&&j!=="all"?j==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,D=p?{aggregate:t.currentView.aggregate,groups:[]}:te,$=c.useCallback(F=>{if(!p||!u)return;const Ke=F.scope??(I===In?"all":"group"),T=F.search??f;H.current=T,u({scope:Ke,...Ke==="group"?{groupKey:F.groupKey??I}:{},queryClass:F.queryClass??j,...T?{search:T}:{},...F.sort?{sort:F.sort}:{}})},[u,f,j,I,p]);c.useEffect(()=>{!t.currentView||i||(w(t.currentView.queryClass),k(t.currentView.scope.key??In),t.currentView.sort&&O(t.currentView.sort))},[i,t.currentView]),c.useEffect(()=>{m!==void 0&&(H.current=m,b(F=>F.trim()===m.trim()?F:m))},[m]),c.useEffect(()=>{if(!p||!u||f===H.current)return;const F=window.setTimeout(()=>$({search:f}),fj);return()=>window.clearTimeout(F)},[u,$,f,p]);const Q=t.availableGroups??D.groups;c.useEffect(()=>{I===In||Q.some(F=>F.id===I)||k(In)},[Q,I]);const B=p?void 0:D.groups.find(F=>F.id===I),_=B?.aggregate??D.aggregate,M=F=>v?F:jj,W=U,ne=f.trim().toLocaleLowerCase(),ie=c.useMemo(()=>!p&&ne?_.properties.filter(F=>F.name.toLocaleLowerCase().includes(ne)):_.properties,[_.properties,ne,p]),be=p?ie:ie.slice(0,S),ke=(p?t.currentView?.scope.kind==="group":B!=null)&&j==="non-brand"&&v&&(p||B.confirmedCompetitorCount>0)&&(_.shareOfVoice?.length??0)>0,X=v?_.unavailablePropertyCount??0:0,le=t.flaggedResults.reduce((F,Ke)=>F+(Ke.count??1),0),je=t.flaggedResultsTotal??le,ee=[M(_.metrics.propertiesMentioned),M(_.metrics.mentionCoverage),M(_.metrics.citationCoverage)].map(Vd).find(Boolean),oe=v?t.nextActionText??ee??(X>0?`${X} ${X===1?"property is":"properties are"} unavailable.`:je>0?`${je} flagged ${je===1?"result needs":"results need"} review.`:null):Ud.plan_v1,se=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?wj(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Se=Sj(t.latestMeasurement.date),Ce=[{value:In,label:"All properties"},...Q.map(F=>({value:F.id,label:F.label}))],Ie=Q.length>yj;function Be(F){k(F),$(F===In?{scope:"all"}:{scope:"group",groupKey:F})}function qe(F){w(F),$({queryClass:F})}function pe(F){const Ke=J!==F;V(Ke?F:null),Ke&&g?.(F)}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(re,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(re,{tone:"caution",children:"Includes historical data"}):null,se?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:se}):null,Se?e.jsx("span",{className:"text-sm text-secondary",children:Se}):null,oe?e.jsx("span",{className:"text-sm text-secondary",children:oe}):null,s&&v&&n?e.jsx(L,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!v?e.jsx(L,{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:Ie?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),Ie?e.jsx("select",{id:"advanced-measurement-group",value:I,onChange:F=>Be(F.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:Ce.map(F=>e.jsx("option",{value:F.value,children:F.label},F.value))}):e.jsx(Xo,{ariaLabelledBy:"advanced-measurement-group-label",value:I,options:Ce,onChange:Be})]}),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(Xo,{ariaLabelledBy:"advanced-measurement-class-label",value:j,options:bj,onChange:qe,disabled:!v})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:f,onChange:F=>b(F.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&&ke?e.jsx(Rj,{values:_.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(_e,{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??ie.length," ",(t.currentView?.propertyTotal??ie.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(Pj,{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:[hj.map(F=>{const Ke=W.startsWith(`${F.key}-`),T=Ke&&W.endsWith("-desc")?"descending":Ke?"ascending":"none";return e.jsx("th",{"aria-sort":T,className:(F.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=`${F.key}-${Ke&&W.endsWith("-asc")?"desc":"asc"}`;O(ye),$({sort:ye})},"aria-label":`Sort by ${F.label.toLowerCase()}`,children:[F.label,e.jsx(ra,{className:`h-3 w-3 transition-transform ${Ke?"opacity-100":"opacity-0"} ${T==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):F.label},F.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[be.map(F=>{const Ke=J===F.id;return e.jsxs(c.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:T=>{Cj(T.target)||pe(F.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[y?y({id:F.id,name:F.name}):F.name,Wo(F.status)||F.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[Wo(F.status)?e.jsx(re,{tone:F.status.tone,children:F.status.label}):null,F.historical?e.jsx(re,{tone:"caution",children:"Historical"}):null]}):null,Yo(F)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Yo(F)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(wa,{metric:F.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(wa,{metric:F.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(L,{size:"icon",variant:"ghost","aria-expanded":Ke,"aria-label":Ke?`Hide details for ${F.name}`:`Show details for ${F.name}`,onClick:()=>pe(F.id),children:e.jsx(ra,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${Ke?"rotate-180":""}`,"aria-hidden":"true"})})})]},F.id),Ke?(F.providers??[]).map(T=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:T.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(wa,{metric:T.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(wa,{metric:T.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${F.id}:${T.provider}`)):null,Ke?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(Aj,{property:F,onRetryEvidence:x})})},`${F.id}:details`):null]},F.id)}),be.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]})]})}),p&&t.currentView.nextCursor&&h?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",be.length," of ",t.currentView.propertyTotal]}),d?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(L,{size:"sm",variant:"outline",disabled:o,onClick:()=>h(t.currentView.nextCursor),children:o?"Loading…":d?"Retry loading more properties":"Show 50 more"})]}):p?be.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",be.length," of ",t.currentView.propertyTotal]}):null:e.jsx(vl,{shown:be.length,total:ie.length,itemLabel:"properties",onShowAll:()=>A(Number.MAX_SAFE_INTEGER)})]}),!i&&!ne&&je>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 (",je,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,P).map(F=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(re,{tone:F.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:F.property}),e.jsx("span",{className:"text-secondary",children:F.summary})]},F.id))}),P<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,P).reduce((F,Ke)=>F+(Ke.count??1),0)," of ",je," flagged results"]}),e.jsx(L,{size:"sm",variant:"outline",onClick:()=>C(F=>Math.min(t.flaggedResults.length,F+gj)),children:"Show 50 more"})]}):le<je?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",le," of ",je," flagged results"]}),p&&t.currentView.nextCursor&&h?e.jsx(L,{size:"sm",variant:"outline",disabled:o,onClick:()=>h(t.currentView.nextCursor),children:o?"Loading…":d?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function Hd(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function Tj(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 Lj({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:l,onRunMeasurement:i,onRetryReport:o,onViewChange:d,onLoadMore:m,onPropertyExpand:u,onRetryEvidence:h,renderPropertyLink:g,isRunningMeasurement:x,isOpeningSetup:y,isViewLoading:p,isLoadingMore:v,isLoadMoreError:j,viewSearch:w}){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(L,{type:"button",size:"sm",disabled:y,onClick:l,children:y?"Opening setup…":Hd(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."}),o?e.jsx(L,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:o,children:"Retry report"}):null]}):a?e.jsx(Ij,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:l,onViewChange:d,onLoadMore:m,onPropertyExpand:u,onRetryEvidence:h,renderPropertyLink:g,isRunningMeasurement:x,isRepublishingSetup:y,isViewLoading:p,isLoadingMore:v,isLoadMoreError:j,viewSearch:w}):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 Jn={numerator:null,denominator:null,reason:"plan_v1"};function $j(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Zo(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 Mj(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function qj(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Ej(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 Dj(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function Oj(t){const s=new Map;for(const n of t){const a=Dj(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function Fj(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 p=l.get(y.targetKey)??[];p.push(...y.queryIds.map(v=>r.get(v)).filter(v=>!!v)),l.set(y.targetKey,[...new Set(p)])}const i=Oj(s.evidence),o=n.executionNodes.reduce((y,p)=>y+p.expectedSnapshots,0),d=s.run?.status==="completed"&&o>0,m=d?o:0,u=d?o:0,h=s.targets.map(y=>{const p=a.get(y.id),v=i.get(y.id)??[],j=v.map(k=>({id:`${k.observationId}:${k.usageEdgeId}:${k.sourceUrl}`,kind:Mj(k.classification),query:k.queryText,url:k.sourceUrl,tone:qj(k.classification),historical:k.historical||k.bridged})),w=v.some(k=>k.historical||k.bridged),I=s.run?y.completeness.complete?p?.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:Zo(y.mentionCoverage),citationCoverage:Zo(y.citationCoverage),status:I,assignedQueries:l.get(y.id)??[],urls:p?.urls.map($j)??[],evidence:j,historical:w}}),g=new Map(h.map(y=>[y.id,y])),x=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:m,totalSlots:u,date:Ej(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Jn,mentionCoverage:Jn,citationCoverage:Jn},properties:h},groups:s.groups.map(y=>({id:y.id,label:y.label,confirmedCompetitorCount:x.get(y.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Jn,mentionCoverage:Jn,citationCoverage:Jn},properties:y.targetIds.map(p=>g.get(p)).filter(p=>!!p)}}))},flaggedResults:[]}}function ec({rate:t}){const s=Pr(t);return e.jsxs("td",{children:[e.jsx("strong",{children:dh(t)}),e.jsx("p",{className:"text-xs text-secondary",children:uh(t)}),s?e.jsx("p",{className:"text-xs text-secondary",children:s}):null]})}function Kj({visibility:t}){const s=t.populations.filter(a=>a.queryClass!=="unknown"||a.summary.answerCount>0),n=t.populations.filter(a=>a.queryClass!=="unknown"||a.trend.some(r=>r.answerCount>0));return e.jsxs("section",{id:"client-summary","data-report-section":"client-summary",className:"page-section-divider","aria-label":Yt.title,children:[e.jsx("h2",{className:"text-xl font-semibold text-heading",children:Yt.title}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:t.selection.mode==="advanced"?Yt.description:Yt.simpleDescription}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:lh(t)}),e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsx("tr",{children:[Yt.queryType,Yt.queries,Yt.answers,Yt.mentioned,Yt.cited].map(a=>e.jsx("th",{children:a},a))})}),e.jsx("tbody",{children:s.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:$l(a.queryClass)}),e.jsx("td",{children:a.summary.queryCount}),e.jsx("td",{children:a.summary.answerCount}),[a.summary.mentionCoverage,a.summary.citationCoverage].map((r,l)=>e.jsx(ec,{rate:r},l))]},a.queryClass))})]})}),e.jsxs("details",{className:"mt-4",children:[e.jsx("summary",{className:"cursor-pointer text-sm text-secondary",children:oh(t)}),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.jsx("tr",{children:[Yt.date,Yt.queryType,Yt.mentioned,Yt.cited,Yt.comparison].map(a=>e.jsx("th",{children:a},a))})}),e.jsx("tbody",{children:n.flatMap(a=>a.trend.map(r=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("time",{dateTime:r.createdAt,children:r.createdAt.slice(0,10)})}),e.jsx("td",{children:$l(a.queryClass)}),[r.mentionCoverage,r.citationCoverage].map((l,i)=>e.jsx(ec,{rate:l},i)),e.jsx("td",{children:ch(r.continuity.state,r.continuity.comparedRunId!==null&&!a.trend.some(l=>l.runId===r.continuity.comparedRunId))})]},`${a.queryClass}:${r.runId}`)))})]})})]})]})}const Gj="Report audience",_j={client:"Client",agency:"Agency"},Bj=["client","agency"],tn={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-heading"},Uj={positive:"bg-positive-500/70",caution:"bg-caution-500/70",negative:"bg-negative-500/70",neutral:"bg-mono-500/70"},jl={positive:tn.positive,caution:tn.caution,negative:tn.negative,neutral:""};function qn(t,s,n){const a=yx(t,s,n);return a?e.jsx("span",{className:jl[Oc(t.deltaPct)]||void 0,children:a}):null}function Qd(t){const s=t.filter(Boolean);if(s.length!==0)return s.map((n,a)=>e.jsxs("span",{children:[a>0?" · ":null,n]},a))}const pi=new Set;function gi({title:t,subtitle:s,children:n}){return e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:Pc.eyebrow}),e.jsx("h1",{className:"page-title",children:t}),s?e.jsx("p",{className:"page-subtitle",children:s}):null,n]})}function Vj({projectName:t,projectTitle:s}){const[n,a]=c.useState(!1),[r,l]=c.useState(null),[i,o]=c.useState(mh),[d,m]=c.useState("client"),u=ce(),h=u?"client":d,[g,x]=c.useState(()=>({project:t,refs:pi}));g.project!==t&&x({project:t,refs:pi});const y=g.project===t?g.refs:pi,p=hh(),v=f=>{const b=f.targetRef;if(!b)return;const S=A=>new Set(A.project===t?A.refs:[]);x(A=>({project:t,refs:S(A).add(b)})),p.mutate({projectName:t,body:{targetRef:b}},{onSuccess:()=>{Oe({tone:"positive",title:`Dismissed "${f.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:A=>{Oe({tone:"negative",title:`Couldn't dismiss "${f.title}"`,detail:String(A)}),x(P=>{const C=S(P);return C.delete(b),{project:t,refs:C}})}})},j=Me({...xh({client:Y,path:{name:t},query:{period:i}}),placeholderData:Ar});async function w(){a(!0),l(null);try{await vh(t,h,i)}catch(f){const b=f instanceof En||f instanceof Error?f.message:"Download failed";l(b)}finally{a(!1)}}const I=s||t;if(j.isLoading)return e.jsxs("div",{children:[e.jsx("div",{className:"page-header",children:e.jsx(gi,{title:I})}),e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"})]});if(j.error){const f=j.error instanceof Error?j.error.message:"Failed to load report";return e.jsxs("div",{children:[e.jsx("div",{className:"page-header",children:e.jsx(gi,{title:I})}),e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-negative-400",children:f})})]})}const k=j.data;return k?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsx(gi,{title:k.meta.project.displayName,subtitle:e.jsxs(e.Fragment,{children:[k.meta.project.canonicalDomain," · ",k.meta.project.country," / ",k.meta.project.language.toUpperCase()," · ",k.visibility?.selection.mode==="advanced"?ph(k.visibility):gh(k.meta.location)," · ",fh(k.meta.periodDays)," · ",Pc.generated," ",Ic(k.meta.generatedAt)]}),children:r?e.jsx("p",{className:"mt-2 text-xs text-negative-400",children:r}):null}),e.jsxs("div",{className:"page-header-right flex flex-col items-end gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[!u&&e.jsx(Hj,{audience:h,onChange:m}),e.jsx(Wj,{period:i,onChange:o})]}),e.jsxs(L,{variant:"secondary",size:"sm",onClick:tt(w),disabled:n,children:[e.jsx(Yc,{className:"size-4"}),n?"Preparing…":"Download report HTML"]})]})]}),yh(k,h).map(f=>e.jsx(Qj,{id:f,report:k,audience:h,dismissedRefs:y,onDismiss:v},f))]}):null}function Hj({audience:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":Gj,children:Bj.map(n=>{const a=n===t;return e.jsx("button",{type:"button",onClick:()=>s(n),"aria-pressed":a,className:`segmented-option ${a?"segmented-option-active":""}`,children:_j[n]},n)})})}function Qj({id:t,report:s,audience:n,dismissedRefs:a,onDismiss:r}){switch(t){case Ee["client-summary"]:return s.visibility?e.jsx(Kj,{visibility:s.visibility}):e.jsx(Jj,{report:s});case Ee["executive-summary"]:return e.jsx(aN,{report:s});case Ee["share-of-voice"]:return e.jsx(zj,{report:s});case Ee["whats-changed"]:return e.jsx(eN,{report:s,audience:n});case Ee["server-activity"]:return n==="client"?e.jsx(Yj,{report:s}):e.jsx(NN,{report:s});case Ee["client-action-plan"]:return e.jsx(tc,{report:s,audience:"client",dismissedRefs:a,onDismiss:r});case Ee["agency-action-plan"]:return e.jsx(tc,{report:s,audience:"agency",dismissedRefs:a,onDismiss:r});case Ee["agency-diagnostics"]:return e.jsx(iN,{report:s});case Ee["citation-scorecard"]:return e.jsx(oN,{report:s});case Ee["competitor-landscape"]:return e.jsx(mN,{report:s});case Ee["ai-source-origin"]:return e.jsx(pN,{report:s});case Ee.gsc:return e.jsx(yN,{report:s});case Ee.ga:return e.jsx(bN,{report:s});case Ee["social-referrals"]:return e.jsx(vN,{report:s});case Ee["ai-referrals"]:return e.jsx(jN,{report:s});case Ee["indexing-health"]:return e.jsx(wN,{report:s});case Ee["citations-trend"]:return e.jsx(CN,{report:s});case Ee.insights:return e.jsx(kN,{report:s});case Ee["content-opportunities"]:return e.jsx(AN,{report:s});case Ee["content-gaps"]:return e.jsx(IN,{report:s});case Ee["recommended-next-steps"]:return e.jsx(lN,{report:s});case Ee["client-evidence-summary"]:return e.jsx(Xj,{report:s})}}function zj({report:t}){const s=[t.mentionLandscape.nonBrand?.shareOfVoice,t.mentionLandscape.branded?.shareOfVoice?.queryClass==="branded"?t.mentionLandscape.branded.shareOfVoice:void 0];return e.jsx("div",{className:"space-y-2 text-sm text-secondary","aria-label":"Share of voice","data-report-section":Ee["share-of-voice"],children:s.map(n=>n?e.jsxs("div",{children:[e.jsx("p",{children:Xh(n.percent,n.queryClass,n)}),n.reason?e.jsx("p",{children:Zh(n.reason)}):null]},n.queryClass):null)})}function Wj({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:bh.map(n=>{const a=n===t;return e.jsxs("button",{type:"button",onClick:()=>s(n),"aria-pressed":a,className:`segmented-option ${a?"segmented-option-active":""}`,children:[n,"d"]},n)})})}function Yj({report:t}){const s=t.serverActivity;if(!s)return null;const n=t.meta.periodDays,a=rt["server-activity"];if(!s.hasData)return e.jsx(ot,{...yr("client",!1,n),children:e.jsx(Ot,{message:a.client.empty})});const r={current:s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,prior:s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior,deltaPct:Hh(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},l=el(n),i=Qh(s.verifiedCrawlerHits.current,s.unverifiedCrawlerHits.current),o=qn(r,a.countNouns.requests,l),d=qn(s.aiUserFetchHits,a.countNouns.requests,l),m=Qd([qn(s.referralArrivals,a.countNouns.sessions,l),s.referralArrivalsClassSummary,Dc(s.referralRedirects)]),u=s.byOperator.filter(p=>p.verifiedHits>0||p.unverifiedHits>0||p.userFetchHits>0||p.referralArrivals>0).slice(0,5),[h,g,x,y]=bx(n);return e.jsxs(ot,{...yr("client",!0,n),children:[e.jsx(sn,{columns:3,tiles:[{label:a.client.tiles.botRequests,value:De(r.current),subtitle:o?e.jsxs(e.Fragment,{children:[i," · ",o]}):i},{label:a.client.tiles.userFetches,value:De(s.aiUserFetchHits.current),subtitle:d??a.client.userFetchFallback},{label:a.client.tiles.referralSessions,value:De(s.referralArrivals.current),subtitle:m}]}),u.length>0&&e.jsx(Et,{title:a.client.operatorsHeading,headers:[h,{label:g,numeric:!0},{label:x,numeric:!0},{label:y,numeric:!0}],footnote:e.jsx(Ps,{children:a.client.operatorsFootnote}),children:u.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:p.operator}),e.jsx("td",{className:"text-right tabular-nums",children:De(p.verifiedHits+p.unverifiedHits)}),e.jsx("td",{className:"text-right tabular-nums",children:De(p.userFetchHits)}),e.jsx("td",{className:"text-right tabular-nums",children:De(p.referralArrivals)})]},p.operator))})]})}function Jj({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=rt["client-summary"],r=s.totalQueryCount??0,l=r>0?Fe(s.mentionRate,Lt.percent):"—",i=tx(t.whatsChanged.mentionRate),{lead:o,mention:d,link:m,closing:u}=a.explainer;return e.jsxs("section",{id:Ee["client-summary"],"data-report-section":Ee["client-summary"],className:"page-section-divider",children:[e.jsxs("div",{className:"rounded-2xl border border-default bg-bg-elevated/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:a.heroEyebrow}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-primary sm:text-7xl",children:l}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-neutral sm:text-lg",children:sx(r,s.mentionedQueryCount)}),i&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${i.tone==="positive"?"text-positive-400":i.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:i.arrow}),i.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(fi,{label:a.tiles.mentioned,value:Fe(s.mentionRate,Lt.percent),subtitle:nx(s.mentionedQueryCount,r)}),e.jsx(fi,{label:a.tiles.cited,value:Fe(s.citationRate,Lt.percent),subtitle:ax(s.citedQueryCount,r)}),e.jsx(fi,{label:a.tiles.providers,value:De(s.providerCount),subtitle:rx(n.providers,s.queryCount)})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-bg/40 px-4 py-3 text-[13px] text-secondary","data-report-note":!0,children:[e.jsx("span",{className:"font-semibold text-strong",children:o})," ",d.article," ",e.jsx("span",{className:"font-medium text-strong",children:d.term})," ",d.definition," ",m.article," ",e.jsx("span",{className:"font-medium text-strong",children:m.term})," ",m.definition," ",u]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading","data-report-heading":!0,children:a.queriesHeading}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary","data-report-note":!0,children:ix(n.queries.length)}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((h,g)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-bg/40 px-3 py-2 text-sm text-strong",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-muted",children:String(g+1).padStart(2,"0")}),e.jsxs("span",{children:['"',h,'"']})]},g))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading","data-report-heading":!0,children:a.providerBarsHeading}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary","data-report-note":!0,children:a.providerBarsSubtitle}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(h=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:Xi(h.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-positive-500/70",style:{width:`${Math.max(h.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[Fe(h.mentionRate,Lt.percent)," ",e.jsxs("span",{className:"font-normal text-muted",children:["(",h.mentionedCount,"/",h.totalCount,")"]})]})]},h.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((h,g)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-[13px] text-secondary","data-report-note":!0,children:h},g))})]})}function fi({label:t,value:s,subtitle:n}){return e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted","data-report-tile":!0,children:t}),e.jsx("p",{className:"mt-3 text-4xl font-bold tracking-tight text-primary sm:text-5xl",children:s}),e.jsx("p",{className:"mt-2 text-[13px] text-secondary",children:n})]})}function tc({report:t,audience:s,dismissedRefs:n,onDismiss:a}){const r=Gh(t,s),l=s==="client",i=l?Ee["client-action-plan"]:Ee["agency-action-plan"],o=rt[i],d=n.size>0?r.filter(m=>!m.targetRef||!n.has(m.targetRef)):r;return e.jsx(ot,{id:i,eyebrow:o.eyebrow,title:o.title,intro:o.intro,children:d.length===0?e.jsx(Ot,{message:o.empty}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:d.map((m,u)=>{const h=m.evidence.length>0?m.evidence:m.why,g=m.why.length>0||m.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-default bg-surface p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-mono-800/80 text-sm font-semibold text-heading",title:o.rankTitle,children:u+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(re,{tone:Bh(m),children:_h(s,m.horizon)}),!l&&e.jsx(re,{tone:"neutral",children:Uh(m.category)}),e.jsx(re,{tone:"neutral",children:Vh(s,m.confidence)})]}),e.jsx("h3",{className:"text-sm font-medium text-heading","data-report-heading":!0,children:m.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:m.action}),e.jsx($r,{items:h,limit:3,className:"mt-3"}),g&&e.jsxs("details",{className:"mt-3 text-[13px] text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-secondary hover:text-neutral",children:o.detailsSummary}),m.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:o.whyLabel}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:m.why.map((x,y)=>e.jsx("li",{children:x},y))})]}),m.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:o.evidenceLabel}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:m.evidence.map((x,y)=>e.jsx("li",{children:x},y))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-[13px] text-neutral",children:[e.jsx("span",{className:"font-medium",children:o.successLabel})," ",m.successMetric]}),m.targetRef&&!ce()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>a(m),className:"rounded-md border border-default bg-bg-elevated/50 px-2.5 py-1 text-[11px] font-medium text-neutral hover:border-mono-600 hover:bg-mono-800/70 hover:text-heading",title:"Stop showing this recommendation. The page-detection logic relies on GSC/GA syncs that lag by days — if you've already addressed it, dismissing keeps the report current.",children:"Mark addressed"})})]},`${m.priority}-${m.title}`)})})})}function sc({label:t,value:s,displayValue:n,max:a,barClass:r}){const l=a>0?Math.max(s/a*100,1.5):0;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-neutral",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${r}`,style:{width:`${l}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function Xj({report:t}){const s=rt["client-evidence-summary"],n=t.aiSourceOrigin.topDomains.slice(0,5),a=t.gsc,r=t.indexingHealth,l=Tc(t).slice(0,5),i=n.length>0?Math.max(...n.map(u=>u.count)):0,o=a?Math.max(...a.topQueries.slice(0,5).map(u=>u.impressions),1):0,d=r?jh(r.indexedPct):"neutral",m=n.length>0||a!==null||r!==null||l.length>0;return e.jsx(ot,{id:Ee["client-evidence-summary"],eyebrow:s.eyebrow,title:s.title,intro:s.intro,children:m?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[n.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading","data-report-heading":!0,children:s.sources.heading}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary","data-report-note":!0,children:s.sources.subtitle}),e.jsx("div",{className:"mt-4 space-y-3",children:n.map(u=>e.jsx(sc,{label:u.isCompetitor?`${u.domain} ${s.sources.competitorTag}`:u.domain,value:u.count,displayValue:Nh(u.count),max:i,barClass:"bg-mono-400/70"},u.domain))})]}),r&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading","data-report-heading":!0,children:s.indexing.heading}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary","data-report-note":!0,children:s.indexing.subtitle}),e.jsx("p",{className:`mt-4 text-5xl font-bold tracking-tight ${tn[d]}`,children:Fe(r.indexedPct,Lt.percent)}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:wh(r.indexed,r.total)}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${Uj[d]}`,style:{width:`${Math.max(r.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-[13px] text-secondary",children:[e.jsx("span",{className:"font-medium text-strong",children:De(r.notIndexed)})," ",Sh(r.notIndexed)]})]}),a&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading","data-report-heading":!0,children:s.search.heading}),e.jsxs("p",{className:"mt-1 text-[13px] text-secondary","data-report-note":!0,children:[s.search.subtitleLead," ",e.jsx("span",{className:"font-semibold text-strong",children:De(a.totalImpressions)})," ",s.search.subtitleMiddle," ",e.jsx("span",{className:"font-semibold text-strong",children:De(a.totalClicks)})," ",Ch(a.totalClicks)," ",s.search.subtitleTail]}),a.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:a.topQueries.slice(0,5).map(u=>e.jsx(sc,{label:u.query,value:u.impressions,displayValue:kh(u.impressions),max:o,barClass:"bg-info-500/70"},u.query))})]}),l.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading","data-report-heading":!0,children:s.opportunities.heading}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary","data-report-note":!0,children:s.opportunities.subtitle}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:l.map((u,h)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:u.query}),e.jsxs("div",{className:"mt-0.5 flex items-center gap-2 text-[13px] text-secondary",children:[Lc(u.action),u.winnabilityClass===$c.ceded&&e.jsx(re,{tone:"caution",children:s.opportunities.cededTag})]})]},h))})]})]}):e.jsx(Ot,{message:s.empty})})}function yi({label:t,delta:s,unit:n}){return s?e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft","data-report-tile":!0,children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${tn[Zi(s.direction)]}`,children:[Nx(s,n)," ",e.jsx("span",{className:"text-sm font-medium",children:Fc(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:wx(s,n)})]}):e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft","data-report-tile":!0,children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:rt["whats-changed"].rateTileEmpty})]})}function nc({label:t,delta:s,countLabel:n,comparisonWindowDays:a}){return s?e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft","data-report-tile":!0,children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${tn[Zi(s.direction)]}`,children:[De(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:Fc(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:Sx(s,n,el(a))})]}):e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft","data-report-tile":!0,children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:rt["whats-changed"].trafficTileEmpty})]})}function Zj({movements:t,audience:s}){const n=t.filter(m=>m.direction!=="flat");if(n.length===0)return null;const a=s==="client",r=a?rt["whats-changed"].client:rt["whats-changed"].agency,[l,i,o,d]=r.movementHeaders;return e.jsx(Et,{title:r.movementsHeading,headers:[l,{label:i,numeric:!0},{label:o,numeric:!0},{label:d,numeric:!0}],children:n.map(m=>{const u=Zi(m.direction);return e.jsxs("tr",{children:[e.jsx("td",{children:a?Xi(m.provider):m.provider}),e.jsx("td",{className:"text-right tabular-nums",children:Fe(m.prior,Lt.percent)}),e.jsx("td",{className:"text-right tabular-nums",children:Fe(m.current,Lt.percent)}),e.jsx("td",{className:`text-right tabular-nums ${u==="neutral"?"text-neutral":tn[u]}`,children:Cx(m)})]},m.provider)})})}function ac({insights:t,heading:s,emptyMessage:n,audience:a}){if(t.length===0)return e.jsx(Gn,{title:s,children:e.jsx(Ps,{children:n})});const r=a==="client",l=r?rt["whats-changed"].client:rt["whats-changed"].agency;return e.jsx(Et,{title:s,headers:l.insightHeaders,children:t.map(i=>e.jsxs("tr",{children:[!r&&e.jsx("td",{children:e.jsx(re,{tone:qc(i),children:Mc(i.severity)})}),e.jsxs("td",{className:"evidence-query-cell",children:[i.title,i.instanceCount>1&&e.jsx(re,{tone:"neutral",className:"ml-2",children:Ec(i.instanceCount)})]}),e.jsx("td",{className:"text-[13px] text-secondary",children:i.query}),e.jsx("td",{className:"text-[13px] text-secondary",children:r?Xi(i.provider):i.provider})]},i.id))})}function eN({report:t,audience:s}){const n=t.whatsChanged,a=s==="client",{client:r,agency:l}=rt["whats-changed"],i=a?r:l,o=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0;return e.jsx(ot,{id:Ee["whats-changed"],eyebrow:i.eyebrow,title:i.title,intro:a?void 0:n.headline,children:o?e.jsx(Ot,{message:i.empty}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(yi,{label:a?r.tiles.mentionRate:l.tiles.citationRate,delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(yi,{label:a?r.tiles.citationRate:l.tiles.mentionRate,delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(yi,{label:a?r.tiles.mentionedQueryCount:l.tiles.citedQueryCount,delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(nc,{label:i.tiles.gscClicks,delta:n.gscClicksDelta,countLabel:i.gscCountLabel,comparisonWindowDays:n.comparisonWindowDays}),e.jsx(nc,{label:i.tiles.aiReferrals,delta:n.aiReferralsDelta,countLabel:i.aiReferralsCountLabel,comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(Zj,{movements:n.providerMovements,audience:s}),e.jsx(ac,{insights:n.wins,heading:i.winsHeading,emptyMessage:i.winsEmpty,audience:s}),e.jsx(ac,{insights:n.regressions,heading:i.regressionsHeading,emptyMessage:i.regressionsEmpty,audience:s})]})})}const tN={positive:"insight-card-positive",caution:"insight-card-caution",negative:"insight-card-negative",neutral:""};function Nl(t,s){return["insight-card",tN[t],s].filter(Boolean).join(" ")}const sN=Nl("caution","gap-1 rounded-r-lg bg-caution-950/25 px-3 py-2");function nN(t){return t>=5?5:t===4?4:3}function aN({report:t}){const s=t.executiveSummary,n=rt["executive-summary"],a=ex(t),r=[{label:n.proofTiles.citationTrend,value:a.trendLabel,tone:a.trendTone,subtitle:a.citedFragment},{label:n.proofTiles.mentionCoverage,value:Fe(s.mentionRate,Lt.percent),subtitle:a.mentionedFragment},{label:n.proofTiles.prioritizedActions,value:De(a.prioritizedActionCount),subtitle:n.prioritizedActionsCopy}],l=[{label:n.tiles.citationRate,value:Fe(s.citationRate,Lt.percent),subtitle:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:jl[a.trendTone]||void 0,children:a.trendLabel}),` · ${a.citedFragment} · ${a.providerCountLabel}`]})},{label:n.tiles.mentionRate,value:Fe(s.mentionRate,Lt.percent),subtitle:a.mentionedFragment},{label:n.tiles.queriesTracked,value:De(s.queryCount),subtitle:a.competitorCountLabel}];return s.gsc&&a.gscDelta!==null&&l.push({label:n.tiles.gscClicks,value:De(s.gsc.clicks),subtitle:a.gscDelta}),s.ga&&a.gaDelta!==null&&l.push({label:n.tiles.gaSessions,value:De(s.ga.sessions),subtitle:a.gaDelta}),e.jsxs(ot,{id:Ee["executive-summary"],eyebrow:n.eyebrow,title:n.title,intro:n.intro,children:[e.jsxs("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,2fr)_minmax(0,3fr)]",children:[e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"eyebrow-soft",children:n.heroKicker}),e.jsx("p",{className:"mt-2 text-xl font-semibold tracking-tight text-heading",children:a.title}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:a.subtitle})]}),e.jsx(sn,{columns:3,tiles:r})]}),e.jsx("div",{className:"mt-3",children:e.jsx(sn,{columns:nN(l.length),tiles:l})}),s.findings.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:s.findings.map((i,o)=>e.jsxs("div",{className:Nl(i.tone,"gap-1 rounded-r-lg bg-surface px-4 py-3"),children:[e.jsx("strong",{className:"text-sm font-semibold text-heading",children:i.title}),e.jsx("span",{className:"text-[13px] text-secondary",children:i.detail})]},`${o}-${i.title}`))}),e.jsx(rN,{report:t})]})}function rN({report:t}){const s=kx(t);if(!s)return null;const n=rt["executive-summary"].marketScope;return e.jsxs(Gn,{title:n.heading,children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(bi,{label:n.currentLabel,value:s.currentValue,detail:n.currentCopy}),e.jsx(bi,{label:n.notIncludedLabel,value:s.notIncludedValue,detail:s.notIncludedCopy}),e.jsx(bi,{label:n.providerLabel,value:s.providerValue,detail:s.providerCopy})]}),s.weakProviders!==null&&e.jsxs(Ps,{className:sN,children:[e.jsx("strong",{className:"font-semibold text-heading",children:n.warningTitle})," ",s.weakProviders," ",n.warningDetail]})]})}function bi({label:t,value:s,detail:n}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2.5",children:[e.jsx("p",{className:"eyebrow-soft","data-report-tile":!0,children:t}),e.jsx("p",{className:"text-lg font-semibold leading-tight text-heading",children:s}),e.jsx("p",{className:"mt-1.5 text-[13px] text-secondary",children:n})]})}function iN({report:t}){const s=rt["agency-diagnostics"],n=t.agencyDiagnostics.diagnostics.filter(a=>a.title!==s.hiddenTitle);return e.jsx(ot,{id:Ee["agency-diagnostics"],eyebrow:s.eyebrow,title:s.title,intro:s.intro,children:n.length===0?e.jsx(Ot,{message:s.empty}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:n.map((a,r)=>e.jsxs("article",{className:Nl(a.severity,"gap-2 rounded-r-lg bg-surface p-4"),children:[e.jsx("h3",{className:"text-sm font-semibold text-heading","data-report-heading":!0,children:a.title}),e.jsx("p",{className:"text-sm text-secondary",children:a.detail}),e.jsx($r,{items:a.evidence,limit:3,className:"mt-1"})]},`${r}-${a.title}`))})})}function lN({report:t}){const s=rt["recommended-next-steps"],n=t.recommendedNextSteps;return e.jsx(ot,{id:Ee["recommended-next-steps"],eyebrow:s.eyebrow,title:s.title,intro:s.intro,children:n.length===0?e.jsx(Ot,{message:s.empty}):e.jsx("ol",{className:"grid gap-2",children:n.map((a,r)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsx(re,{tone:"neutral",className:"shrink-0",children:a.horizon}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:a.title}),e.jsx("p",{className:"mt-0.5 text-[13px] text-secondary",children:a.rationale})]})]},`${r}-${a.title}`))})})}function oN({report:t}){const s=rt["citation-scorecard"],n=t.citationScorecard,a=ns.series;return e.jsxs(ot,{id:Ee["citation-scorecard"],eyebrow:s.eyebrow,title:s.title,intro:s.intro,children:[e.jsx(Wd,{title:s.providerChartTitle,rows:n.providerRates.map((r,l)=>({label:r.provider,value:r.citationRate,color:a[l%a.length],valueLabel:Kh(r)})),domainMax:Math.max(...n.providerRates.map(r=>r.citationRate),100),track:!0}),n.queries.length>0&&n.providers.length>0?e.jsx(cN,{scorecard:n}):e.jsx(Ot,{message:s.empty})]})}function cN({scorecard:t}){const{queryHeader:s,glyphs:n,legend:a}=rt["citation-scorecard"];return e.jsx(Et,{headers:[s,...t.providers],note:e.jsxs(Ps,{className:"mb-2",children:[a.lead," ",e.jsx(Js,{mark:"yes",children:n.cited}),"/",e.jsx(Js,{mark:"no",children:n.notCited})," ",a.citedMeaning," ",e.jsx(Js,{mark:"yes",children:n.mentioned}),"/",e.jsx(Js,{mark:"no",children:n.notMentioned})," ",a.mentionedMeaning," ",e.jsx(Js,{mark:"pending",children:n.pending})," ",a.pendingMeaning]}),children:t.queries.map((r,l)=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:r}),t.providers.map((i,o)=>e.jsx("td",{className:"whitespace-nowrap font-mono text-[13px]",children:e.jsx(uN,{cell:t.matrix.at(l)?.at(o)??null})},`${o}-${i}`))]},`${l}-${r}`))})}const dN={yes:`font-semibold ${tn.positive}`,no:"text-secondary",pending:"italic text-secondary"};function Js({mark:t,children:s}){return e.jsx("span",{className:dN[t],children:s})}function uN({cell:t}){const{glyphs:s}=rt["citation-scorecard"];if(!t)return e.jsx(Js,{mark:"pending",children:s.missingCell});const n=t.citationState===mc.cited;return e.jsxs(e.Fragment,{children:[e.jsx(Js,{mark:n?"yes":"no",children:n?s.cited:s.notCited})," ",t.answerMentioned===null?e.jsx(Js,{mark:"pending",children:s.pending}):e.jsx(Js,{mark:t.answerMentioned?"yes":"no",children:t.answerMentioned?s.mentioned:s.notMentioned})]})}function mN({report:t}){const s=rt["competitor-landscape"],{competitors:n,projectCitationCount:a}=t.competitorLandscape,r=t.mentionLandscape,l=r.branded,i=r.nonBrand,o=(l?.totalAnswerSnapshots??0)>0,d=n.length===0&&a===0,m=r.competitors.length===0&&r.projectMentionCount===0&&!o;if(d&&m)return e.jsx(ot,{id:Ee["competitor-landscape"],eyebrow:s.eyebrow,title:s.title,children:e.jsx(Ot,{message:s.empty})});const u=t.meta.project.canonicalDomain,h=Fh(r),g=vi(u,a,n.map(w=>({domain:w.domain,count:w.citationCount}))),x=vi(u,r.projectMentionCount,r.competitors.map(w=>({domain:w.domain,count:w.mentionCount}))),y=l&&o?vi(u,l.projectMentionCount,l.competitors.map(w=>({domain:w.domain,count:w.mentionCount}))):[],p=!i?.shareOfVoice&&r.projectMentionCount===0&&r.competitors.length>0&&r.competitors.every(w=>w.sharePct===null),v=e.jsx(ji,{title:s.citationsChartTitle,rows:g}),j=e.jsx(ji,{title:h.mentionsChartTitle,rows:x});return e.jsxs(ot,{id:Ee["competitor-landscape"],eyebrow:s.eyebrow,title:s.title,intro:s.intro,children:[p?e.jsx(Ps,{children:h.mentionShareUnavailable}):null,g.length>0&&x.length>0?e.jsxs("div",{className:"grid gap-x-4 lg:grid-cols-2",children:[v,j]}):e.jsxs(e.Fragment,{children:[v,j]}),n.length>0?e.jsx(hN,{report:t,mentionCopy:h}):e.jsx(Ot,{message:s.noCompetitors}),y.length>0?e.jsxs("div",{className:"mt-4",children:[e.jsx(Ps,{children:h.brandedNote}),e.jsx(ji,{title:s.brandedChartTitle,rows:y})]}):null]})}function vi(t,s,n){if(n.length===0)return[];const a=ns.series;return[{label:t,value:s,color:a[1],valueLabel:String(s)},...n.map((r,l)=>({label:r.domain,value:r.count,color:a[(l+2)%a.length],valueLabel:String(r.count)}))]}function ji({title:t,rows:s}){return e.jsx(Wd,{title:t,rows:s,rowHeight:28,labelWidth:160})}function hN({report:t,mentionCopy:s}){const n=rt["competitor-landscape"],a=t.mentionLandscape,r=new Map(a.competitors.map(l=>[l.domain,l]));return e.jsx(Et,{headers:[n.headers.domain,n.headers.pressure,{label:n.headers.citations,numeric:!0},{label:s.mentionsHeader,numeric:!0,tooltip:s.mentionsTooltip},{label:n.headers.citationShare,numeric:!0,tooltip:n.citationShareTooltip},n.headers.citedQueries],children:t.competitorLandscape.competitors.map((l,i)=>{const o=r.get(l.domain);return e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:l.domain}),e.jsx("td",{children:e.jsx(re,{tone:xx(l.pressureLabel),children:l.pressureLabel})}),e.jsxs("td",{className:"whitespace-nowrap text-right tabular-nums",children:[l.citationCount," / ",l.totalCount]}),e.jsxs("td",{className:"whitespace-nowrap text-right tabular-nums",children:[o?.mentionCount??0," / ",o?.totalCount??a.totalAnswerSnapshots]}),e.jsx("td",{className:"text-right tabular-nums",children:Fe(l.sharePct,Lt.percent)}),e.jsxs("td",{className:"min-w-48",children:[px(l.citedQueries,5),l.theirCitedPages.length>0?e.jsx(xN,{pages:l.theirCitedPages}):null]})]},`${i}-${l.domain}`)})})}function xN({pages:t}){return e.jsxs("details",{className:"mt-2 text-[13px] text-secondary",children:[e.jsx("summary",{className:"cursor-pointer rounded-sm text-secondary hover:text-neutral focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:Rx(t.length)}),e.jsx("ul",{className:"mt-2 space-y-1",children:t.map((s,n)=>e.jsxs("li",{className:"break-all",children:[e.jsx(Vi,{href:s.url,children:s.url})," ",e.jsx("span",{className:"text-secondary",children:s.citedFor.join(", ")})]},`${n}-${s.url}`))})]})}function pN({report:t}){const s=rt["ai-source-origin"],n=t.aiSourceOrigin;if(n.categories.length===0&&n.topDomains.length===0)return e.jsx(ot,{id:Ee["ai-source-origin"],eyebrow:s.eyebrow,title:s.title,children:e.jsx(Ot,{message:s.empty})});const a=Eh(n.categories),[r,l,i]=s.topSourceHeaders;return e.jsxs(ot,{id:Ee["ai-source-origin"],eyebrow:s.eyebrow,title:s.title,intro:s.intro,children:[a?e.jsxs(Ps,{children:[e.jsx("strong",{className:"font-semibold text-heading",children:a.share})," ",a.detail]}):null,n.topDomains.length>0?e.jsx(Et,{title:s.topSourcesHeading,headers:[r,{label:l,numeric:!0},i],children:n.topDomains.map((o,d)=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:o.domain}),e.jsx("td",{className:"text-right tabular-nums",children:o.count}),e.jsx("td",{children:o.isCompetitor?e.jsx(re,{tone:"negative",children:s.trackedCompetitorTag}):e.jsx(re,{tone:"neutral",children:s.externalTag})})]},`${d}-${o.domain}`))}):null,e.jsx(Oa,{title:s.categoriesHeading,scale:"max",rows:n.categories.map(o=>({label:o.label,count:o.count,sharePct:o.sharePct,color:gN(Oh(o.category)),valueLabel:`${o.count} ${Dh(o.sharePct)}`}))})]})}function gN(t){return{negative:ns.tone.negative,caution:ns.tone.caution,positive:ns.series[1],neutral:ns.series[1]}[t]}const fN=6;function yN({report:t}){const s=t.gsc,n=rt.gsc;if(!s)return e.jsx(ot,{id:Ee.gsc,eyebrow:n.eyebrow,title:n.title,children:e.jsx(Ot,{message:n.empty})});const[a,r,l,i,o,d]=n.topQueryHeaders;return e.jsxs(ot,{id:Ee.gsc,eyebrow:n.eyebrow,title:n.title,intro:qh(t),children:[e.jsx(sn,{columns:4,tiles:[{label:n.tiles.clicks,value:De(s.totalClicks)},{label:n.tiles.impressions,value:De(s.totalImpressions)},{label:n.tiles.ctr,value:Fe(s.ctr)},{label:n.tiles.position,value:s.avgPosition.toFixed(1)}]}),e.jsx(Lr,{title:n.trendTitle,data:s.trend,xKey:"date",dataKey:"clicks",color:ns.series[1],formatValue:De,dates:"calendar"}),e.jsx(Et,{title:n.topQueriesHeading,headers:[a,{label:r,numeric:!0},{label:l,numeric:!0},{label:i,numeric:!0},{label:o,numeric:!0},d],children:s.topQueries.map((m,u)=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:m.query}),e.jsx("td",{className:"text-right tabular-nums",children:De(m.clicks)}),e.jsx("td",{className:"text-right tabular-nums",children:De(m.impressions)}),e.jsx("td",{className:"text-right tabular-nums",children:Fe(m.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:m.avgPosition.toFixed(1)}),e.jsx("td",{children:e.jsx(re,{tone:"neutral",children:m.category})})]},`${u}-${m.query}`))}),e.jsx(Oa,{title:n.intentHeading,scale:"share",rows:Tr(s.categoryBreakdown.map(m=>({label:m.category,count:m.clicks,sharePct:m.sharePct})),n.intentCountLabel)}),e.jsx(rc,{title:n.untrackedDemand.heading,note:n.untrackedDemand.subtitle,queries:s.trackedButNoGsc}),e.jsx(rc,{title:n.suggestedQueries.heading,note:n.suggestedQueries.subtitle,queries:s.gscButNotTracked})]})}function rc({title:t,note:s,queries:n}){return n.length===0?null:e.jsxs(Gn,{title:t,children:[e.jsx(Ps,{children:s}),e.jsx($r,{items:n,limit:fN,className:"mt-3"})]})}function bN({report:t}){const s=t.ga,n=rt.ga;if(!s)return e.jsx(ot,{id:Ee.ga,eyebrow:n.eyebrow,title:n.title,children:e.jsx(Ot,{message:n.empty})});const[a,r,l]=n.topPageHeaders;return e.jsxs(ot,{id:Ee.ga,eyebrow:n.eyebrow,title:n.title,intro:Mh(s),children:[e.jsx(sn,{columns:3,tiles:[{label:n.tiles.sessions,value:De(s.totalSessions)},{label:n.tiles.users,value:De(s.totalUsers)},{label:n.tiles.organicSessions,value:De(s.totalOrganicSessions)}]}),e.jsx(Et,{title:n.topPagesHeading,headers:[a,{label:r,numeric:!0},{label:l,numeric:!0}],children:s.topLandingPages.map((i,o)=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx(kr,{page:i.page})}),e.jsx("td",{className:"text-right tabular-nums",children:De(i.sessions)}),e.jsx("td",{className:"text-right tabular-nums",children:De(i.organicSessions)})]},`${o}-${i.page}`))}),e.jsx(Oa,{title:n.channelsHeading,scale:"share",rows:Tr(s.channelBreakdown.map(i=>({label:i.channel,count:i.sessions,sharePct:i.sharePct})),n.channelsCountLabel)})]})}function vN({report:t}){const s=t.socialReferrals,n=rt["social-referrals"];if(!s)return e.jsx(ot,{id:Ee["social-referrals"],eyebrow:n.eyebrow,title:n.title,children:e.jsx(Ot,{message:n.empty})});const[a,r,l]=n.campaignHeaders;return e.jsxs(ot,{id:Ee["social-referrals"],eyebrow:n.eyebrow,title:n.title,intro:n.intro,children:[e.jsx(sn,{columns:3,tiles:[{label:n.tiles.sessions,value:De(s.totalSessions)},{label:n.tiles.organic,value:De(s.organicSessions)},{label:n.tiles.paid,value:De(s.paidSessions)}]}),e.jsx(Oa,{title:n.channelsHeading,scale:"share",rows:Tr(s.channels.map(i=>({label:i.channelGroup,count:i.sessions,sharePct:i.sharePct})),n.channelsCountLabel)}),e.jsx(Et,{title:n.campaignsHeading,headers:[a,r,{label:l,numeric:!0}],children:s.topCampaigns.map((i,o)=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:i.source}),e.jsx("td",{className:"text-[13px] text-secondary",children:i.medium}),e.jsx("td",{className:"text-right tabular-nums",children:De(i.sessions)})]},`${o}-${i.source}-${i.medium}`))})]})}function jN({report:t}){const s=t.aiReferrals,n=rt["ai-referrals"];if(!s)return e.jsx(ot,{id:Ee["ai-referrals"],eyebrow:n.eyebrow,title:n.title,children:e.jsx(Ot,{message:n.empty})});const[a,r]=n.topPageHeaders;return e.jsxs(ot,{id:Ee["ai-referrals"],eyebrow:n.eyebrow,title:n.title,intro:n.intro,children:[e.jsx(sn,{columns:3,tiles:[{label:n.tiles.sessions,value:De(s.totalSessions)}]}),e.jsx(Lr,{title:n.trendTitle,data:s.trend,xKey:"date",dataKey:"sessions",color:ns.series[2],formatValue:De,dates:"calendar"}),e.jsx(Oa,{title:n.sourcesHeading,scale:"share",rows:Tr(s.bySource.map(l=>({label:l.source,count:l.sessions,sharePct:l.sharePct})),n.sourcesCountLabel,2)}),e.jsx(Et,{title:n.topPagesHeading,headers:[a,{label:r,numeric:!0}],children:s.topLandingPages.map((l,i)=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx(kr,{page:l.page})}),e.jsx("td",{className:"text-right tabular-nums",children:De(l.sessions)})]},`${i}-${l.page}`))})]})}function Tr(t,s,n=0){const a=ns.series;return t.map((r,l)=>({...r,color:a[(l+n)%a.length],valueLabel:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-heading",children:De(r.count)})," ",mx(s,r.sharePct)]})}))}function NN({report:t}){const s=t.serverActivity,n=t.meta.periodDays,a=rt["server-activity"],r=a.agency;if(!s?.hasData)return e.jsx(ot,{...yr("agency",!1,n),children:e.jsx(Ot,{message:s?r.empty:r.emptyNotConnected})});const l=el(n),i=vx(n),[o,d,m,u,h,g]=jx(n),[x,y,p,v]=r.crawledPathHeaders,[j,w,I]=r.referralProductHeaders,[k,f,b]=r.referralLandingHeaders,S=[qn(s.referralArrivals,a.countNouns.sessions,l),s.referralArrivalsClassSummary,Dc(s.referralRedirects)];return e.jsxs(ot,{...yr("agency",!0,n),children:[e.jsx(sn,{columns:4,tiles:[{label:i.verified,value:De(s.verifiedCrawlerHits.current),subtitle:qn(s.verifiedCrawlerHits,a.countNouns.hits,l)},{label:i.unverified,value:De(s.unverifiedCrawlerHits.current),subtitle:qn(s.unverifiedCrawlerHits,a.countNouns.hits,l)},{label:i.userFetches,value:De(s.aiUserFetchHits.current),subtitle:qn(s.aiUserFetchHits,a.countNouns.hits,l)},{label:i.referralSessions,value:De(s.referralArrivals.current),subtitle:Qd(S)}]}),e.jsx(Lr,{title:zh(n),data:s.dailyTrend,xKey:"date",dataKey:"verifiedCrawlerHits",color:ns.series[1],formatValue:De,dates:"calendar"}),s.byOperator.length>0&&e.jsx(Et,{title:r.operatorsHeading,tooltip:r.operatorsNote,headers:[o,{label:d,numeric:!0},{label:m,numeric:!0},{label:u,numeric:!0},{label:h,numeric:!0},{label:g,numeric:!0}],children:s.byOperator.map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:A.operator}),e.jsx("td",{className:"text-right tabular-nums",children:De(A.verifiedHits)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:De(A.unverifiedHits)}),e.jsx("td",{className:"text-right tabular-nums",children:De(A.userFetchHits)}),e.jsx("td",{className:"text-right tabular-nums",children:De(A.referralArrivals)}),e.jsx("td",{className:`text-right tabular-nums ${A.deltaPct===null?"":jl[Oc(A.deltaPct)]}`,children:Wh(A.deltaPct)})]},A.operator))}),s.topCrawledPaths.length>0&&e.jsx(Et,{title:r.crawledPathsHeading,note:e.jsx(Ps,{className:"mb-2",children:Jh(n)}),headers:[x,{label:y,numeric:!0},{label:p,numeric:!0},{label:v,numeric:!0}],children:s.topCrawledPaths.map((A,P)=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx(kr,{page:A.path})}),e.jsx("td",{className:"text-right tabular-nums",children:De(Yh(A))}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:De(A.verifiedHits)}),e.jsx("td",{className:"text-right tabular-nums",children:A.distinctOperators})]},`${P}-${A.path}`))}),s.referralProducts.length>0&&e.jsx(Et,{title:r.referralProductsHeading,note:e.jsx(Ps,{className:"mb-2",children:r.referralProductsNote}),headers:[j,{label:w,numeric:!0},{label:I,numeric:!0}],children:s.referralProducts.map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:A.product}),e.jsx("td",{className:"text-right tabular-nums",children:De(A.arrivals)}),e.jsx("td",{className:"text-right tabular-nums",children:A.distinctLandingPaths})]},A.product))}),s.topReferralLandingPaths.length>0&&e.jsx(Et,{title:r.referralLandingHeading,headers:[k,{label:f,numeric:!0},{label:b,numeric:!0}],children:s.topReferralLandingPaths.map((A,P)=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx(kr,{page:A.path})}),e.jsx("td",{className:"text-right tabular-nums",children:De(A.arrivals)}),e.jsx("td",{className:"text-right tabular-nums",children:A.distinctProducts})]},`${P}-${A.path}`))})]})}function wN({report:t}){const s=t.indexingHealth,n=rt["indexing-health"];if(!s)return e.jsx(ot,{id:Ee["indexing-health"],eyebrow:n.eyebrow,title:n.title,children:e.jsx(Ot,{message:n.empty})});const r=[{key:"indexed",label:n.segments.indexed,count:s.indexed,color:ns.tone.positive},{key:"notIndexed",label:n.segments.notIndexed,count:s.notIndexed,color:ns.tone.caution},{key:"deindexed",label:n.segments.deindexed,count:s.deindexed,color:ns.tone.negative},{key:"unknown",label:n.segments.unknown,count:s.unknown,color:ns.tone.neutral}].filter(l=>l.count>0);return e.jsxs(ot,{id:Ee["indexing-health"],eyebrow:n.eyebrow,title:n.title,intro:$h(s.provider),children:[e.jsx(sn,{columns:3,tiles:[{label:n.tiles.indexed,value:De(s.indexed),tone:"positive"},{label:n.tiles.total,value:De(s.total)},{label:n.tiles.share,value:Fe(s.indexedPct,Lt.percent)}]}),e.jsxs(Gn,{title:n.coverageHeading,children:[e.jsx(SN,{label:n.coverageLabel,segments:r}),e.jsx("ul",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1 text-[13px] text-secondary",children:r.map(l=>e.jsxs("li",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"size-2.5 shrink-0 rounded-sm",style:{background:l.color}}),Lh(l.label,l.count)]},l.key))})]})]})}function SN({label:t,segments:s}){const n=Object.fromEntries(s.map(a=>[a.key,a.count]));return e.jsx("div",{role:"img","aria-label":t,children:e.jsx(Us,{width:"100%",height:28,children:e.jsxs(Xc,{data:[n],layout:"vertical",margin:{top:0,right:0,bottom:0,left:0},barCategoryGap:0,accessibilityLayer:!1,children:[e.jsx(Vs,{type:"number",domain:[0,"dataMax"],hide:!0}),e.jsx(Hs,{type:"category",hide:!0}),s.map(a=>e.jsx(Zc,{dataKey:a.key,stackId:"coverage",fill:a.color,isAnimationActive:!1},a.key))]})})})}function CN({report:t}){const s=t.citationsTrend,n=rt["citations-trend"],a=Ee["citations-trend"];if(Ph(s))return e.jsx(ot,{id:a,eyebrow:n.eyebrow,title:n.title,children:e.jsx(Ot,{message:s.length===0?n.empty:Ih(s.length)})});const[r,l,i]=n.breakdownHeaders;return e.jsxs(ot,{id:a,eyebrow:n.eyebrow,title:n.title,intro:n.intro,children:[e.jsx(Lr,{title:n.chartTitle,data:s,xKey:"date",dataKey:"citationRate",color:ns.tone.positive,height:220,formatValue:o=>Fe(o,Lt.percent),dates:"observed"}),e.jsx(Et,{title:n.breakdownHeading,headers:[r,{label:l,numeric:!0},i],children:s.map(o=>e.jsxs("tr",{children:[e.jsx("td",{children:Ic(o.date)}),e.jsxs("td",{className:"text-right tabular-nums",children:[Fe(o.citationRate,Lt.percent)," ",e.jsxs("span",{className:"text-muted",children:["(",o.citedQueryCount,"/",o.totalQueryCount,")"]})]}),e.jsx("td",{children:Th(o.providerRates)})]},o.runId))})]})}function kN({report:t}){const s=rt.insights;if(t.insights.length===0)return e.jsx(ot,{id:Ee.insights,eyebrow:s.eyebrow,title:s.title,children:e.jsx(Ot,{message:s.empty})});const[n,a,r,l,i]=s.headers;return e.jsx(ot,{id:Ee.insights,eyebrow:s.eyebrow,title:s.title,intro:s.intro,children:e.jsx(Et,{headers:[{label:n,className:"w-24"},{label:a,className:"w-[28%]"},{label:r,className:"w-[18%]"},{label:l,className:"w-[88px]"},{label:i,className:"w-auto"}],tableClassName:"table-fixed min-w-[680px]",children:t.insights.map(o=>e.jsxs("tr",{children:[e.jsx("td",{className:"align-top",children:e.jsx(re,{tone:qc(o),children:Mc(o.severity)})}),e.jsxs("td",{className:"evidence-query-cell break-words align-top",children:[o.title,o.instanceCount>1&&e.jsx(re,{tone:"neutral",className:"ml-2",children:Ec(o.instanceCount)})]}),e.jsx("td",{className:"break-words align-top text-[13px] text-secondary",children:o.query}),e.jsx("td",{className:"break-words align-top text-[13px] text-secondary",children:o.provider}),e.jsx("td",{className:"break-words align-top text-[13px] text-secondary",children:o.recommendation?o.recommendation:e.jsx("span",{className:"text-muted",children:s.noRecommendation})})]},o.id))})})}function AN({report:t}){const s=rt["content-opportunities"],n=Tc(t),a=t.meta.project.canonicalDomain,[r,l,i,o,d,m,u,h]=s.headers;return e.jsxs(ot,{id:Ee["content-opportunities"],eyebrow:s.eyebrow,title:s.title,intro:s.intro,children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:n.slice(0,3).map((g,x)=>e.jsx(RN,{opportunity:g},`${x}-${g.targetRef}`))}),e.jsx(Et,{headers:[r,l,i,{label:o,numeric:!0,tooltip:s.scoreHeaderTooltip},d,m,u,h],children:n.slice(0,10).map((g,x)=>e.jsx(PN,{opportunity:g,canonicalDomain:a},`${x}-${g.targetRef}`))})]})}function RN({opportunity:t}){const s=rt["content-opportunities"];return e.jsxs("article",{className:"rounded-xl border border-default bg-surface p-4",children:[e.jsxs("div",{className:"mb-2.5 flex items-center gap-1.5",children:[e.jsxs("p",{className:"text-3xl font-extrabold leading-none tracking-tight tabular-nums text-heading",children:[Math.round(t.score),e.jsx("span",{className:"ml-1 text-sm font-semibold text-muted",children:s.scoreSuffix})]}),e.jsx(_e,{text:s.scoreCardTooltip})]}),e.jsx("h3",{className:"text-sm font-semibold text-heading","data-report-heading":!0,children:t.query}),e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:lx(t)}),e.jsx($r,{items:t.drivers,limit:2,className:"mt-3"})]})}function PN({opportunity:t,canonicalDomain:s}){const n=rt["content-opportunities"],a=t.winnabilityClass===$c.ceded;return e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:t.query}),e.jsx("td",{children:e.jsx(re,{tone:"neutral",children:Lc(t.action)})}),e.jsx("td",{children:e.jsx(re,{tone:a?"caution":"neutral",children:ox(t.winnabilityClass)})}),e.jsx("td",{className:"text-right tabular-nums",title:n.scoreHeaderTooltip,children:Math.round(t.score)}),e.jsx("td",{children:t.drivers.length>0?e.jsx("ul",{className:"list-disc space-y-0.5 pl-4 text-[13px] text-secondary",children:t.drivers.map((r,l)=>e.jsx("li",{children:r},l))}):e.jsx("span",{className:"text-[13px] text-secondary",children:n.noDriverSignal})}),e.jsx("td",{children:t.ourBestPage?e.jsx(Vi,{href:cx(t.ourBestPage.url,s),className:"break-all text-[13px]",children:t.ourBestPage.url}):e.jsx("span",{className:"text-[13px] text-secondary",children:n.noPage})}),e.jsx("td",{children:t.winningCompetitor?e.jsx(Vi,{href:t.winningCompetitor.url,className:"text-[13px]",children:t.winningCompetitor.domain}):e.jsx("span",{className:"text-muted",children:n.noWinningCompetitor})}),e.jsx("td",{children:e.jsx(re,{tone:"neutral",children:dx(t.actionConfidence)})})]})}function IN({report:t}){const s=rt["content-gaps"],[n,a,r,l]=s.headers;return e.jsx(ot,{id:Ee["content-gaps"],eyebrow:s.eyebrow,title:s.title,intro:s.intro,children:e.jsx(Et,{headers:[n,{label:a,numeric:!0},r,{label:l,numeric:!0}],children:t.contentGaps.slice(0,10).map((i,o)=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:i.query}),e.jsx("td",{className:"text-right tabular-nums",children:i.competitorCount}),e.jsx("td",{className:"text-[13px] text-secondary",children:Ah(i.competitorDomains,5)}),e.jsx("td",{className:"text-right tabular-nums",children:Rh(i.missRate)})]},`${o}-${i.query}`))})})}function ot({id:t,eyebrow:s,title:n,intro:a,children:r}){return e.jsxs("section",{id:t,"data-report-section":t,className:"page-section-divider",children:[e.jsx(TN,{eyebrow:s,title:n,subtitle:a??void 0}),r]})}function TN({eyebrow:t,title:s,subtitle:n}){return e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"eyebrow-soft","data-report-eyebrow":!0,children:t}),e.jsx("h2",{className:"page-title",children:s}),n&&e.jsx("p",{className:"page-subtitle mt-1","data-report-intro":!0,children:n})]})}function zd({title:t,tooltip:s}){return e.jsxs("div",{className:"mb-2 flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading","data-report-heading":!0,children:t}),s?e.jsx(Ps,{tooltip:s}):null]})}function Ps(t){return t.tooltip!==void 0?e.jsx("span",{className:"inline-flex","data-report-note":!0,children:e.jsx(_e,{text:t.tooltip})}):e.jsx("p",{className:`mt-2 text-[13px] text-secondary ${t.className??""}`,"data-report-note":!0,children:t.children})}function Gn({title:t,tooltip:s,children:n,className:a=""}){return e.jsxs("div",{className:`mt-4 rounded-xl border border-default bg-surface p-4 ${a}`,children:[t?e.jsx(zd,{title:t,tooltip:s}):null,n]})}function Et({title:t,tooltip:s,note:n,footnote:a,headers:r,children:l,className:i="",tableClassName:o=""}){return e.jsxs("div",{className:`mt-4 ${i}`,children:[t?e.jsx(zd,{title:t,tooltip:s}):null,n,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:`evidence-table ${o}`,children:[e.jsx("thead",{children:e.jsx("tr",{children:r.map((d,m)=>{const u=typeof d=="string"?{label:d}:d,h=[u.numeric?"text-right":"",u.className??""].filter(Boolean).join(" ");return e.jsx("th",{className:h||void 0,"aria-label":u.tooltip?u.label:void 0,children:u.tooltip?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[u.label,e.jsx(_e,{text:u.tooltip})]}):u.label},`${m}-${u.label}`)})})}),e.jsx("tbody",{children:l})]})}),a]})}function LN({label:t,value:s,tone:n,subtitle:a}){return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft","data-report-tile":!0,children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${tn[n??"neutral"]}`,children:s}),a?e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:a}):null]})}const $N={1:"",2:"sm:grid-cols-2",3:"sm:grid-cols-3",4:"sm:grid-cols-2 lg:grid-cols-4",5:"sm:grid-cols-2 lg:grid-cols-5"};function sn({tiles:t,columns:s=3}){return e.jsx("div",{className:`grid gap-3 ${$N[s]}`,children:t.map(n=>e.jsx(LN,{...n},n.label))})}function Oa({title:t,rows:s,scale:n}){const a=n==="share"?s.filter(i=>i.count>0||i.sharePct>0):s,r=s.reduce((i,o)=>i+o.count,0);if(a.length===0||n==="max"&&r===0)return null;const l=Math.max(...s.map(i=>i.count),1);return e.jsx(Gn,{title:t,children:e.jsx("div",{className:"space-y-3",children:a.map((i,o)=>{const d=n==="share"?Math.max(0,Math.min(100,i.sharePct)):i.count/l*100;return e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-neutral",title:i.label,children:i.label}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{"data-share-bar":!0,className:"h-full rounded-full",style:{width:`${d}%`,background:i.color}})})]}),e.jsx("span",{className:"whitespace-nowrap text-[13px] tabular-nums text-secondary",children:i.valueLabel})]},`${o}-${i.label}`)})})})}const ns={series:ct,tone:Kn};function MN(t){return t==="calendar"?{xTickFormatter:fn,labelFormatter:Tt}:{xTickFormatter:s=>zc(Dt(s)),labelFormatter:s=>oa(Dt(s))}}function Vi({href:t,children:s,className:n=""}){return e.jsx("a",{href:Ax(t),target:"_blank",rel:"noopener noreferrer",className:`text-link hover:underline ${n}`,children:s})}function Lr({title:t,data:s,xKey:n,dataKey:a,color:r,height:l=200,formatValue:i,dates:o}){if(s.length===0)return null;const d=o?MN(o):void 0;return e.jsx(Gn,{title:t,children:e.jsx(sl,{ariaLabel:ux(t),data:s,xKey:n,series:[{dataKey:a,label:t,color:r,axisId:"value",formatValue:i}],height:l,xTickFormatter:d?.xTickFormatter,labelFormatter:d?.labelFormatter})})}function Wd({title:t,rows:s,domainMax:n,rowHeight:a=32,track:r=!1,labelWidth:l=96}){if(s.length===0)return null;const i=n??Math.max(...s.map(d=>d.value),1),o=Math.max(s.length*a+24,80);return e.jsx(Gn,{title:t,children:e.jsx("div",{role:"img","aria-label":gx(t),children:e.jsx(Us,{width:"100%",height:o,children:e.jsxs(Xc,{data:[...s],layout:"vertical",margin:{top:4,right:72,bottom:4,left:0},accessibilityLayer:!1,children:[e.jsx(Vs,{type:"number",domain:[0,i],hide:!0}),e.jsx(Hs,{type:"category",dataKey:"label",width:l,tick:Qt,stroke:xs,tickLine:!1,axisLine:!1}),e.jsxs(Zc,{dataKey:"value",radius:3,isAnimationActive:!1,background:r?{fill:os.surface}:!1,children:[s.map((d,m)=>e.jsx(mg,{fill:d.color},`${m}-${d.label}`)),e.jsx(hg,{dataKey:"valueLabel",position:"right",fill:os.text,fontSize:11})]})]})})})})}function kr({page:t}){const s=hx(t);return e.jsxs("span",{className:"inline-flex min-w-0 flex-wrap items-baseline gap-x-2",children:[e.jsx("span",{className:"font-mono text-[13px] text-heading",children:s.path}),s.querySummary?e.jsx("span",{className:"text-[13px] text-secondary",title:s.raw,children:s.querySummary}):null]})}function $r({items:t,limit:s=3,className:n}){if(t.length===0)return null;const a=t.slice(0,s),r=t.length-a.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[a.map((l,i)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[13px] text-neutral",children:l},i)),r>0&&e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[13px] text-secondary",children:fx(r)})]})}function Ot({message:t}){return e.jsx("p",{className:"py-4 text-center text-sm text-secondary","data-report-empty":!0,children:t})}function qN({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=c.useState(!1),[l,i]=c.useState(!1),[o,d]=c.useState(null),[m,u]=c.useState(t.displayName),[h,g]=c.useState(t.canonicalDomain),[x,y]=c.useState(t.country),[p,v]=c.useState(t.language),[j,w]=c.useState(t.ownedDomains??[]),[I,k]=c.useState(""),[f,b]=c.useState(t.aliases??[]),[S,A]=c.useState(""),[P,C]=c.useState(null),[U,O]=c.useState(!1),[J,V]=c.useState(!1),[H,te]=c.useState(""),[D,$]=c.useState(""),[Q,B]=c.useState(""),[_,M]=c.useState(""),[W,ne]=c.useState(""),[ie,be]=c.useState(null),[ke,X]=c.useState(null);c.useEffect(()=>{a||(u(t.displayName),g(t.canonicalDomain),y(t.country),v(t.language),w(t.ownedDomains??[]),b(t.aliases??[]))},[t,a]);function le(){r(!1),d(null),u(t.displayName),g(t.canonicalDomain),y(t.country),v(t.language),w(t.ownedDomains??[]),b(t.aliases??[]),k(""),A("")}function je(){const T=I.trim();T&&(j.includes(T)||w([...j,T]),k(""))}function ee(T){w(j.filter(ye=>ye!==T))}function oe(){const T=S.trim();if(!T)return;const ye=T.toLowerCase();f.some(Ve=>Ve.toLowerCase()===ye)||b([...f,T]),A("")}function G(T){b(f.filter(ye=>ye!==T))}async function ue(){if(!(!m.trim()||!h.trim()||!x.trim()||!p.trim())){i(!0),d(null);try{await s(t.name,{displayName:m.trim(),canonicalDomain:h.trim(),ownedDomains:j,aliases:f,country:x.trim(),language:p.trim()}),r(!1),Oe({title:"Project settings saved",detail:`${m.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(T){d(T instanceof Error?T.message:"Failed to save")}finally{i(!1)}}}async function se(){const T=H.trim(),ye=D.trim(),Ve=Q.trim(),Ye=_.trim();if(!(!T||!ye||!Ve||!Ye)){O(!0),C(null);try{const et={label:T,city:ye,region:Ve,country:Ye};W.trim()&&(et.timezone=W.trim()),await Tx(t.name,et),n(),te(""),$(""),B(""),M(""),ne(""),V(!1),Oe({title:"Location added",detail:`${T} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${T}`,dedupeMode:"drop"})}catch(et){C(et instanceof Error?et.message:"Failed to add location")}finally{O(!1)}}}async function Se(T){O(!0),C(null);try{await Ix(t.name,T),n(),Oe({title:"Location removed",detail:`${T} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${T}`,dedupeMode:"drop"})}catch(ye){C(ye instanceof Error?ye.message:"Failed to remove location")}finally{O(!1)}}async function Ce(T){O(!0),C(null);try{await Px(t.name,T),n(),Oe({title:"Default location updated",detail:`${T} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(ye){C(ye instanceof Error?ye.message:"Failed to set default location")}finally{O(!1)}}async function Ie(T){be(T),X(null);try{await Lx(t.name,T),Oe({title:`${T.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(ye){X(ye instanceof Error?ye.message:"Could not download tracking results.")}finally{be(null)}}const Be=m!==t.displayName||h!==t.canonicalDomain||x!==t.country||p!==t.language||JSON.stringify(j)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(f)!==JSON.stringify(t.aliases??[]),qe=!ce()&&!Xs(),pe="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",F="mb-1 block text-sm font-medium text-secondary",Ke=H.trim()&&D.trim()&&Q.trim()&&_.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(L,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),o&&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:[o,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:F,children:"Display name"}),e.jsx("input",{className:pe,type:"text",value:m,onChange:T=>u(T.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:F,children:"Canonical domain"}),e.jsx("input",{className:pe,type:"text",value:h,onChange:T=>g(T.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:F,children:"Country"}),e.jsx("input",{className:pe,type:"text",value:x,onChange:T=>y(T.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:F,children:"Language"}),e.jsx("input",{className:pe,type:"text",value:p,onChange:T=>v(T.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:F,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:j.map(T=>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:[T,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>ee(T),"aria-label":`Remove ${T}`,children:"×"})]},T))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${pe} flex-1`,type:"text",placeholder:"docs.example.com",value:I,onChange:T=>k(T.target.value),onKeyDown:T=>T.key==="Enter"&&(T.preventDefault(),je())}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:!I.trim(),onClick:je,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:F,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(T=>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:[T,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>G(T),"aria-label":`Remove ${T}`,children:"×"})]},T))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${pe} flex-1`,type:"text",placeholder:"Facebook",value:S,onChange:T=>A(T.target.value),onKeyDown:T=>T.key==="Enter"&&(T.preventDefault(),oe())}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:!S.trim(),onClick:oe,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(L,{type:"button",disabled:l||!Be||!m.trim()||!h.trim(),onClick:tt(ue),children:l?"Saving...":"Save changes"}),e.jsx(L,{type:"button",variant:"outline",disabled:l,onClick:le,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(T=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:T},T))}):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(T=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:T},T))}):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(T=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:T},T))})})]}):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:[P&&e.jsxs("div",{className:"mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-xs text-negative",children:[P,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>C(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(T=>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 ${T.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[T.label,T.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:T.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:T.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:T.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:T.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[qe&&T.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:U,onClick:()=>{Ce(T.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${T.label} as default location`,children:"Set default"}),qe&&e.jsx("button",{type:"button",disabled:U,onClick:()=>{Se(T.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${T.label}`,children:"Remove"})]})})]},T.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),qe?J?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:pe,type:"text",value:H,onChange:T=>te(T.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:pe,type:"text",value:D,onChange:T=>$(T.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:pe,type:"text",value:Q,onChange:T=>B(T.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:pe,type:"text",value:_,onChange:T=>M(T.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:pe,type:"text",value:W,onChange:T=>ne(T.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(L,{type:"button",size:"sm",disabled:U||!Ke,onClick:tt(se),children:U?"Adding...":"Add location"}),e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:U,onClick:()=>{V(!1),C(null)},children:"Cancel"})]})]}):e.jsx(L,{type:"button",size:"sm",variant:"outline",onClick:()=>V(!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(L,{type:"button",variant:"outline",size:"sm",disabled:ie!==null,onClick:tt(()=>Ie("csv")),children:ie==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:ie!==null,onClick:tt(()=>Ie("json")),children:ie==="json"?"Preparing JSON...":"Download JSON"})]})]}),ke&&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:ke})]})]})]})}function ba(t){return{...t??{}}}function EN(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 o=a[i];return o?.[0]===r&&o[1]===l})}function DN({project:t,onSave:s}){const{isAdmin:n}=Fn(),a=Me({queryKey:["settings"],queryFn:yc,staleTime:6e4,enabled:n&&!ce()}),[r,l]=c.useState(t.providers.length===0),[i,o]=c.useState(t.providers),[d,m]=c.useState(()=>ba(t.providerModels)),[u,h]=c.useState({providers:t.providers,providerModels:ba(t.providerModels)}),[g,x]=c.useState(!1),[y,p]=c.useState(!1),[v,j]=c.useState(null),[w,I]=c.useState(null),k=c.useRef(null),f=a.data?.providerCatalog??[],b=c.useMemo(()=>new Set((a.data?.providers??[]).filter(V=>V.configured).map(V=>V.name)),[a.data]),S=c.useMemo(()=>{const V=new Map(a.data?.providers.map(te=>[te.name,te.model])),H=new Map(f.map(te=>[te.name,{...te,defaultModel:V.get(te.name)||te.defaultModel}]));for(const te of Object.keys(d))H.has(te)||H.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[...H.values()].sort((te,D)=>te.displayName.localeCompare(D.displayName))},[f,d,a.data?.providers]),A=!EN(d,u.providerModels);c.useEffect(()=>{if(g||y)return;const V={providers:t.providers,providerModels:ba(t.providerModels)};h(V),l(V.providers.length===0),o(V.providers),m(V.providerModels)},[t]);function P(){p(!0),l(!1),i.length===0&&o([...b])}function C(V,H,te=!1){p(!0),m(D=>{const $={...D};return H==="__inherit__"?delete $[V]:H==="__custom__"?$[V]=te?"":$[V]??"":$[V]=H,$}),H==="__custom__"&&queueMicrotask(()=>k.current?.focus())}function U(V,H){p(!0),o(te=>H?[...new Set([...te,V])]:te.filter(D=>D!==V))}function O(){p(!1),l(u.providers.length===0),o(u.providers),m(ba(u.providerModels)),j(null),I(null)}async function J(){if(!(a.isError||a.isLoading||!r&&i.length===0)){x(!0),j(null),I(null);try{const V=Object.fromEntries(Object.entries(d).filter(([te,D])=>D.trim()!==""&&(r||i.includes(te)))),H={providers:r?[]:i,providerModels:V};await s(H),h({providers:[...H.providers],providerModels:ba(H.providerModels)}),p(!1),I("Engine settings saved. They apply on the next sweep.")}catch(V){j(fr(V))}finally{x(!1)}}}return ce()||!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(L,{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(L,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):b.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(Bs,{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:()=>{p(!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:P})," Choose engines"]}),!r&&e.jsx("div",{className:"project-engine-list",children:S.map(V=>{const H=i.includes(V.name),te=b.has(V.name),D=H&&!te,$=d[V.name],Q=V.knownModels.some(_=>_.id===$),B=$===void 0?"__inherit__":Q?$:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:H,disabled:!te&&!H,onChange:_=>U(V.name,_.target.checked)})," ",e.jsx("span",{children:V.displayName}),D&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),H&&(V.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${V.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${V.name}`,value:B,onChange:_=>C(V.name,_.target.value,Q),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",V.defaultModel||"default"]}),V.knownModels.map(_=>e.jsx("option",{value:_.id,children:_.displayName},_.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),B==="__custom__"&&e.jsx("input",{ref:k,"aria-label":`${V.displayName} custom model ID`,value:$??"",onChange:_=>{p(!0),m(M=>({...M,[V.name]:_.target.value}))},"aria-describedby":`project-model-hint-${V.name}`}),e.jsxs("p",{id:`project-model-hint-${V.name}`,className:"project-engine-help",children:[$?"Project override":"Inherited from instance settings",". ",V.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},V.name)})})]}),!r&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),v&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:v}),w&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:w}),A&&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(L,{type:"button",onClick:()=>{J()},disabled:g||!r&&i.length===0,children:g?"Saving engines…":"Save engines"}),e.jsx(L,{type:"button",variant:"outline",onClick:O,disabled:g,children:"Cancel"})]})]})}const ur={edit:"Edit schedule",pause:"Pause",resume:"Resume",save:"Save schedule"},ON=[{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"}],ic=["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 Ni(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),o=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 ${o} · ${n}`}function FN({projectName:t}){const s=Ns(),n=!ce()&&!Xs()&&!s,a=ws(),[r,l]=c.useState(!1),[i,o]=c.useState("daily"),[d,m]=c.useState(6),[u,h]=c.useState(""),[g,x]=c.useState(14),[y,p]=c.useState(""),[v,j]=c.useState("00:00"),[w,I]=c.useState("UTC"),[k,f]=c.useState(!1),[b,S]=c.useState(""),[A,P]=c.useState(!1),[C,U]=c.useState(!1),[O,J]=c.useState(null),[V,H]=c.useState(void 0),te=$x({client:Y,path:{name:t}}),D=Me({...Kc({client:Y,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),$=D.isPending||D.isFetching,Q=D.isError,B=D.data?.find(ee=>ee.kind==="answer-visibility")??null,_=r&&V!==void 0&&(B?.updatedAt??null)!==V,M=ee=>{a.setQueryData(te,oe=>{const G=(oe??[]).filter(ue=>ue.kind!=="answer-visibility");return ee?[...G,ee]:G})},W=ee=>{if(ee){if(ee.recurrence)o("calendar"),x(ee.recurrence.everyDays),p(ee.recurrence.startDate),j(ee.recurrence.time);else{const G=Ox(ee.preset??null,ee.cronExpr);o(G.freq),m(G.hour),h(G.customCron)}const oe=ic.includes(ee.timezone);I(oe?ee.timezone:"Other"),f(!oe),S(oe?"":ee.timezone)}else o("daily"),m(6),h(""),x(14),p(""),j("00:00"),I("UTC"),f(!1),S("");H(ee?.updatedAt??null)},ne=()=>{n&&(W(B),J(null),l(!0))},ie=()=>{W(B),J(null)},be=async()=>{(await D.refetch()).isError?J("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):J(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},ke=async(ee,oe)=>{if(ee instanceof En&&ee.code==="SCHEDULE_VERSION_CONFLICT"){await be();return}J(ee instanceof Error?ee.message:oe)},X=async()=>{if(n&&!(_||V===void 0)){P(!0),J(null);try{const ee=await D.refetch();if(ee.isError||ee.data===void 0){J("Canonry could not verify the latest schedule. Try again before saving.");return}const oe=ee.data.find(Se=>Se.kind==="answer-visibility")??null;if((oe?.updatedAt??null)!==V)return;const ue={timezone:k?b.trim()||"UTC":w,enabled:oe?.enabled??!0,providers:oe?.providers??[],expectedUpdatedAt:V};i==="calendar"?ue.recurrence={everyDays:g,startDate:y,time:v}:i==="custom"?ue.cron=u.trim():ue.preset=Dx(i,d);const se=await Ml(t,ue);l(!1),H(void 0),M(se),Oe({title:"Schedule saved",detail:se.recurrence?Ni(se.recurrence,se.timezone):Gr(se.preset??null,se.cronExpr,se.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(ee){await ke(ee,"Failed to save schedule")}finally{P(!1)}}},le=async()=>{if(!n||!B)return;const ee=B.updatedAt;P(!0),J(null);try{const oe=await D.refetch();if(oe.isError||oe.data===void 0){J("Canonry could not verify the latest schedule. Try again before updating it.");return}const G=oe.data.find(Se=>Se.kind==="answer-visibility")??null;if(!G||G.updatedAt!==ee){J("This schedule changed elsewhere. Review the latest version and try again.");return}const ue={timezone:G.timezone,enabled:!G.enabled,providers:G.providers,expectedUpdatedAt:ee};G.recurrence?ue.recurrence=G.recurrence:G.preset?ue.preset=G.preset:ue.cron=G.cronExpr;const se=await Ml(t,ue);M(se),Oe({title:se.enabled?"Schedule resumed":"Schedule paused",detail:se.recurrence?Ni(se.recurrence,se.timezone):Gr(se.preset??null,se.cronExpr,se.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(oe){await ke(oe,"Failed to update schedule")}finally{P(!1)}},je=async()=>{if(!n||!B)return;const ee=B.updatedAt;U(!0),J(null);try{await Ex(t,ee),M(null),l(!1),H(void 0),Oe({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(oe){await ke(oe,"Failed to remove schedule")}finally{U(!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&&!$&&!Q&&!r&&e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:ne,children:B?ur.edit:"+ Set schedule"})]}),$&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),O&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:O}),!$&&Q&&e.jsxs(ve,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(L,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{D.refetch()},children:"Retry"})]}),!$&&!Q&&!r&&B===null&&e.jsx(ve,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?aa:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!$&&!Q&&!r&&B!==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:aa}),e.jsx("p",{className:"text-sm font-medium text-strong",children:B.recurrence?Ni(B.recurrence,B.timezone):Gr(B.preset??null,B.cronExpr,B.timezone)}),!B.recurrence&&e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:B.cronExpr})]}),B.enabled&&B.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",Mx(B.nextRunAt,B.timezone)]}),B.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(B.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(re,{tone:B.enabled?"positive":"neutral",children:B.enabled?"Active":"Paused"}),n&&e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:A,onClick:tt(le),children:B.enabled?ur.pause:ur.resume}),n&&e.jsx(L,{type:"button",variant:"ghost",size:"sm",disabled:C,onClick:tt(je),children:C?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[_&&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(L,{type:"button",variant:"outline",size:"sm",onClick:ie,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:ee=>o(ee.target.value),children:ON.map(ee=>e.jsx("option",{value:ee.value,children:ee.label},ee.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:ee=>m(parseInt(ee.target.value)),children:Array.from({length:24},(ee,oe)=>e.jsx("option",{value:oe,children:qx(oe)},oe))})]})]}),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:ee=>h(ee.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:ee=>x(Number(ee.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:ee=>p(ee.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Recurrence time",type:"time",value:v,onChange:ee=>j(ee.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":w,onChange:ee=>{ee.target.value==="Other"?(f(!0),I("Other")):(f(!1),I(ee.target.value))},children:[ic.map(ee=>e.jsx("option",{value:ee,children:ee},ee)),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:b,onChange:ee=>S(ee.target.value)})]}),O&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:O}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>{l(!1),H(void 0),J(null)},children:"Cancel"}),e.jsx(L,{type:"button",size:"sm",disabled:A||D.isFetching||Q||_||i==="custom"&&!u.trim()||i==="calendar"&&(!Number.isInteger(g)||g<1||g>3650||!y||!v),onClick:tt(X),children:A?"Saving...":ur.save})]})]})]})}const KN=[{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 GN({projectName:t}){const[s,n]=c.useState("loading"),[a,r]=c.useState(!1),[l,i]=c.useState(""),[o,d]=c.useState(["citation.lost","citation.gained"]),[m,u]=c.useState(!1),[h,g]=c.useState(null),[x,y]=c.useState({}),[p,v]=c.useState(new Set),j=!ce()&&!Xs();c.useEffect(()=>{Fx(t).then(n).catch(()=>n([]))},[t]);const w=b=>{d(S=>S.includes(b)?S.filter(A=>A!==b):[...S,b])},I=async()=>{if(!(!l.trim()||o.length===0)){u(!0),g(null);try{const b=await Kx(t,{channel:"webhook",url:l.trim(),events:o});n(S=>S==="loading"?[b]:[...S,b]),i(""),d(["citation.lost","citation.gained"]),r(!1),Oe({title:"Webhook added",detail:`Notifications will be sent to ${b.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(b){g(b instanceof Error?b.message:"Failed to add webhook")}finally{u(!1)}}},k=async b=>{if(!p.has(b)){v(S=>new Set(S).add(b));try{await _x(t,b),n(S=>S==="loading"?S:S.filter(A=>A.id!==b)),Oe({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${b}`,dedupeMode:"drop"})}catch(S){g(S instanceof Error?S.message:"Failed to remove webhook")}finally{v(S=>{const A=new Set(S);return A.delete(b),A})}}},f=async b=>{y(S=>({...S,[b]:{state:"testing"}}));try{const S=await Gx(t,b);y(A=>({...A,[b]:{state:S.ok?"ok":"fail",status:S.status}})),S.ok&&Oe({title:"Test notification sent",detail:`Webhook returned status ${S.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${b}`,dedupeMode:"replace"})}catch{y(S=>({...S,[b]:{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"})]}),j&&s!=="loading"&&e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),g(null)},children:a?"Cancel":"+ Add webhook"})]}),j&&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:b=>i(b.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:KN.map(b=>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:o.includes(b.value),onChange:()=>w(b.value)}),e.jsx("span",{className:"text-sm text-neutral",children:b.label})]},b.value))})]}),h&&e.jsx("p",{className:"text-negative-400 text-sm",children:h}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),g(null)},children:"Cancel"}),e.jsx(L,{type:"button",size:"sm",disabled:m||!l.trim()||o.length===0,onClick:tt(I),children:m?"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(b=>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:b.urlHost,children:b.urlDisplay??b.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:b.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(re,{tone:b.enabled?"positive":"neutral",children:b.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[x[b.id]&&(()=>{const S=x[b.id],A=S.state==="testing"?"Sending…":S.state==="ok"?`Delivered${S.status?` (${S.status})`:""}`:`Failed${S.status?` (${S.status})`:""}`;return e.jsx(re,{tone:S.state==="ok"?"positive":S.state==="fail"?"negative":"neutral",children:A})})(),j&&e.jsx(L,{variant:"ghost",size:"sm",type:"button",disabled:x[b.id]?.state==="testing",onClick:()=>{f(b.id)},children:"Test"}),j&&e.jsx(L,{variant:"ghost",size:"sm",type:"button",disabled:p.has(b.id),onClick:()=>{k(b.id)},children:p.has(b.id)?"Removing…":"Remove"})]})})]},b.id))})]}),h&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:h})]})]})}function _N({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:l}){return ce()||Ns()?null:e.jsx(Ux,{open:t,onOpenChange:n,children:e.jsxs(Vx,{onCloseAutoFocus:i=>{r&&(i.preventDefault(),r())},children:[e.jsxs(Hx,{children:[e.jsx(Qx,{children:"Run AI sweep for the whole project?"}),e.jsxs(zx,{children:["Runs all tracked queries for ",s,". Report filters do not limit the sweep. Provider charges apply."]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsx(L,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(Ze,{disabled:l,onClick:a,children:"Run project-wide sweep"})]})]})})}const lc=2e3,oc=3e5;function BN(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function UN(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 VN({projectName:t,refreshNonce:s}){const n=ws(),[a,r]=c.useState(null),[l,i]=c.useState([]),[o,d]=c.useState(null),[m,u]=c.useState([]),[h,g]=c.useState([]),[x,y]=c.useState(null),[p,v]=c.useState(""),[j,w]=c.useState(""),[I,k]=c.useState(""),[f,b]=c.useState(!0),[S,A]=c.useState(!1),[P,C]=c.useState(null),[U,O]=c.useState("performance");c.useEffect(()=>{J()},[t,s]);async function J(){b(!0),C(null);try{const M=await n.fetchQuery({...Hc({client:Y,path:{name:t}}),staleTime:ts});if(r(M),M.connected){const[W,ne,ie,be]=await Promise.all([n.fetchQuery({...Mp({client:Y,path:{name:t}}),staleTime:ts}).catch(()=>null),n.fetchQuery({...qp({client:Y,path:{name:t}}),staleTime:ts}).catch(()=>[]),n.fetchQuery({...Ep({client:Y,path:{name:t}}),staleTime:ts}).catch(()=>[]),M.siteUrl?Promise.resolve([]):n.fetchQuery({...Dp({client:Y,path:{name:t}}),staleTime:ts}).then(ke=>ke.sites).catch(()=>[])]);d(W),u(ne),g(ie),i(be)}else d(null),u([]),g([]),i([])}catch(M){C(M instanceof Error?M.message:"Failed to load Bing data")}finally{b(!1)}}async function V(){if(j.trim()){C(null);try{const M=await Op(t,j.trim());await qt(n,"bing"),w(""),M.availableSites.length>0&&i(M.availableSites),await J()}catch(M){C(M instanceof Error?M.message:"Failed to connect")}}}async function H(){try{await Fp(t),await qt(n,"bing"),r(null),i([]),d(null),u([]),g([]),y(null),k(""),C(null)}catch(M){C(M instanceof Error?M.message:"Failed to disconnect")}}async function te(){if(I)try{await Kp(t,I),await qt(n,"bing"),await J()}catch(M){C(M instanceof Error?M.message:"Failed to set site")}}async function D(){if(p.trim())try{const M=await Gp(t,p.trim());await qt(n,"bing"),y(M),u(W=>[M,...W])}catch(M){C(M instanceof Error?M.message:"Inspection failed")}}async function $(M){A(!0),C(null);try{const W=await Dl(t,{urls:[M]}),{succeeded:ne,failed:ie,total:be}=W.summary;Oe({title:"Bing submission requested",detail:ie===0?`${ne} URL submitted to Bing.`:`${ne}/${be} submitted successfully, ${ie} failed.`,tone:ie===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${M}`,dedupeMode:"replace"})}catch(W){const ne=W instanceof Error?W.message:"Submission failed";C(ne),Oe({title:"Bing submission failed",detail:ne,tone:"negative",dedupeKey:`bing:indexing:${t}:${M}`,dedupeMode:"replace"})}finally{A(!1)}}async function Q(){A(!0),C(null),Oe({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const M=await Dl(t,{allUnindexed:!0}),{succeeded:W,failed:ne,total:ie}=M.summary;Oe({title:"Bing submissions requested",detail:ne===0?`${W}/${ie} URL${ie!==1?"s":""} submitted to Bing.`:`${W}/${ie} submitted successfully, ${ne} failed.`,tone:ne===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(M){const W=M instanceof Error?M.message:"Batch submission failed";C(W),Oe({title:"Bing submissions failed",detail:W,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{A(!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 ce()?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(re,{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(re,{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:j,onChange:M=>w(M.target.value),onKeyDown:M=>{M.key==="Enter"&&V()}}),e.jsx(Ze,{size:"sm",disabled:!j.trim(),onClick:tt(V),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"})]})]}),P&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:P})]});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(re,{tone:"positive",children:"Connected"}),!ce()&&e.jsx(Ze,{size:"sm",variant:"ghost",onClick:tt(H),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.domain})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?ss(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:I,onChange:M=>k(M.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(M=>e.jsxs("option",{value:M.url,children:[M.url,M.verified?" (verified)":""]},M.url))]}),!ce()&&e.jsx(Ze,{size:"sm",disabled:!I,onClick:tt(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."})]})]}),P&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:P})]});const B=[{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"}],_=B.find(M=>M.key===U)??B[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(re,{tone:"positive",children:"Connected"}),!ce()&&e.jsx(Ze,{size:"sm",variant:"ghost",onClick:tt(H),children:"Disconnect"})]})]}),P&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:P}),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?ss(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:_.eyebrow}),e.jsx("h3",{children:_.title})]}),e.jsx("p",{className:"text-xs text-muted",children:o?.lastInspectedAt?`Last inspected ${ss(o.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:B.map(M=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${U===M.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>O(M.key),children:M.label},M.key))}),U==="coverage"&&o&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ya,{label:"Indexed",value:o.summary.indexed,tone:"positive"}),e.jsx(Ya,{label:"Not in index",value:o.summary.notIndexed+(o.summary.unknown??0),tone:"negative"}),e.jsx(Ya,{label:"Status unknown",value:o.summary.unknown??0,tone:"neutral"}),e.jsx(Ya,{label:"Coverage",value:Fe(o.summary.percentage,Lt.percent),tone:"neutral"})]}),o.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 (",o.notIndexed.length,")"]}),!ce()&&e.jsx(Ze,{size:"sm",variant:"ghost",disabled:S,onClick:tt(Q),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"}),!ce()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:o.notIndexed.map(M=>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:M.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:M.httpCode??"—"}),!ce()&&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:()=>{$(M.url)},children:"Submit"})})]},M.id))})]})})]}),(o.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 (",(o.unknown??[]).length,")"]}),!ce()&&e.jsx(Ze,{size:"sm",variant:"ghost",disabled:S,onClick:tt(Q),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"}),!ce()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(o.unknown??[]).map(M=>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:M.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:M.lastCrawledDate?ss(M.lastCrawledDate):"—"}),!ce()&&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:()=>{$(M.url)},children:"Submit"})})]},M.id))})]})})]}),o.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",o.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:o.indexed.map(M=>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:M.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:M.lastCrawledDate?ss(M.lastCrawledDate):"—"})]},M.id))})]})})]})]}),U==="coverage"&&!o&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),U==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!ce()&&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:p,onChange:M=>v(M.target.value),onKeyDown:M=>{M.key==="Enter"&&D()}}),e.jsx(Ze,{size:"sm",disabled:!p.trim(),onClick:tt(D),children:"Inspect"})]}),x&&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:x.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:x.inIndex?"text-positive-400":"text-negative-400",children:x.inIndex?"Yes":"No"})," · ","HTTP: ",x.httpCode??"—"," · ","Crawled: ",x.lastCrawledDate??"—"]})]}),m.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:m.map(M=>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:M.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(re,{tone:M.inIndex?"positive":"negative",children:M.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:M.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:ss(M.inspectedAt)})]},M.id))})]})})]}),U==="performance"&&e.jsx("div",{className:"mt-4",children:h.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:za[$n.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:za[$n.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:za[$n.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:za[$n.Position]})]})}),e.jsx("tbody",{children:h.map((M,W)=>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:M.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:M.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:M.impressions}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:Fe(M.ctr)}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:M.averagePosition.toFixed(1)})]},W))})]})})})]})]})}function HN({projectName:t}){const s=ws(),[n,a]=c.useState("google"),[r,l]=c.useState(!0),[i,o]=c.useState("idle"),[d,m]=c.useState(null),u=c.useRef(null),[h,g]=c.useState(null),[x,y]=c.useState(null),[p,v]=c.useState(0);async function j(I=!1){I||l(!0),m(null);try{const[k,f]=await Promise.all([s.fetchQuery({...Wi({client:Y,path:{name:t}}),staleTime:ts}).catch(()=>[]),s.fetchQuery({...Hc({client:Y,path:{name:t}}),staleTime:ts}).catch(()=>null)]),b=k.find(S=>S.connectionType==="gsc")??null;g(b),y(f)}catch(k){m(k instanceof Error?k.message:"Failed to load search engine connections")}finally{l(!1)}}async function w(){if(i!=="idle")return;u.current?.abort();const I=new AbortController;u.current=I;const k=I.signal;o("syncing"),m(null),Oe({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=[],b=[];try{async function S(){if(!h)return;const C=await Lp(t);if(!C?.id)return;const U=Date.now()+oc;for(;Date.now()<U;){if(k.aborted||(await new Promise(J=>setTimeout(J,lc)),k.aborted))return;const O=await wi(C.id).catch(()=>null);if(!O)break;if(["completed","failed","cancelled"].includes(O.status)){O.status!=="completed"&&f.push(`Google sync ${O.status}`);return}}b.push("Google sync is still running — search data will appear shortly")}async function A(){if(!x?.connected)return;const C=await $p(t).catch(()=>null);if(!C?.id){f.push("Bing sweep could not be started");return}const U=Date.now()+oc;for(;Date.now()<U;){if(k.aborted||(await new Promise(J=>setTimeout(J,lc)),k.aborted))return;const O=await wi(C.id).catch(()=>null);if(!O)break;if(["completed","failed","cancelled","partial"].includes(O.status)){O.status==="failed"?f.push("Bing sweep failed"):O.status==="partial"&&b.push("Bing sweep finished with some pages unverified");return}}b.push("Bing sweep is still running — coverage will update shortly")}const P=await Promise.allSettled([S(),A()]);for(const C of P)C.status==="rejected"&&f.push(C.reason instanceof Error?C.reason.message:"Sync failed");if(await Promise.all([qt(s,"gsc"),qt(s,"bing")]),k.aborted)return;if(o("reloading"),await j(!0),v(C=>C+1),f.length>0){const C=`Partial refresh: ${[...f,...b].join("; ")}`;m(C),Oe({title:"Search coverage partially refreshed",detail:C,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else b.length>0?Oe({title:"Search coverage refresh incomplete",detail:b.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):Oe({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 A=S instanceof Error?S.message:"Refresh failed";m(A),Oe({title:"Search coverage refresh failed",detail:A,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{k.aborted||o("idle")}}return c.useEffect(()=>(j(),()=>{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(([I,k])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===I,className:`project-subnav-link ${n===I?"project-subnav-link-active":""}`,onClick:()=>a(I),children:k},I))}),!ce()&&e.jsxs(Ze,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{w()},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(Bf,{projectName:t,refreshNonce:p}),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(VN,{projectName:t,refreshNonce:p})]})]})}function cc({label:t,summary:s,displayValue:n,tooltip:a}){const{figure:r,sign:l}=Hi(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(_e,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${Aa[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 QN({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(ra,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:r})]})}function zN({insights:t,suggestedQueries:s,onManageQueries:n}){const{openEvidence:a}=Qi(),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(re,{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((x,y)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(Ai,{state:x.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:x.query}),x.provider?e.jsx(Tp,{provider:x.provider}):null,!ce()&&x.evidenceId?e.jsx(L,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(x.evidenceId)},children:"View evidence"}):null]},x.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(L,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},g.query),o=t.slice(0,1),d=r.slice(0,1),m=t.slice(1),u=r.slice(1),h=m.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:[o.map(l),d.map(i)]}),h>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:[h," more ",h===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[m.map(l),u.map(i)]})]}):null]})}function mw(t){const{projectName:s}=Jd({from:"/projects/$projectName"}),a=Gc()?.dashboard.projects.find(b=>b.project.name===s||b.project.id===s)?.project.name??null,r=Me({...Bx({client:Y}),enabled:!a}),l=a??r.data?.find(b=>b.name===s||b.id===s)?.name??null,i=_c(),o=Bc(t.tab,Uc(i)),[d,m]=c.useState(null),u=l!==null&&d===l,h=c.useCallback(()=>{l&&m(l)},[l]),{commandCenter:g,isLoading:x,overviewLoading:y,overviewError:p,isError:v,latestVisibilityRevision:j,competitorHistoryRevision:w,refetch:I}=Vc(l,{overview:o==="overview"&&u}),k=!a&&r.isLoading||x;return!l&&!a&&r.isSuccess&&!x?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(L,{asChild:!0,children:e.jsx(Bs,{to:"/",children:"Return to overview"})})]})}):!g&&(v||r.isError)?e.jsxs("div",{className:"page-container",role:"alert",children:[e.jsx("p",{children:"Could not load this project."}),e.jsx(L,{type:"button",variant:"outline",onClick:()=>{Promise.all([r.refetch(),I()])},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(b=>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"})]},b))}),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(b=>e.jsx("div",{className:"skeleton-text-sm w-full"},b))})]})]}):e.jsx(ZN,{model:g,refetch:I,latestVisibilityRevision:j,competitorHistoryRevision:w,overviewLoading:y,overviewError:p,overviewRequested:u,onRequestOverview:h,...t})}function WN({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=c.useRef(null),l=c.useRef(null),[i,o]=c.useState(null);c.useLayoutEffect(()=>{const u=r.current,h=l.current;if(!u||!h)return;const g=()=>{const y=u.getBoundingClientRect().width;if(!y)return;const p=Number.parseFloat(getComputedStyle(u).columnGap)||0,v=new Map([...h.querySelectorAll("[data-project-tab]")].map(b=>[b.dataset.projectTab,b.getBoundingClientRect().width])),j=b=>v.get(b)??0,w=b=>b.reduce((S,A)=>S+j(A),0)+Math.max(0,b.length-1)*p,I=[...t.map(b=>b.key),...s.length?["more"]:[],...n?[n.key]:[]];let k=t.map(b=>b.key),f=!1;if(w(I)>y){const b=t.find(P=>P.key===a),S=b?[b.key]:[];f=!!(n&&w([...S,"more",n.key])>y);const A=["more",...n&&!f?[n.key]:[]];for(const P of t)if(P.key!==b?.key){if(w([...S,P.key,...A])>y)break;S.push(P.key)}k=t.filter(P=>S.includes(P.key)).map(P=>P.key)}o(b=>b?.settingsInMore===f&&b.visibleKeys.join()===k.join()?b:{visibleKeys:k,settingsInMore:f})};if(g(),typeof ResizeObserver>"u")return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g);const x=new ResizeObserver(g);return x.observe(u),x.observe(h),()=>x.disconnect()},[t,s,n,a]);const d=i?t.filter(u=>i.visibleKeys.includes(u.key)):t,m=[...t.filter(u=>!d.includes(u)),...s,...i?.settingsInMore&&n?[n]:[]];return e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",ref:r,children:[e.jsx("div",{className:"project-subnav-measure","aria-hidden":"true",children:e.jsxs("div",{className:"project-subnav-measure-row",ref:l,children:[[...t,...n?[n]:[]].map(u=>e.jsx("span",{className:"project-subnav-link","data-project-tab":u.key,children:u.label},u.key)),e.jsxs("span",{className:"project-subnav-link project-subnav-more-trigger","data-project-tab":"more",children:["More",e.jsx(ra,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),d.map(u=>e.jsx(Bs,{to:u.href,search:h=>({...h,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(YN,{items:m,activeTab:a}),n&&!i?.settingsInMore&&e.jsx(Bs,{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 YN({items:t,activeTab:s}){const[n,a]=c.useState(!1),r=c.useRef(null),l=c.useRef(null),i=c.useRef("first"),o=c.useId(),d=t.map(u=>u.key).join();if(c.useEffect(()=>{a(!1)},[d]),c.useEffect(()=>{if(!n)return;const u=r.current?.querySelectorAll('[role="menuitem"]');(i.current==="last"?u?.[u.length-1]:u?.[0])?.focus()},[n]),c.useEffect(()=>{if(!n)return;const u=g=>{r.current&&!r.current.contains(g.target)&&a(!1)},h=g=>{g.key==="Escape"&&(a(!1),l.current?.focus())};return document.addEventListener("pointerdown",u),document.addEventListener("keydown",h),()=>{document.removeEventListener("pointerdown",u),document.removeEventListener("keydown",h)}},[n]),t.length===0)return null;const m=t.some(u=>u.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",ref:l,className:`project-subnav-link project-subnav-more-trigger ${m?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?o: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(ra,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:o,"aria-label":"More project sections",onKeyDown:u=>{const h=[...u.currentTarget.querySelectorAll('[role="menuitem"]')],g=h.indexOf(document.activeElement),x=u.key==="Home"?0:u.key==="End"?h.length-1:u.key==="ArrowDown"?(g+1)%h.length:u.key==="ArrowUp"?(g-1+h.length)%h.length:null;x!==null&&(u.preventDefault(),h[x]?.focus())},onBlur:u=>{r.current?.contains(u.relatedTarget)||a(!1)},children:t.map(u=>e.jsx(Bs,{to:u.href,search:h=>({...h,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 JN=20,XN=5;function ZN({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r,overviewLoading:l,overviewError:i,overviewRequested:o,onRequestOverview:d}){const m=Xd(),u=ws(),{account:h,canWrite:g}=Fn(),[x,y]=c.useState(null),p=c.useRef(null),v=Gc(),j=s.project.name,w=v?.dashboard.projects.some(q=>q.project.name===j)??!1,I=Zd({strict:!1}),k=Wx(I),f=fg(k),b=Me({...Yx({client:Y,path:{name:j}}),enabled:!ce()&&!!j&&(g||t==="portfolio"||t==="overview"||t==="settings"||f),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),S=v?v.dashboard.settings.providerStatuses.filter(q=>q.state==="ready").map(q=>ql(q.name)):void 0,A=b.data?.answerVisibilityProviderReady,P=S,C=s.project.providers.map(ql),U=P?.some(q=>C.length===0||C.includes(q))===!0,O=C.length===0||C.includes(Jx),J=Me({...Xx({client:Y}),enabled:!ce()&&g&&A===void 0&&O&&!U,staleTime:6e4,retry:!1}),V=O?J.isSuccess?typeof J.data.browserVersion=="string":J.isError?!1:void 0:!1,H=A??Zx({projectProviders:C,configuredApiProviders:P,cdpConfigured:V}),te=c.useMemo(()=>Uc(_c()),[]),D=Bc(t,te),$=c.useMemo(()=>s.competitors.map(q=>q.domain),[s.competitors]),[Q,B]=c.useState(!1),[_,M]=c.useState(!1),W=ep(),ne=c.useCallback((q,ge)=>{m({to:".",search:fe=>tp(fe,q),replace:ge?.replace===!0})},[m]),ie=I.queryWorkspace==="research"||D==="discovery"&&I.queryWorkspace===void 0?"research":"tracked",be=td(ie,ed(h?.role,h?.role==="viewer"?Ac():null)),ke=Me({...Ji({client:Y,path:{name:j}}),enabled:!ce()&&(D==="queries"||D==="discovery")&&be==="tracked"}),X=I.manageQueries===!0,le=c.useCallback(()=>{m({to:".",replace:!0,search:q=>({...q,siteHealthRunId:void 0})})},[m]),[je,ee]=c.useState(X),[oe,G]=c.useState(""),[ue,se]=c.useState(!1),[Se,Ce]=c.useState(null),[Ie,Be]=c.useState("30d"),[qe,pe]=c.useState(void 0),[F,Ke]=c.useState(""),[T,ye]=c.useState(!1),[Ve,Ye]=c.useState(null),[et,xe]=c.useState(!1),ft=sp(I),[ze,nt]=c.useState(void 0),[as,xt]=c.useState(void 0),at=c.useCallback(q=>{nt(q.search),q.sort&&xt(q.sort),m({to:".",search:ge=>({...ge,...np(q)}),replace:!1})},[m]),[yt,At]=c.useState(!1),$t=s?.project.displayName||s?.project.name||j,He=ap(),R=Me({...El({client:Y,path:{name:j}}),enabled:D==="portfolio"&&!!j,staleTime:0,refetchOnMount:"always"}),Ae=Me({...rp({client:Y,path:{name:j}}),enabled:!ce()&&!!j&&(g||D==="portfolio"||D==="overview"||D==="settings"),staleTime:0,refetchOnMount:"always"}),me=Ae.data?.active??null,Je=Ae.data!==void 0,Ft=new Set(me&&Number(me.plan.schemaVersion)===2?me.plan.groups?.map(q=>q.stableKey)??[]:[]),ut={...ft.scope==="group"&&!!ft.groupKey&&Je&&!Ft.has(ft.groupKey)?{scope:"all",queryClass:ft.queryClass}:ft,...ze?{search:ze}:{}},Z=me===null?null:Number(me.plan.schemaVersion),Ge=me?.revision??0,Te=Je?`${j}:${Ge}`:null,Pe=c.useRef(null);c.useEffect(()=>{const q=Pe.current;Te!==null&&(Pe.current=Te),ip(q,Te)&&(at({scope:"all",queryClass:"all"}),At(!1))},[Te,at]);const Gt={client:Y,path:{name:j},query:{scope:ut.scope,...ut.groupKey?{groupKey:ut.groupKey}:{},queryClass:ut.queryClass,...ut.search?{search:ut.search}:{},...as?{sort:as}:{},limit:50}},St=dc({...lp(Gt),enabled:!1,initialPageParam:Gt,getNextPageParam:(q,ge)=>{if(!q.properties.nextCursor)return;const fe=ge[0]?.measurement.displayedRunId;return{path:Gt.path,query:{...Gt.query,cursor:q.properties.nextCursor,...fe?{runId:fe}:{}}}},placeholderData:Ar,staleTime:0,refetchOnMount:"always"}),rs=St.data?.pages[0]?.measurement.displayedRunId,it=Me({...op({client:Y,path:{name:j},query:{revision:Ge,...rs?{runId:rs}:{}}}),enabled:D==="overview"&&!!j&&me!==null&&Z===1,staleTime:0,refetchOnMount:"always"}),_t=Ae.data!==void 0,cs=R.data!==void 0,Is=Ae.isPending&&!_t,Ts=Ae.isError&&!_t,Ls=R.isPending&&!cs,nn=R.isError&&!cs,jt=it.data!==void 0,Ss=Tj({activePlanSchemaVersion:b.data?.activeSchemaVersion??Z,hasDraft:b.data?.draft!==null&&b.data?.draft!==void 0}),st=Ss.surface==="simple-overview",zt=b.data===void 0&&Ae.data===void 0&&(Ae.isLoading||b.isLoading);c.useEffect(()=>{D==="overview"&&st&&!zt&&d()},[zt,st,d,D]);const ds=yg({tab:D,surface:zt?"unresolved":Ss.surface,embedded:ce(),scoped:f,queryWorkspace:be,tracking:ke.isError?{state:"error"}:ke.data?{state:"ready",mode:ke.data.mode,scopeUnavailable:sd(ke.data,k)}:{state:"pending"}}),ps=jd(j,k,{enabled:ds.kind==="report-picker"}),Cs=D==="overview"&&st&&!zt,Rt=Vc(j,{evidence:Cs}),Mt=Rt.commandCenter?.visibilityEvidence??s.visibilityEvidence,us=c.useMemo(()=>{const q=new Map(Mt.map(fe=>[na(fe.query),fe.queryClass??null])),ge=cp(dp(s.project));return fe=>{const vt=q.get(na(fe));return vt!==void 0?vt:ge?.classify(fe)??null}},[Mt,s.project]),Wt=c.useMemo(()=>[...new Set([...Mt.map(q=>q.query),...s.movementComparison.addedQueries,...s.movementComparison.removedQueries])],[Mt,s.movementComparison]),an=c.useMemo(()=>s.visibilitySweeps.map(q=>q.createdAt),[s.visibilitySweeps]),Ct=g&&!ce()&&!Ns()&&D!=="overview",is=Me({...El({client:Y,path:{name:j}}),enabled:Ct,staleTime:Yi,refetchOnWindowFocus:"always"}),bt=Z===2&&k.measurementScope==="group"?k.measurementScopeKey:void 0,K=Z===2&&k.measurementScope==="project",ae=c.useMemo(()=>{if(!(me?.plan.schemaVersion!==2||!bt))return me.plan.groups.find(q=>q.stableKey===bt)},[me,bt]),Re={client:Y,path:{name:j},query:{window:Ie,queryClass:Z===2&&k.queryClass!=="unknown"?k.queryClass:"non-brand",...bt?{groupKey:bt}:{},...K?{scope:"all-markets"}:{}}},he=D==="overview"&&!k.marketKey&&!!j&&(st||Je)&&!zt&&(st||(k.measurementScope==="project"||Z===2&&k.measurementScope==="group")&&k.queryClass!=="unknown"&&(Z===2||k.queryClass!=="branded")),[Le,Qe]=c.useState(null);c.useEffect(()=>{he||Qe(null)},[he]),c.useEffect(()=>{Qe(null)},[j]);const gt=Le===j,Nt=he&&gt,ms=Me({...up(Re),enabled:Nt,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});mp(j,JSON.stringify([r,s.competitors.map(q=>q.domain).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,Ge,b.data?.draft?.etag??null]),Nt);const E=ms.isError?ms.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,Ne=c.useMemo(()=>s.competitors.map(q=>({domain:q.domain,label:q.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:q.citationCount,answeredResults:q.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),mt=c.useMemo(()=>{if(me?.plan.schemaVersion!==2)return Ne;const q=bt?ae?.competitors??[]:me.plan.groups.flatMap(fe=>fe.competitors),ge=new Map;for(const fe of q){const vt=fe.domain.trim().toLowerCase();!vt||ge.has(vt)||ge.set(vt,{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 Ne){const vt=fe.domain.trim().toLowerCase();!vt||ge.has(vt)||ge.set(vt,fe)}return[...ge.values()]},[me,bt,Ne,ae]),Bt=Z===2?mt:Ne,ls=Ht({...hp({client:Y}),meta:{skipGlobalErrorToast:!0}}),We=b.data!==void 0?"success":b.isError?"error":"pending",wt=c.useMemo(()=>{const q=St.data?.pages;return q?!Up(q):!1},[St.data]),gs=c.useMemo(()=>{const q=St.data?.pages,ge=q?.[0],fe=q?.at(-1);if(!(!ge||!fe||wt))return{...ge,properties:{...ge.properties,items:q.flatMap(vt=>vt.properties.items),nextCursor:fe.properties.nextCursor}}},[wt,St.data]),ca=c.useMemo(()=>{if(me)return me.plan.schemaVersion===1?it.data?Fj(me,it.data):void 0:gs?Vp({overview:gs,activePlan:me,sort:as,report:it.data,reportState:gs.measurement.displayedRunId===void 0?"ready":it.isFetching&&it.data===void 0?"loading":it.isError&&it.data===void 0?"error":it.data?"ready":"loading"}):void 0},[me,it.data,it.isError,it.isFetching,gs]),ks=Z===2?wt?"error":St.isPending?"loading":St.isError&&ca===void 0?"error":"ready":it.isPending&&!jt?"loading":it.isError&&!jt?"error":"ready",vn=(s?.recentRuns??[]).some(q=>q.kind===gn["answer-visibility"]&&(q.status===_s.running||q.status===_s.queued)),Ut=s.queryCounts.total>0,$s=c.useMemo(()=>(s?.project.locations??[]).map(q=>q.label),[s?.project.locations]),jn=c.useMemo(()=>new Set(Mt.map(q=>q.location??"")),[Mt]),Fa=jn.has(""),da=c.useMemo(()=>[...new Set(Mt.map(q=>q.query))].sort((q,ge)=>q.localeCompare(ge)),[Mt]),Nn=da.length>0||s.queryCounts.total>0||(is.data?.length??0)>0||me!==null,Ga=g&&!Nn&&(Ae.data===void 0&&Ae.isPending||is.isLoading||Cs&&Rt.evidenceLoading),Ms=g&&(b.isError&&!b.isFetching||Ct&&is.isError&&!is.isFetching),rn=g&&!Ms&&(Ga||H===void 0||b.isFetching),ln=!rn&&!Ms&&Nn&&H===!0,_n=g&&!rn&&!ln,Bn=!ce()&&D==="overview"&&_n&&!Nn,ua=Me({...xp({client:Y,path:{name:j},query:{limit:JN}}),enabled:Bn&&!!j,retry:!1}),Un=ua.isSuccess&&ua.data.scans.some(q=>q.status==="completed"||q.status==="partial"),Mr=Bn&&ua.isSuccess&&!Un,on=Bn&&Un,wn=Me({...Kc({client:Y,path:{name:j}}),enabled:!ce()&&!Ns()&&!!j,retry:!1}).data?.find(q=>q.kind===gn["answer-visibility"]),ma=wn?.enabled&&wn.nextRunAt?pp(wn.nextRunAt,wn.timezone):null,ha=ma?`Next AI sweep ${ma}`:null,_a=c.useMemo(()=>{const q=[...jn].filter(Boolean);return q.length>1?q:$s},[jn,$s]);c.useEffect(()=>{if(!Cs||qe===void 0||qe===""||!j){Ye(null),xe(!1);return}xe(!0),gp(j,qe,20).then(q=>{Ye(q),xe(!1)}).catch(()=>{Ye(null),xe(!1)})},[qe,j,Cs]);const cn=c.useMemo(()=>{if(!Ve)return null;const q=new Map;for(const ge of Ve){for(const[fe,vt]of Object.entries(ge.providerRuns??{}))q.set(`${ge.query}::${fe}`,vt.map(Es=>({runId:Es.runId,citationState:Es.citationState,createdAt:Es.createdAt,answerMentioned:Es.answerMentioned,visibilityState:Es.visibilityState,visibilityTransition:Es.visibilityTransition,mentionState:Es.mentionState,mentionTransition:Es.mentionTransition})));(!ge.providerRuns||Object.keys(ge.providerRuns).length===0)&&q.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 q},[Ve]),xa=c.useMemo(()=>{const q=qe!==void 0?Mt.filter(ge=>qe===""?!ge.location:ge.location===qe):Mt;return cn?q.map(ge=>{const fe=cn.get(`${ge.query}::${ge.provider}`)??cn.get(`${ge.query}::`);return fe?{...ge,runHistory:fe}:ge}):q},[Mt,qe,cn]);async function Ba(){if(!(x!==j||!g||ce()||Ns()||He.isPending||vn||!ln))try{await He.mutateAsync({projectName:j,projectLabel:$t,sourceAction:"project-run"}),y(null),n()}catch{}}function qr(){m({to:"/setup",search:{experience:"legacy",setupProject:j}})}function Ua(){m({to:"/projects/$projectName/technical-aeo",params:{projectName:j}})}async function Er(){M(!0);try{await Ip(j),Oe({title:"Project deleted",detail:`${$t} was removed.`,tone:"positive",dedupeKey:`project:delete:${j}`,dedupeMode:"drop"}),m({to:"/"}),n()}catch(q){console.error("Failed to delete project:",q)}finally{M(!1)}}async function Va(){const q=oe.split(`
7
- `).map(ge=>ge.trim()).filter(Boolean);if(q.length!==0){se(!0);try{await Cp(j,q),n(),G("")}finally{se(!1)}}}async function N(q){Ce(q);try{await Sp(j,[q]),n()}catch(ge){Oe({title:"Could not remove query",detail:ge instanceof Error?ge.message:`Failed to remove "${q}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{Ce(null)}}async function z(q){const ge=q.trim();if(!ge)return!1;try{return await yp(j,[ge]),n(),!0}catch(fe){return Oe({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 de(q){const ge=s.competitors.find(fe=>fe.domain===q);if(!ge)return Oe({title:"Could not remove competitor",detail:`Could not find ${q} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await bp(j,ge.id),n(),!0}catch(fe){return Oe({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 we(q){const ge=q.trim();if(!ge||!bt||Z!==2||!g||ce()||ls.isPending)return!1;try{const fe=await ls.mutateAsync({client:Y,path:{name:j},headers:{"Idempotency-Key":BN()},body:{expectedActiveRevision:Ge,groupKey:bt,domain:ge}});return Promise.allSettled([b.refetch()]),Oe({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:${bt}:${ge}`,dedupeMode:"replace"}),!0}catch(fe){return Oe({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 lt(q,ge){const fe=await kp(q,ge);return await u.invalidateQueries({queryKey:Ap({client:Y})}),u.setQueryData(Rp({client:Y,path:{name:q}}),fe),UN(u,fe),ge.providers!==void 0&&await u.invalidateQueries({queryKey:Pp({client:Y,path:{name:q}}),exact:!0}),fe}const Ue=`/projects/${encodeURIComponent(s.project.name)}`,pt=[{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`}],Vt=[{key:"report",label:"Report",href:`${Ue}/report`},{key:"history",label:"Change History",href:`${Ue}/history`}],ht=pt.filter(q=>_r(q.key,te)),$e=Vt.filter(q=>_r(q.key,te)),qs=_r("settings",te)?{key:"settings",label:"Settings",href:`${Ue}/settings`}:null;function Sn(q){const ge=st?q:e.jsx(Uy,{projectName:j,selection:k,showUnmeasuredFallback:!me&&!Ut&&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:ne,onManageQueries:ce()?void 0:()=>{m({to:"/projects/$projectName/queries",params:{projectName:j},search:vt=>({...vt,queryWorkspace:"tracked",trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:ce()?void 0:({id:vt,label:Es})=>e.jsx(Bs,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:j,targetKey:vt},search:vp,"aria-label":`Property details for ${Es}`,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:q});if(ce())return ge;let fe=jp(k,st?"simple":"advanced",typeof I.sentimentEvaluationDefinitionId=="string"?I.sentimentEvaluationDefinitionId:void 0);return st&&(fe.location=qe===""?"none":qe,fe=Np(fe,xa,F)),e.jsx(wp,{hasSourceEvidence:!st||!!(fe.runId||fe.runIds?.length),evidenceReady:!st||!(Rt.isLoading||Rt.evidenceLoading||Rt.evidenceError),waitForResolvedRun:!st,projectName:j,runOptions:s.visibilitySweeps.slice(0,XN).map(vt=>({id:vt.id,label:ss(vt.finishedAt??vt.createdAt)})),selection:fe,children:ge})}function Vn(){switch(ds.kind){case"report-picker":{if(ps.error)return Cc(kc(ps.error))?e.jsx("p",{className:"text-[13px] text-secondary",children:Wa.savedScopeUnavailable}):null;const q=ps.data;if(!q)return e.jsx("div",{className:"skeleton-text h-11 w-56",role:"status","aria-label":"Loading measurement scope"});if(q.selection.availability.state!=="available"||q.scopeOptions.length<=1)return null;const ge=ki(q.scopeOptions,k)??q.selection.scope;return e.jsx(Ol,{labelVisibility:"sr-only",options:q.scopeOptions,selected:ge,marketKey:k.marketKey,onSelect:(fe,vt)=>ne({measurementScope:fe.kind,measurementScopeKey:fe.kind==="project"?void 0:fe.id,measurementMarketKey:vt})})}case"tracking-picker":{const q=ke.data?.scopeOptions??[],ge=ki(q,k);return ge?e.jsx(Ol,{labelVisibility:"sr-only",options:q,selected:ge,onSelect:fe=>ne({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:Wa.savedScopeUnavailable});case"project-wide":return e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[13px] text-secondary",children:Wa.projectWide}),e.jsx(_e,{text:Wa.projectWideHelp})]});case"none":return null}}const As=D==="overview"&&!st&&(k.from||k.to)?`${k.from?.slice(0,10)??"First measurement"} to ${k.to?.slice(0,10)??"Latest measurement"}`:null,Ha=Vn(),Cl=he?e.jsx(Mg,{window:Ie,landscape:ms.data,pinnedFallback:Bt,canWrite:g,isEmbed:ce(),onWindowChange:Be,onPin:bt&&g&&!ce()?we:!K&&g&&!ce()?z:void 0,onUnpin:bt||K||!g||ce()?void 0:de,onAddCompetitor:bt&&g&&!ce()?we:!K&&g&&!ce()?z:void 0,error:E,onRetry:Nt?()=>{ms.refetch()}:void 0,isLoading:Nt&&ms.isPending&&ms.data===void 0,scopeLabel:bt?`${ae?.label??bt} group`:K?"All markets":"Project-wide"}):null;return e.jsxs("div",{className:"page-container",children:[ce()?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:Ns()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:As!==null?e.jsx("p",{className:"text-sm text-muted",children:As}):null})]}):e.jsxs("div",{className:"project-context-row",children:[D!=="report"?e.jsx("h1",{className:"project-context-title md:sr-only",children:s.project.displayName||s.project.name}):null,Ha!==null?e.jsx("div",{className:"project-context-scope",children:Ha}):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:Ns()?e.jsx(fp,{projectName:j,running:vn,portfolio:!st}):e.jsxs(e.Fragment,{children:[ha?e.jsx("p",{className:"text-sm text-secondary",children:ha}):null,Mr?e.jsx(Ze,{type:"button",onClick:Ua,children:"Map site"}):on?e.jsx(Ze,{type:"button",onClick:Ua,children:"View Page Health"}):null,e.jsx(Ze,{type:"button",variant:"outline",disabled:He.isPending||vn||rn,onClick:Ms?()=>{Promise.all([b.refetch(),...Ct?[is.refetch()]:[]])}:_n?qr:q=>{p.current=q.currentTarget,y(j)},children:He.isPending?"Starting…":vn?"AI sweep running…":rn?"Checking AI readiness…":Ms?"Retry AI readiness":_n?"Set up AI Visibility":"Run AI sweep"})]})})]}),!ce()&&!Ns()&&e.jsx(_N,{open:x===j,projectLabel:$t,onOpenChange:q=>y(q?j:null),onConfirm:tt(Ba),onClosed:()=>p.current?.focus(),disabled:He.isPending||vn||!ln}),e.jsx(WN,{items:ht,overflowItems:$e,settingsItem:qs,activeTab:D}),D==="portfolio"&&!ce()?e.jsx(mj,{projectName:j,canEdit:g,queries:R.data??[],isQueryLoading:Ls,isQueryError:nn,onRetryQueries:()=>{R.refetch()},publishedPlan:me,onCreateQueries:async q=>(await W.mutateAsync({projectName:j,queries:[...q]}),(await R.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{m({to:"/projects/$projectName",params:{projectName:j},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([b.refetch(),Ae.refetch()]).finally(()=>{m({to:"/projects/$projectName",params:{projectName:j}})})}},j):D==="overview"?zt||st&&!w&&(!o||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"})]}):st&&i?e.jsxs("div",{role:"alert",className:"page-section-divider",children:[e.jsx("p",{children:"Could not load AI visibility."}),e.jsx(L,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[Ts?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(L,{type:"button",size:"sm",variant:"outline",onClick:()=>{Ae.refetch()},children:"Retry setup check"})]}):null,Sn(e.jsx(Lj,{mode:Ss,canEdit:g&&!ce()&&!Is&&!Ts,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(lb,{projectName:s.project.name,competitorDomains:$,analyticsRevision:a,queryTexts:Wt,classifyQuery:us,sweepTimes:an})}),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"}),Ut?e.jsx("p",{className:"av-card-meta",children:"Latest sweep"}):null]}),Ut?e.jsxs("div",{className:"competitive-summary",children:[e.jsx(wg,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:$},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(cc,{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(cc,{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(jy,{projectName:s.project.name,classify:us,hasCompetitors:$.length>0,providerScores:s.providerScores})}),e.jsxs(QN,{id:"evidence-section",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[!ce()&&e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-end gap-2",children:[e.jsx(Sc,{}),e.jsx(Ze,{type:"button",variant:"outline",size:"sm",onClick:()=>ee(!je),children:je?"Done":"Manage queries"})]}),!ce()&&je&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[da.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:da.map(q=>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:q,children:q}),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 ${q}`,title:`Stop tracking "${q}"`,disabled:Se!==null,onClick:()=>{N(q)},children:Se===q?"Removing…":"Remove"})]},q))}):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:oe,onChange:q=>G(q.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[oe.split(`
8
- `).filter(q=>q.trim()).length," to add"]}),e.jsx(Ze,{type:"button",size:"sm",disabled:!oe.trim()||ue,onClick:tt(Va),children:ue?"Adding...":"Add queries"})]})]}),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:()=>{pe(void 0)},children:"All locations"}),s.project.locations.map(q=>e.jsx("button",{className:`filter-chip ${qe===q.label?"filter-chip-active":""}`,type:"button","aria-pressed":qe===q.label,onClick:()=>{pe(q.label),ye(!1)},children:q.label},q.label)),Fa&&e.jsx("button",{className:`filter-chip ${qe===""?"filter-chip-active":""}`,type:"button","aria-pressed":qe==="",onClick:()=>{pe(""),ye(!1)},children:"No location"}),_a.length>1&&qe===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${T?"filter-chip-active":""}`,type:"button","aria-pressed":T,onClick:()=>ye(q=>!q),title:"Side-by-side location comparison",children:"Compare"})]}),Rt.evidenceLoading?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading query evidence…"}):Rt.evidenceError?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load query evidence."}),e.jsx(L,{type:"button",variant:"outline",onClick:()=>{Rt.refetch()},children:"Retry"})]}):e.jsx(xf,{evidence:xa,compareLocations:T,providerSelection:F,onProviderSelectionChange:Ke,addedQueries:s.movementComparison.addedQueries})]}),!ce()&&e.jsx("div",{className:"page-section-divider",children:e.jsx(wy,{runs:s.recentRuns,collapsed:!0})})]}),report:ca,reportState:ks,onOpenSetup:ce()?void 0:()=>{m({to:"/projects/$projectName/portfolio",params:{projectName:j}})},onRetryReport:()=>{Z===2?Promise.all([St.refetch(),it.refetch()]):it.refetch()},onViewChange:q=>{at({scope:q.scope,...q.groupKey?{groupKey:q.groupKey}:{},queryClass:q.queryClass,...q.search?.trim()?{search:q.search.trim()}:{}})},onLoadMore:q=>{q===gs?.properties.nextCursor&&St.fetchNextPage()},onPropertyExpand:()=>{yt&&it.isError&&it.refetch(),At(!0)},onRetryEvidence:()=>{it.refetch()},isViewLoading:St.isPlaceholderData,isLoadingMore:St.isFetchingNextPage,isLoadMoreError:St.isFetchNextPageError,viewSearch:ut.search??""},`${j}:${Ge}`)),!st&&k.measurementScope==="project"?e.jsxs("details",{className:"visibility-disclosure",onToggle:q=>{q.currentTarget.open&&d()},children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Project signals"})}),!o||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(L,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsx(zN,{insights:s.insights,suggestedQueries:s.suggestedQueries,onManageQueries:ce()?void 0:()=>{m({to:"/projects/$projectName/queries",params:{projectName:j},search:q=>({...q,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]},j):null,Cl!==null?e.jsxs("details",{className:`visibility-disclosure${st?" page-section-divider":""}`,open:gt,onToggle:q=>Qe(q.currentTarget.open?j: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:Cl})]}):null]}):D==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(qN,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(q,ge)=>{await lt(q,ge)},onRefresh:()=>{n()}}),e.jsx(DN,{project:s.project,onSave:async q=>{await lt(s.project.name,q)}}),g&&!ce()?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."}),We==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):We==="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(L,{type:"button",size:"sm",variant:"outline",onClick:()=>{b.refetch()},children:"Retry"})]}):e.jsx(L,{type:"button",variant:"outline",onClick:()=>{m({to:"/projects/$projectName/portfolio",params:{projectName:j}})},children:Hd(Ss.setupAction)})]}):null,e.jsx(FN,{projectName:s.project.name}),e.jsx(GN,{projectName:s.project.name}),g&&!ce()?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."}),Q?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(L,{type:"button",variant:"destructive",disabled:_,onClick:tt(Er),children:_?"Deleting...":"Yes, delete project"}),e.jsx(L,{type:"button",variant:"outline",disabled:_,onClick:()=>B(!1),children:"Cancel"})]})]}):e.jsxs(Ze,{type:"button",variant:"outline",onClick:()=>B(!0),children:[e.jsx(Jc,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):D==="report"?e.jsx(Vj,{projectName:s.project.name,projectTitle:s.project.displayName||s.project.name}):D==="queries"||D==="discovery"?e.jsx(yb,{projectName:j,queryWorkspace:ie,onQueryWorkspaceChange:q=>ne({queryWorkspace:q,trackingQueryId:void 0}),researchMode:I.researchMode==="test"?"test":"find",onResearchModeChange:q=>ne({researchMode:q}),selection:k,onSelectionChange:ne,trackingQueryId:typeof I.trackingQueryId=="string"?I.trackingQueryId:void 0,onTrackingQueryIdChange:q=>ne({trackingQueryId:q})}):D==="technical-aeo"?e.jsx(_p,{projectName:s.project.name,projectId:s.project.id,initialRunId:I.siteHealthRunId,onReleaseInitialRun:le}):D==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(Rv,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(xv,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):D==="history"?e.jsx(Ub,{projectName:s.project.name}):D==="activity"?e.jsx(Pf,{projectName:s.project.name}):D==="backlinks"?e.jsx(xy,{projectName:s.project.name}):D==="local"?e.jsx(Vf,{projectName:s.project.name,projectId:s.project.id}):D==="search-console"?e.jsx(HN,{projectName:s.project.name}):null]})}export{mw as ProjectPage,WN as ProjectSubnav,_N as ProjectSweepConfirmation,UN as patchProjectDashboardCache};