@canonry/canonry 7.12.0 → 7.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. package/assets/assets/{AuditHistoryPanel-Bpkuj-iF.js → AuditHistoryPanel-BYxGn9mS.js} +1 -1
  2. package/assets/assets/{BacklinksPage-CbRIZhu5.js → BacklinksPage-BQxB_eFt.js} +1 -1
  3. package/assets/assets/{HistoryPage-Dfq1vK9k.js → HistoryPage-DgGUM2tr.js} +1 -1
  4. package/assets/assets/{MeasurementPropertyPage-DcH0zYNN.js → MeasurementPropertyPage-Cl91vUu5.js} +1 -1
  5. package/assets/assets/{ProjectPage-enF4twWt.js → ProjectPage-B_S900QN.js} +7 -7
  6. package/assets/assets/{RunsPage-aOeJ60pX.js → RunsPage-BtjVuurK.js} +1 -1
  7. package/assets/assets/{SettingsPage-nA0_ImoQ.js → SettingsPage-p0x0ZwGY.js} +1 -1
  8. package/assets/assets/{SiteHealthSection-CUOt7jeo.js → SiteHealthSection-DMHWsfM4.js} +3 -3
  9. package/assets/assets/{TrafficPage-C0fVYizx.js → TrafficPage-Bf0NkbIR.js} +1 -1
  10. package/assets/assets/{TrafficSourceDetailPage-LMhXbFlA.js → TrafficSourceDetailPage-BtwOdTAO.js} +1 -1
  11. package/assets/assets/{extract-error-message-5aHy0fsK.js → extract-error-message-Cyc59Xi7.js} +1 -1
  12. package/assets/assets/index-D4QB1Igv.css +1 -0
  13. package/assets/assets/{index-BJh8cX5E.js → index-DR_kNdE4.js} +2 -2
  14. package/assets/assets/{react-sigma_core.esm.min-ldX35rMq.js → react-sigma_core.esm.min-CFB4bYg_.js} +1 -1
  15. package/assets/assets/{v2-overview-adapter-CaO9vY-l.js → v2-overview-adapter-CLF10Pij.js} +1 -1
  16. package/assets/index.html +2 -2
  17. package/dist/{chunk-DXI2FTSW.js → chunk-GBH7N3VZ.js} +1 -1
  18. package/dist/cli.js +1 -1
  19. package/dist/index.js +1 -1
  20. package/package.json +11 -11
  21. package/assets/assets/index-BNeiohKS.css +0 -1
@@ -1,8 +1,8 @@
1
- import{j as e,r as o,t as rd,u as $e,L as Ms,h as hs,o as Et,B as wi,C as Ml,D as id,k as od,l as ld}from"./vendor-tanstack-ZXXkndVj.js";import{T as Ne,t as cd,a as dd,s as Si,M as ga,I as Oe,f as et,R as Yn,m as ud,B as P,c as md,b as hd,d as pd,S as Ll,e as $l,u as Ci,g as xd,n as Bn,C as gd,h as ql,i as El,j as ki,k as fd,l as yd,o as bd,p as vn,q as Dl,r as Ol,v as je,w as sr,x as Y,y as oe,z as Ls,A as $t,D as Ze,E as vd,F as jd,G as Nd,H as Fl,J as wd,K as Sd,L as nn,N as jn,O as Cd,P as kd,Q as Mn,U as Jt,V as Ad,W as Rd,X as to,Y as Gl,Z as Yt,_ as Ai,$ as Pd,a0 as Id,a1 as Td,a2 as Md,a3 as so,a4 as De,a5 as Ld,a6 as $d,a7 as Nr,a8 as qd,a9 as Ed,aa as Dd,ab as Od,ac as Fd,ad as Gd,ae as Kd,af as _d,ag as Ud,ah as Bd,ai as Vd,aj as zd,ak as Qd,al as Hd,am as Wd,an as Kl,ao as Us,ap as Yd,aq as _l,ar as ir,as as Jd,at as Ye,au as Xd,av as Zd,aw as eu,ax as or,ay as tu,az as su,aA as nu,aB as Vn,aC as au,aD as ru,aE as iu,aF as Ul,aG as ti,aH as ou,aI as Ri,aJ as lu,aK as zn,aL as ds,aM as xr,aN as Ts,aO as Bl,aP as nr,aQ as si,aR as cu,aS as no,aT as Vl,aU as fa,aV as du,aW as zl,aX as Ql,aY as uu,aZ as Hl,a_ as hn,a$ as Pi,b0 as wr,b1 as mu,b2 as hu,b3 as pu,b4 as xu,b5 as gu,b6 as ha,b7 as ao,b8 as Ea,b9 as Sr,ba as fu,bb as yu,bc as ro,bd as Cr,be as Nn,bf as Wl,bg as Ii,bh as Yl,bi as bu,bj as vu,bk as io,bl as ju,bm as Nu,bn as wu,bo as Su,bp as Cu,bq as ku,br as Au,bs as Ru,bt as Pu,bu as Iu,bv as Tu,bw as Mu,bx as Lu,by as $u,bz as qu,bA as Eu,bB as Du,bC as Ou,bD as Fu,bE as Gu,bF as Ku,bG as _u,bH as Uu,bI as Bu,bJ as Vu,bK as zu,bL as Qu,bM as Hu,bN as Cs,bO as Wu,bP as jt,bQ as Yu,bR as Ju,bS as Xu,bT as Zu,bU as em,bV as tm,bW as sm,bX as nm,bY as am,bZ as rm,b_ as im,b$ as om,c0 as lm,c1 as cm,c2 as dm,c3 as um,c4 as mm,c5 as hm,c6 as pm,c7 as xm,c8 as gm,c9 as fm,ca as oo,cb as ym,cc as bm,cd as vm,ce as jm,cf as Nm,cg as Jl,ch as wm,ci as Sm,cj as Cm,ck as Xl,cl as kr,cm as km,cn as Am,co as lo,cp as Rm,cq as Pm,cr as Im,cs as Tm,ct as Mm,cu as Lm,cv as $m,cw as Zl,cx as qm,cy as ec,cz as tc,cA as sc,cB as nc,cC as Em,cD as Dm,cE as Om,cF as Fm,cG as Gm,cH as Km,cI as _m,cJ as co,cK as Um,cL as Bm,cM as Vm,cN as zm,cO as Qm,cP as Hm,cQ as Wm,cR as Ym,cS as uo,cT as Jm,cU as Xm,cV as Zm,cW as eh,cX as th,cY as sh,cZ as nh,c_ as ah,c$ as rh,d0 as ih,d1 as oh,d2 as lh,d3 as Ar,d4 as ch,d5 as dh,d6 as uh,d7 as mh,d8 as hh,d9 as ph,da as xh,db as gh,dc as fh,dd as yh,de as bh,df as vh,dg as jh,dh as ac,di as Nh,dj as wh,dk as Sh,dl as Ch,dm as kh,dn as Ah,dp as Da,dq as Rh,dr as Ph,ds as Ih,dt as mo,du as Th}from"./index-BJh8cX5E.js";import{u as wn,D as Js,a as Ks,b as rc,M as ar,c as Os,F as Mh,P as ic,s as Lh,p as $h,S as qh}from"./SiteHealthSection-CUOt7jeo.js";import{A as Ti,a as Eh,b as Dh,c as Oh,V as ho}from"./v2-overview-adapter-CaO9vY-l.js";import{o as Bt,C as ya,f as Sn,a as us,b as Ut,c as Pt,d as ns,e as lt,g as ms,h as Jn,M as oc,i as Fh,j as Sa,p as Gh,k as Kh,l as po,m as _h}from"./ChartPrimitives-CYlrwLJs.js";import{g as lc,y as ba,U as Uh,z as Bh,L as Vh,D as zh,l as Qh,j as lr,I as Hh,J as Wh,C as Qn,X as Yh,e as Jh,K as Xh,P as Zh,N as ep,O as cc}from"./vendor-lucide-N6vOpZmh.js";import{u as tp,a as sp,b as np,t as ap,e as rp,c as St}from"./extract-error-message-5aHy0fsK.js";import{R as Xs,C as Zs,a as va,X as en,Y as tn,T as sn,b as ni,L as cr,A as Ws,d as Gs,e as ip}from"./vendor-recharts-D-cUuLZo.js";import{A as op}from"./AuditHistoryPanel-Bpkuj-iF.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B4giJcws.js";import"./vendor-yaml-GWJz5H2G.js";const lp=1e6;function cp(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/lp);if(n.showTinyAsLessThan&&t>0&&r===a.format(0)){const l=10**-(a.resolvedOptions().maximumFractionDigits??0);return`<${a.format(l)}`}return r}const Oa={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 dc(t,s){return t!=="viewer"||s!==null}function uc(t,s){return t==="research"&&!s?"tracked":t}function mc(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 ai(t,s){return t.find(n=>n.kind===s.measurementScope&&(n.kind==="project"||n.id===s.measurementScopeKey))}function dp(t){return t.measurementScope!=="project"||t.marketKey!==void 0}function up(t){if(t.embedded)return{kind:"none"};const{tab:s}=t;switch(s){case"overview":return t.surface==="advanced-overview"?{kind:"report-picker"}:{kind:"none"};case"queries":case"discovery":{const{tracking:n}=t;return t.queryWorkspace!=="tracked"||n.state!=="ready"||n.mode!=="advanced"?{kind:"none"}:n.scopeUnavailable?{kind:"scope-unavailable"}:{kind:"tracking-picker"}}case"search-console":case"activity":case"technical-aeo":case"conversions":case"local":case"backlinks":case"history":return t.scoped&&t.surface==="advanced-overview"?{kind:"project-wide"}:{kind:"none"};case"settings":case"portfolio":return{kind:"none"};default:return s}}function ri({state:t,label:s,className:n}){return e.jsx(Ne,{tone:dd(t),className:n,children:s??cd(t)})}const pn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],xo={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},mp={"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."},hp="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function pp(t,s){return s.unavailable?{headline:"No data",numeric:!1,detail:"could not load, refresh to retry",showRows:!1}:s.noRun?{headline:"No data",numeric:!1,detail:"no sweep has run yet",showRows:!1}:t.snapshotsTotal===0?s.otherClassHasData?{headline:"No non-brand queries",numeric:!1,detail:"every tracked query names your brand",showRows:!1}:{headline:"No queries",numeric:!1,detail:"none tracked",showRows:!1}:t.snapshotsWithAnswerText===0?{headline:"No answers",numeric:!1,detail:"no answer text in this run",showRows:!1}:s.hasCompetitors?t.combinedMentionSnapshots===0||t.score===null?{headline:"No mentions",numeric:!1,detail:`no brand named in ${t.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:et(t.score,Yn.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 xp({breakdown:t,projectLabel:s}){if(t.ranking.length===0)return null;const n=t.ranking.map(a=>({label:a.kind==="project"?`${s} (you)`:a.domain??"",mentions:a.mentionSnapshots,share:a.share,isYou:a.kind==="project"}));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Oe,{text:hp})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:n.map(a=>e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${a.isYou?"text-heading font-medium":"text-secondary"}`,children:a.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${a.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${a.share>0?Math.max(a.share*100,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:a.mentions}),e.jsx("td",{className:"mention-share-share",children:et(a.share)})]},a.label))})]})}function gp({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=o.useState("non-brand"),l=o.useId(),i=t.scope==="pooled",c=!i&&t.branded.snapshotsTotal>0,d=c?a:"non-brand",m=i?"pooled":d,u=d==="branded"?t.branded:t.breakdown,p=d==="branded"?t.breakdown:t.branded,x=pp(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:p.snapshotsTotal>0}),h=Si(x.headline),y=m==="non-brand"?ga[t.tone]:"text-secondary";function f(b){const N=pn.findIndex(L=>L.value===d);let k=null;b.key==="ArrowRight"||b.key==="ArrowDown"?k=(N+1)%pn.length:b.key==="ArrowLeft"||b.key==="ArrowUp"?k=(N-1+pn.length)%pn.length:b.key==="Home"?k=0:b.key==="End"&&(k=pn.length-1),k!==null&&(b.preventDefault(),r(pn[k].value),b.currentTarget.querySelectorAll('[role="radio"]')[k]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:l,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Oe,{text:mp[m]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":l,className:"segmented flex-wrap",onKeyDown:f,children:pn.map(b=>{const N=b.value===d;return e.jsx("button",{type:"button",role:"radio","aria-checked":N,tabIndex:N?0:-1,onClick:()=>r(b.value),className:`segmented-option min-h-11 ${N?"segmented-option-active":""}`,children:b.label},b.value)})}):e.jsx("span",{className:"mention-share-class",children:xo[m]})]}),x.numeric?e.jsxs("p",{className:`mention-share-value ${y}`,children:[h.figure,h.sign?e.jsx("span",{className:"text-faint",children:h.sign}):null]}):e.jsx("p",{className:"mention-share-value-text",children:x.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:xo[m]}),` · ${x.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),x.showRows&&e.jsx(xp,{breakdown:u,projectLabel:s})]})}function Ca({items:t,label:s="Details"}){return t.length===0?null:e.jsxs("details",{className:"av-details",children:[e.jsx("summary",{children:s}),e.jsx("ul",{className:"av-details-list",children:t.map((n,a)=>e.jsx("li",{children:n},a))})]})}function pa({options:t,value:s,onChange:n,label:a,className:r=""}){const l=o.useId();function i(c){const d=t.findIndex(u=>u.value===s);let m=null;c.key==="ArrowRight"||c.key==="ArrowDown"?m=(d+1)%t.length:c.key==="ArrowLeft"||c.key==="ArrowUp"?m=(d-1+t.length)%t.length:c.key==="Home"?m=0:c.key==="End"&&(m=t.length-1),m!==null&&(c.preventDefault(),n(t[m].value),c.currentTarget.querySelectorAll('[role="radio"]')[m].focus())}return e.jsx("div",{role:"radiogroup","aria-label":a,className:`segmented ${r}`.trim(),onKeyDown:i,children:t.map(c=>{const d=c.value===s,m=c.description?`${l}-${c.value}`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button",role:"radio","aria-checked":d,"aria-describedby":m,tabIndex:d?0:-1,onClick:()=>n(c.value),className:`segmented-option pointer-coarse:min-h-11 ${d?"segmented-option-active":""}`,children:c.label}),c.description?e.jsx("span",{id:m,className:"sr-only",children:c.description}):null]},c.value)})})}const fp=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],yp={"7d":"last 7 days","30d":"last 30 days","90d":"last 90 days",all:"all sweeps"},bp={"non-brand":"Non-brand",branded:"Branded",all:"All queries"},vp={"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."},jp={"select-query-class":"no query type selected","answer-selection":"answers selected by the brands they named","no-competitors":"no competitors configured","insufficient-observed":"needs 3 observed competitors, each named in 3 or more answers","no-answers":"no answer text","no-mentions":"no brands named",unavailable:"competitor data unavailable"},go="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.",ii=100;function Np(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function hc(t){return t==="unavailable"?"Unavailable":"Not measured"}function oi(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 ks(t,s,n){return t===1?s:n}function pc(t){const s=t.label.trim(),n=md(t.domain);return s&&s.toLowerCase()!==t.domain.toLowerCase()&&s.toLowerCase()!==n.toLowerCase()?s:null}function xc({row:t,aliases:s=[],autoAliases:n=[]}){const a=pc(t),r=[...s.map(i=>({alias:i,auto:!1})),...n.map(i=>({alias:i,auto:!0}))],l=r.length>0?e.jsxs("span",{className:"av-of block",children:["Also named"," ",r.map(({alias:i,auto:c},d)=>e.jsxs("span",{children:[d>0?", ":"",i,c?e.jsx("span",{className:"av-alias-auto",title:"Detected automatically from this project's stored answers",children:" (auto)"}):null]},`${c?"auto":"curated"}:${i}`))]}):null;return a?e.jsxs(e.Fragment,{children:[a," ",e.jsx("span",{className:"av-of",children:t.domain}),l]}):e.jsxs(e.Fragment,{children:[t.domain,l]})}function wp(t){const s=pc(t);return s?`${s} (${t.domain})`:t.domain}function fo(t,s){return s&&t>=ii?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:t})]}):e.jsx("strong",{children:t})}function li({action:t,domain:s,mutation:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(null);async function c(){if(!a){r(!0),i(null);try{await n(s)===!1&&i(`Could not ${t} competitor. Try again.`)}catch{i(`Could not ${t} competitor. Try again.`)}finally{r(!1)}}}return e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",size:"sm",variant:"outline",disabled:a,onClick:()=>{c()},children:[t==="pin"?"Pin":"Unpin"," ",e.jsx("span",{className:"sr-only",children:s})]}),l?e.jsx("span",{role:"alert",className:"sr-only",children:l}):null]})}function Sp({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 On({count:t,of:s,state:n,toneClass:a}){return n!=="measured"?e.jsx("span",{className:"text-[13px] text-secondary",children:hc(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 yo({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":hc(s)});const{figure:a,sign:r}=Si(et(t,Yn.percent));return e.jsxs("span",{className:`av-n-sm ${n}`,children:[a,r?e.jsx("span",{className:"text-faint",children:r}):null]})}function Cp({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(xc,{row:l})}),e.jsx("td",{className:"text-[13px] text-secondary",children:oi(l.surfaceClass)}),e.jsx("td",{children:e.jsx(On,{count:l.mentionCount,of:n,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(On,{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(Sp,{urls:l.sampleUrls}):null,r?e.jsx(li,{action:"pin",domain:l.domain,mutation:r}):null]})})]},l.domain))})]})})}function kp({onAddCompetitor:t}){const s=o.useId(),[n,a]=o.useState(""),[r,l]=o.useState(!1),[i,c]=o.useState(null);async function d(){const m=n.trim();if(!(!m||r)){l(!0),c(null);try{if(await t(m)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("Could not add competitor. Try again.")}finally{l(!1)}}}return e.jsxs("details",{className:"inline-disclosure",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:m=>{m.preventDefault(),d()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:m=>a(m.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(P,{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 Ap({window:t,landscape:s,pinnedFallback:n=[],competitorAliases:a={},competitorAutoAliases:r={},canWrite:l,isEmbed:i,onWindowChange:c,onPin:d,onUnpin:m,onAddCompetitor:u,error:p,onRetry:x,isLoading:h=!1,scopeLabel:y}){const f=o.useId(),b=l&&!i,N=s?.pinned??n,k=s?.observed??[],L=s?.otherSources??[],S=s?.evidence,g=Np(s),v=s?.basis==="observed",C=v?k.filter(E=>E.shareOfVoice!==null):N,I=v?k.filter(E=>E.shareOfVoice===null):k,A=s?.filters.queryClass,w=s?.marketState?.draft?.pendingCompetitorDomains.length??0,V=s?.truncated===!0,G=S?.answeredResults??0,Q=S?S.answeredResults+S.missingAnswerTextResults:0,B=A==="non-brand"&&s?.project.shareOfVoice!=null?ga[ud(s.project.shareOfVoice)]:"text-primary",z=E=>b?E.pinned?m?e.jsx(li,{action:"unpin",domain:E.domain,mutation:m}):null:d?e.jsx(li,{action:"pin",domain:E.domain,mutation:d}):null:null,ne=C.some(E=>z(E)!==null),F=[y,A?bp[A]:null,yp[t],s?.basis?v?"observed competitors only":"tracked competitors only":null].filter(Boolean).join(" · "),_=[];if(s&&!v&&C.length===0&&_.push({key:"no-pins",text:"No pinned competitors."}),s?.reason&&_.push({key:"reason",text:`Mention share: ${jp[s.reason]}`}),s&&I.length>0){const E=I.length;_.push({key:"others",text:V&&E>=ii?`${ii} or more other competitors seen`:`${E} other ${ks(E,"competitor","competitors")} seen`})}w>0&&_.push({key:"pending",text:`${s?.scope.kind==="all-markets"?"Pending publication across markets":"Pending publication"}: ${w} ${ks(w,"competitor","competitors")}`});const Z=[S&&S.missingAnswerTextResults>0?"Answer data incomplete":null,S&&S.incompleteSourceResults>0?"Citation data incomplete":null].filter(Boolean);Z.length>0&&_.push({key:"incomplete",text:Z.join(" · "),className:ga.caution});const $=[];if(s&&S){$.push(s.runCount!==void 0?e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:s.runCount})," ",ks(s.runCount,"sweep","sweeps"),", ",e.jsx("strong",{children:S.answeredResults})," ",ks(S.answeredResults,"answer","answers")]}):e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:S.answeredResults})," ",ks(S.answeredResults,"answer","answers")]})),!s.reason&&g==="measured"&&s.project.shareOfVoice!==null&&$.push(e.jsxs(e.Fragment,{children:["Mention share: you ",e.jsx("strong",{children:s.project.mentionCount}),C.map(te=>e.jsxs(rd.Fragment,{children:[", ",te.domain," ",e.jsx("strong",{children:te.mentionCount})]},te.domain))," ","of ",e.jsx("strong",{children:S.mentionCredits})," ",v?"brand mentions":"tracked-brand mentions"]})),$.push(e.jsxs(e.Fragment,{children:["Answers with source links: ",e.jsx("strong",{children:S.sourceResults})]})),I.length===0&&$.push("Other competitors seen: none"),S.missingAnswerTextResults>0&&$.push(e.jsxs(e.Fragment,{children:["No answer text: ",e.jsx("strong",{children:S.missingAnswerTextResults})," ",ks(S.missingAnswerTextResults,"answer","answers"),", left out of mention share"]})),S.incompleteSourceResults>0&&$.push(e.jsxs(e.Fragment,{children:["Incomplete source lists: ",e.jsx("strong",{children:S.incompleteSourceResults})," ",ks(S.incompleteSourceResults,"answer","answers"),", not counted as misses"]}));const E=S.excludedProbeResults+S.excludedNonCompletedResults;E>0&&$.push(e.jsxs(e.Fragment,{children:["Left out: ",e.jsx("strong",{children:E})," ",ks(E,"answer","answers")," from spot checks or unfinished sweeps"]}))}const ee=[...s?[{name:"You",row:s.project}]:[],...C.map(E=>({name:E.domain,row:E}))].filter(E=>E.row.sampleUrls.length>0);g==="measured"&&ee.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:ee.map(({name:E,row:te})=>e.jsxs("div",{children:[e.jsx("p",{children:E}),e.jsx("ul",{className:"space-y-1 font-mono text-[11px] text-muted",children:te.sampleUrls.map(re=>e.jsx("li",{className:"break-all",children:re},re))})]},te.domain))})]})),s&&I.length>0&&$.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other competitors seen: ",fo(I.length,V)]}),e.jsx("div",{className:"av-subdetails-body",children:e.jsx(Cp,{rows:I,state:g,named:G,cited:Q,onPin:b?d:void 0})})]}));const T=s?.observedNames??[];if(T.length>0){const E=s?.observedNamesTotal??T.length;$.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Company names in answers: ",E>T.length?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:T.length})," of ",e.jsx("strong",{children:E})]}):e.jsx("strong",{children:T.length})]}),e.jsx("ul",{className:"av-subdetails-body",children:T.map(te=>e.jsxs("li",{children:[te.name," · ",te.answerCount," ",ks(te.answerCount,"answer","answers")]},te.name))})]}))}return L.length>0&&$.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other sites cited: ",fo(L.length,V)]}),e.jsx("ul",{className:"av-subdetails-body",children:L.map(E=>e.jsxs("li",{children:[e.jsxs("span",{children:[wp(E)," · ",oi(E.surfaceClass)," · ",E.citationCount," ",ks(E.citationCount,"citation","citations")]}),E.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:E.sampleUrls.map(te=>e.jsx("li",{className:"break-all",children:te},te))}):null]},E.domain))})]})),e.jsxs("section",{"aria-labelledby":f,"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:f,className:"av-card-title",children:"Competitors over time"}),e.jsx(Oe,{text:A?`${vp[A]} ${go}`:go})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsx("p",{className:"av-card-meta",children:F}),e.jsx(pa,{label:"Competitors over time window",className:"flex-wrap",options:fp,value:t,onChange:c})]})]}),e.jsxs("div",{className:"av-card-body space-y-3",children:[p?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:p}),x?e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:x,children:"Retry competitors over time"}):null]}):null,h&&!s&&N.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||C.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"}),ne?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(yo,{percent:s.project.shareOfVoice,state:g,toneClass:B})}),e.jsx("td",{children:e.jsx(On,{count:s.project.mentionCount,of:G,state:g,toneClass:B})}),e.jsx("td",{children:e.jsx(On,{count:s.project.citationCount,of:Q,state:g,toneClass:B})}),ne?e.jsx("td",{className:"av-brand-actions"}):null]}):null,C.map(E=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(xc,{row:E,aliases:E.pinned?a[E.domain]:void 0,autoAliases:E.pinned?r[E.domain]:void 0})}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:oi(E.surfaceClass)}),e.jsx("td",{children:e.jsx(yo,{percent:E.shareOfVoice,state:g,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(On,{count:E.mentionCount,of:G,state:g,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(On,{count:E.citationCount,of:Q,state:g,toneClass:"text-primary"})}),ne?e.jsx("td",{className:"av-brand-actions",children:z(E)}):null]},E.domain))]})]}):null,_.length>0?e.jsx("div",{className:"space-y-1 text-[13px] text-secondary",children:_.map(E=>e.jsx("p",{className:E.className,children:E.text},E.key))}):null]}),e.jsx(Ca,{items:$}),b&&u?e.jsx("div",{className:"border-t border-subtle px-5 py-3",children:e.jsx(kp,{onAddCompetitor:u})}):null]})}function bo({history:t,maxDots:s=12,signal:n="citations"}){const a=t.slice(-s);if(a.length===0)return e.jsx("span",{className:"text-[13px] text-secondary",children:"No data"});const r=n==="mentions"?"Mention":"Citation",l=n==="mentions"?{cited:"mentioned","not-cited":"not mentioned",lost:"mention lost",emerging:"new mention",pending:"mention pending"}:{cited:"cited","not-cited":"not cited",lost:"citation lost",emerging:"new citation",pending:"citation pending"},i={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},c={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},d=a.length-1,m=new Date(a[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(a[d].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),p=`${a.length} ${a.length===1?"run":"runs"}`,x=a.map((h,y)=>{const f=new Date(h.createdAt).toLocaleDateString();return`${y===d?"Latest run, ":""}${f}: ${l[h.citationState]??h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"inline-flex w-max items-center gap-2 whitespace-nowrap",role:"img","aria-label":`${r} history across ${p}. ${x}`,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:p,"aria-hidden":"true",children:a.map((h,y)=>{const f=!!(h.model&&y>0&&a[y-1]?.model&&a[y-1].model!==h.model),b=y===d;return e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 ${c[h.citationState]??"rounded-sm"} ${i[h.citationState]??"bg-mono-700"} ${f?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[l[h.citationState]??h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,f?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[11px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{children:"latest"})]})]})}function ci(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 ka="__cited__",Aa="__mentioned__",_s="__mentionShare__";function $s(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Bt(n),end:Bt(a),sweepCount:s.sweepCount??1}}function ja(t,s=new Date){return pd(t,s)}function Ra(t,s=new Date){const n=$s(t);if(!n)return null;const a=ja(n.start,s),r=ja(n.end,s);return a===r?a:`${a} to ${r}`}function Mi(t,s=new Date){const n=$s(t),a=Ra(t,s);return!n||!a?"Sweep date unavailable":`${a} · ${n.sweepCount} ${n.sweepCount===1?"sweep":"sweeps"}`}function Rp(t){const s=$s(t);return s?hd(s.start):""}function Na(t){return t.trim().toLowerCase()}function Pp(t,s={}){return t.map(n=>{const a=n.trim().toLowerCase(),r=(s[n]??[]).map(l=>l.trim().toLowerCase()).filter(Boolean).sort();return a&&r.length>0?`${a}=${r.join("|")}`:a}).filter(Boolean).sort().join(`
2
- `)}const Ip={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",muse:"Muse",local:"Local"};function ot(t){const s=Na(t);return Ip[s]??t.charAt(0).toUpperCase()+t.slice(1)}function di(t){return Math.round(t*1e3)/10}function ui(t){return t.byProvider??{}}function Tp(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?ka:Aa,m=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(p=>({date:p.startDate,[d]:di(p[m])})),series:[d],hasData:a,singleBucket:r}}const l=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys(ui(d))))].sort();return{rows:t.buckets.map(d=>{const m={date:d.startDate},u=ui(d);for(const p of i){const x=u[p];m[p]=x?di(x[l]):null}return m}),series:i,hasData:a,singleBucket:r}}function gc(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Mp(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Lp(t){return t.servedModelAttribution??{}}function $p(t){return t.modelServiceMismatch??{}}function qp(t){return t.modelPointerChanges??{}}function xa(t){return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function wa(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 Ep(t){return xa([...t.models,...t.includesUnknown?["an unknown model"]:[]])}function Dp(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 Op(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:Dp(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Fp(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 Gp(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[_s]:r?.rate==null?null:di(r.rate)}}),n=s.map(a=>a[_s]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[_s],hasData:n.length>0,singleBucket:n.length===1}}function Kp(t,s,n){return s==="mentionShare"?Gp(t):Tp(t,s,n)}function _p(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 Up(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 Bp(t,s,n){const a=n==="mentioned"?"mentionRate":"citationRate";for(let r=t.buckets.length-1;r>=0;r--){const l=ui(t.buckets[r])[s];if(l)return l[a]}return null}function We(t){return Date.parse(t)}function fc(t,s){const n=$s(t);if(!n)return!1;const a=We(s);return a>=We(n.start)&&a<=We(n.end)}function yc(t){return t.basketChanges??[]}function bc(t,s){return s.filter(n=>fc(t,n.at)).sort((n,a)=>We(n.at)-We(a.at))}function dr(t,s){return Na(t)==="perplexity"&&s.status==="known"&&!s.model.includes("/")}function Vp(t){return Object.entries(t).filter(([s,n])=>!dr(s,n.configured)).sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>({provider:s,mismatch:n}))}function zp(t){return[...yc(t)].sort((s,n)=>We(n.at)-We(s.at)).map(s=>({at:Bt(s.at),added:s.added,removed:s.removed}))}function Qp(t,s){const n=[...t.events].sort((r,l)=>We(r.observedAt)-We(l.observedAt));let a=n[0]?.from??t.latestObservation.state;for(const r of n)We(r.observedAt)<=We(s)&&(a=r.to);return a}function vo(t,s,n,a){return{provider:t,at:Bt(s.observedAt),onOrBefore:s.fromPreWindowAnchor===!0,anchorAt:s.anchorObservedAt?Bt(s.anchorObservedAt):null,from:s.from,to:s.to,served:n,reroute:a}}function Hp(t,s){const n=[];for(const[a,r]of Object.entries(t)){const i=s[a]?.events??[],c=new Set(r.events.map(d=>d.observedAt));for(const d of r.events){const m=dr(a,d.to)?i.find(u=>u.observedAt===d.observedAt):void 0;n.push(vo(a,d,m?{from:m.from,to:m.to}:null,!1))}for(const d of i)c.has(d.observedAt)||dr(a,Qp(r,d.observedAt))&&n.push(vo(a,d,null,!0))}return n.sort((a,r)=>We(r.at)-We(a.at)||a.provider.localeCompare(r.provider))}function Wp({latest:t,queryChanges:s,modelRows:n,now:a=new Date}){const r=[...s.map(x=>x.at),...n.map(x=>x.at)];if(r.length===0)return null;const l=x=>t!==void 0&&fc(t,x),i=s.filter(x=>l(x.at)),c=i.reduce((x,h)=>x+h.added.length,0),d=i.reduce((x,h)=>x+h.removed.length,0),m=n.filter(x=>l(x.at)).length,u=t?Ra(t,a):null;if(u===null||c+d+m===0){const x=r.reduce((h,y)=>We(y)>We(h)?y:h);return`No changes since ${ja(x,a)}`}const p=[u];return c>0&&p.push(`${c} ${c===1?"query":"queries"} added`),d>0&&p.push(`${d} ${d===1?"query":"queries"} removed`),m>0&&p.push(`${m} new ${m===1?"model":"models"}`),p.join(" · ")}function Yp(t,s,n,a=null){const r=We(t);if(!Number.isFinite(r))return null;const l=s.filter(m=>We(m)<r);if(l.length>0)return Bt(l.reduce((m,u)=>We(u)>We(m)?u:m));const i=n.map(m=>$s(m)).filter(m=>m!==null).sort((m,u)=>We(m.start)-We(u.start)),c=i.findIndex(m=>We(m.start)<=r&&r<=We(m.end));if(c===-1)return null;const d=i[c];return We(d.start)===r?c>0?i[c-1].end:a&&We(a)<r?Bt(a):null:d.sweepCount===2&&We(d.end)===r?d.start:null}function Jp(t){const s=new Map,n=(a,r)=>{const l=s.get(a);l?l.push(r):s.set(a,[r])};for(const a of[...t].sort((r,l)=>r.revision-l.revision)){const r=We(a.at);for(const l of a.removed)n(l,{at:r,member:!1});for(const l of a.added)n(l,{at:r,member:!0})}return new Map([...s].filter(([,a])=>a.at(-1).member))}function Hn(t,s){let n=!t[0].member;for(const a of t)a.at<=s&&(n=a.member);return n}function Xp(t,s,n){return t.some(a=>a.at>s&&a.at<=n)}function mi(t,s){const n=We(s.start),a=We(s.end);return s.sweepCount>2?Xp(t,n,a):Hn(t,n)!==Hn(t,a)}function vc(t,s,n,a){const r=We(s),l=We(n),i={added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]},c=new Set;for(const[p,x]of Jp(t)){if(!a(x))continue;c.add(p);const h=Hn(x,r),y=Hn(x,l);h!==y?(y?i.added:i.removed).push(p):(h?i.removedAndAddedBack:i.addedAndRemovedAgain).push(p)}if(c.size===0)return null;const d=p=>[...p.added,...p.removed].some(x=>c.has(x)),m=t.filter(p=>We(p.at)>r&&We(p.at)<=l&&d(p)).sort((p,x)=>We(p.at)-We(x.at)),u=[...new Set(m.flatMap(p=>[...p.added,...p.removed]))].filter(p=>c.has(p));return{changes:m,keys:u,moves:i}}function Zp(t,s){if(t.length<2)return null;const n=t[0],a=t.at(-1),r=$s(n),l=$s(a),i=r?.start??n.startDate,c=l?.end??a.endDate,d=vc(s,i,c,m=>Hn(m,We(i))!==Hn(m,We(c))||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 jc(t,s){const n=$s(t);if(!n)return null;const a=vc(s,n.start,n.end,r=>mi(r,n));return a?{...a,firstCount:t.queryCount,latestCount:t.queryCount}:null}function Rr(t){return`${t} ${t===1?"query":"queries"}`}function ex(t){const s=[],n=a=>s.length===0?Rr(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(`${Rr(t.removedAndAddedBack.length)} removed and added back`),t.addedAndRemovedAgain.length>0&&s.push(`${Rr(t.addedAndRemovedAgain.length)} added and removed again`),xa(s)}function jo(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 No=320;function wo(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function So(t){return t==="non-brand"?0:t==="branded"?1:2}function tx(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 sx(t){return t.phrase}function Co(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 ko(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 nx(t,s){return t.map(n=>Nc(n,s))}function Nc(t,s){return s==="citations"?t:{...t,citationState:Co(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Co(n,s)}))}}function Ao(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,l=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",c=l==="cited"||l==="emerging";return r==="lost"||l!==null&&c&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||l!==null&&!c&&i?{key:s,label:`New ${n}`,tone:"positive"}:l===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function ax(t){const s=ci(nx(t,"mentions")),n=ci(t);return[Ao(s,"mentions"),Ao(n,"citations")]}function rx({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 Ro({items:t}){return e.jsx("div",{className:"query-evidence-signals","aria-label":"Latest run mention and citation signals",children:ax(t).map(s=>e.jsx(rx,{signal:s},s.key))})}function wc({queryClass:t,actions:s}){return e.jsxs(e.Fragment,{children:[s?e.jsx("div",{className:"query-evidence-toolbar",children:e.jsxs("div",{className:"query-evidence-actions",children:[!t&&e.jsx(Ll,{}),s]})}):null,t?e.jsx($l,{queryClass:t,manage:!!s}):null]})}function ix({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed",providerSelection:a,onProviderSelectionChange:r,addedQueries:l=[],actions:i,actionPanel:c}){const{openEvidence:d}=Ci(),m=o.useId(),[u,p]=o.useState(new Set),x=xd(),[h,y]=o.useState("mentions"),[f,b]=o.useState(n),[N,k]=o.useState("all"),[L,S]=o.useState(""),g=a??L,v=$=>{S($),r?.($)},C=o.useMemo(()=>[...new Set([...t.map($=>$.provider).filter(Boolean),...g?[g]:[]])].sort(),[t,g]),I=o.useMemo(()=>{const $=new Map;for(const ee of t){if(g&&ee.provider!==g)continue;const T=ee.query,E=ee.queryClass??null,te=s?ee.location??null:null,re=JSON.stringify([T,E,te]),le=$.get(re)??{key:re,phrase:T,queryClass:E,location:te,items:[],rawItems:[]};le.items.push(Nc(ee,h)),le.rawItems.push(ee),$.set(re,le)}return[...$.values()].sort((ee,T)=>So(ee.queryClass)-So(T.queryClass))},[t,h,s,g]),A=o.useMemo(()=>I.filter($=>N==="all"||(N==="unclassified"?$.queryClass===null:$.queryClass===N)),[I,N]),w=wn({rows:A,getSearchText:sx}),V=o.useMemo(()=>{const $=new Map;for(const ee of w.filteredRows){const T=$.get(ee.queryClass)??new Set;T.add(ee.phrase),$.set(ee.queryClass,T)}return $},[w.filteredRows]),G=o.useMemo(()=>new Set(l.map(Bn)),[l]),Q=x?6:5,B=w.rows.map($=>$.key),z=B.length>0&&B.every($=>u.has($)),ne=$=>{p(ee=>{const T=new Set(ee);return T.has($)?T.delete($):T.add($),T})},F=h==="mentions"?"mentioned":"cited",_=h==="mentions"?"Mention History":"Citation History",Z=h==="mentions"?"mentioned":"cited";return e.jsxs("div",{className:"query-evidence",children:[e.jsx(wc,{queryClass:N,actions:i}),c,e.jsxs("div",{className:"query-evidence-view-row",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"query-evidence-tabs",role:"tablist","aria-label":"Citation tracking view",children:["mentions","citations"].map($=>e.jsx("button",{id:`${m}-${$}`,type:"button",role:"tab","aria-controls":m,"aria-selected":h===$,tabIndex:h===$?0:-1,onClick:()=>y($),onKeyDown:ee=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(ee.key))return;ee.preventDefault();const T=ee.key==="Home"?"mentions":ee.key==="End"||$==="mentions"?"citations":"mentions";y(T),document.getElementById(`${m}-${T}`)?.focus()},children:$==="mentions"?"Mentions":"Citations"},$))}),e.jsx(Oe,{text:"Mentions track your brand or domain in answer text. Citations track your domain in source links. Each signal is measured independently."})]}),e.jsxs("div",{className:"query-evidence-display-controls",children:[e.jsxs("label",{className:"query-evidence-preview-toggle",children:[e.jsx("input",{type:"checkbox",checked:f==="detailed",onChange:$=>b($.target.checked?"detailed":"compact")}),"Show answer previews"]}),e.jsx(P,{type:"button",variant:"ghost",className:"min-h-11",disabled:B.length===0,onClick:()=>{p($=>{const ee=new Set($);for(const T of B)z?ee.delete(T):ee.add(T);return ee})},children:z?"Collapse page":"Expand page"})]})]}),t.length>0||g?e.jsxs("div",{className:"query-evidence-filters",children:[e.jsx(Js,{value:w.query,onChange:w.setQuery,label:"Find a query",placeholder:"Find a query",className:"query-evidence-search"}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Answer engine"}),e.jsxs("select",{value:g,onChange:$=>{v($.target.value),w.setPage(1)},children:[e.jsx("option",{value:"",children:"All engines"}),C.map($=>e.jsx("option",{value:$,children:ot($)},$))]})]}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Query class"}),e.jsxs("select",{value:N,onChange:$=>{k($.target.value),w.setPage(1)},children:[e.jsx("option",{value:"all",children:"All queries"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]})]}):null,e.jsxs("div",{id:m,role:"tabpanel","aria-labelledby":`${m}-${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"}),x&&e.jsx("th",{scope:"col","aria-label":"Sentiment",children:e.jsxs("span",{className:"inline-flex items-center",children:["Sentiment",e.jsx(Oe,{text:"Branded query rows show the favorable share of judged answers. Non-brand rows show only their unfavorable and mixed answers. Expanded engine rows show each stored answer’s sentiment; factual and unmentioned answers are not judgments."})]})}),e.jsx("th",{scope:"col",children:_}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Answer"})})]})}),tx(w.rows).map($=>e.jsxs("tbody",{children:[e.jsx("tr",{className:"query-evidence-group",children:e.jsxs("th",{scope:"rowgroup",colSpan:Q,children:[wo($.queryClass)," (",V.get($.queryClass)?.size??0,")"]})}),$.rows.map(({key:ee,phrase:T,queryClass:E,location:te,items:re,rawItems:le})=>{const we=u.has(ee),X=B.indexOf(ee),ue=`${m}-query-${X}`,xe=G.has(Bn(T)),J=re.map(ie=>ie.citationState),he=J.includes("cited")?"cited":J.includes("emerging")?"emerging":J.includes("lost")?"lost":J.every(ie=>ie==="pending")?"pending":"not-cited",K=[...new Set(le.map(ie=>ie.queryId).filter(ie=>!!ie))],pe=le.map(ie=>ie.sourceSnapshotId).filter(ie=>!!ie),qe=ci(re),Ae=re.filter(ie=>ie.citationState===gd.cited||ie.citationState==="emerging").length;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-row",onClick:()=>ne(ee),children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("button",{type:"button",className:"query-evidence-query","aria-label":T,"aria-describedby":ue,"aria-expanded":we,onClick:ie=>{ie.stopPropagation(),ne(ee)},children:[e.jsx(lc,{size:16,"aria-hidden":"true",className:we?"rotate-90":""}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{children:T}),e.jsxs("span",{id:ue,className:"query-evidence-meta",children:[e.jsx("span",{children:wo(E)}),s&&e.jsx("span",{children:te??"No location"}),re.filter(ie=>ie.provider).map(ie=>e.jsx("span",{children:ot(ie.provider)},ie.id))]})]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ri,{state:he,label:ko(he,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":`${Ae} of ${re.length} engines ${Z}`,title:`${Ae} of ${re.length} engines ${Z}`,children:[Ae,"/",re.length]})]})}),x&&e.jsx("td",{children:e.jsx(ql,{queryId:K.length===1?K[0]:null,sourceSnapshotIds:K.length>1?[]:pe,queryClass:E,location:s?te:void 0})}),e.jsx("td",{children:e.jsx(bo,{history:qe,signal:h})}),e.jsx("td",{className:"evidence-change-cell",children:xe?e.jsx("span",{className:"query-evidence-new",children:"new query"}):e.jsx(Ro,{items:le})}),e.jsx("td",{})]}),we&&re.map((ie,fe)=>e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-engine-row",children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"text-sm text-secondary",children:ie.provider?ot(ie.provider):"Awaiting engine"})}),e.jsx("td",{children:e.jsx(ri,{state:ie.citationState,className:"rounded-none border-0 bg-transparent p-0 text-sm tracking-normal",label:ko(ie.citationState,h)})}),x&&e.jsx("td",{children:e.jsx(El,{queryId:ie.queryId,sourceSnapshotIds:ie.sourceSnapshotId?[ie.sourceSnapshotId]:[],queryClass:ie.queryClass,provider:ie.provider,location:ie.location??null})}),e.jsx("td",{children:e.jsx(bo,{history:ie.runHistory,signal:h})}),e.jsx("td",{className:"evidence-change-cell",children:xe?null:e.jsx(Ro,{items:[le[fe]??ie]})}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",className:"min-h-11",type:"button",title:`View ${ie.provider?ot(ie.provider):"saved"} answer for ${ie.query}`,onClick:Ce=>{Ce.stopPropagation(),d(ie.id)},children:"View"})})]}),f==="detailed"&&e.jsx("tr",{className:"query-evidence-preview-row",children:e.jsx("td",{colSpan:Q,children:e.jsx(lx,{item:ie,mode:h,onViewFull:()=>d(ie.id)},h)})})]},ie.id))]},ee)})]},$.queryClass??"unclassified"))]})}),w.totalRows===0&&(w.hasQuery||N!=="all"||g)?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ks,{page:w.page,pageSize:w.pageSize,visibleRows:w.rows.length,totalRows:w.totalRows,onPageChange:w.setPage,itemLabel:w.hasQuery||N!=="all"||g?"matches":"queries"})]}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",F==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function ox(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=yd(t),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function hi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function lx({item:t,mode:s,onViewFull:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1);if(s==="mentions")return e.jsx(Po,{item:t,onViewFull:n});const c=t.evidenceUrls.length>0?t.evidenceUrls.map(d=>({uri:d,title:t.groundingSources.find(m=>m.uri===d)?.title})):t.groundingSources;return e.jsxs("div",{className:"query-evidence-preview space-y-3",children:[e.jsx("p",{className:"text-[13px] font-medium text-secondary",children:t.evidenceUrls.length>0?"Cited sources":c.length>0?"Grounding sources":"Cited domains"}),c.length>0?e.jsx("ul",{className:"space-y-4",children:c.slice(0,l?void 0:6).map((d,m)=>e.jsxs("li",{className:"min-w-0",children:[e.jsx(ki,{url:d.uri,title:d.title}),hi(t,fd(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,hi(t,d)?" · competitor source":""]},d))}):e.jsx("p",{className:"text-sm text-secondary",children:"No cited sources captured for this run."}),(c.length>6||c.length===0&&t.citedDomains.length>6)&&e.jsx(P,{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(Po,{item:t,onViewFull:n,contextOnly:!0})]}):e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."})]})}function Po({item:t,onViewFull:s,contextOnly:n=!1}){const{matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}=t,c=o.useMemo(()=>ox({matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}),[a,r,l,i]);if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."});const m=t.answerSnippet.length>No;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(Ti,{headingLevel:4,highlightGroups:c,previewLength:No,children:t.answerSnippet}),(!n&&t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("dl",{className:"space-y-2 text-[13px] leading-6 text-secondary",children:[!n&&t.citedDomains.length>0&&e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Cited domains"}),e.jsxs("dd",{className:"flex flex-wrap gap-x-3 gap-y-1",children:[t.citedDomains.slice(0,6).map(u=>e.jsxs("span",{className:"[overflow-wrap:anywhere]",children:[u,hi(t,u)?" · competitor source":""]},`c-${u}`)),t.citedDomains.length>6&&e.jsxs("span",{children:["+",t.citedDomains.length-6," more"]})]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Competitors in answer"}),e.jsxs("dd",{className:"flex flex-wrap gap-x-3 gap-y-1",children:[t.mentionedCompetitorDomains.slice(0,4).map(u=>e.jsx("span",{className:"[overflow-wrap:anywhere]",children:u},`co-${u}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]})]}),m&&e.jsx(P,{type:"button",variant:"ghost",className:"min-h-11",onClick:u=>{u.stopPropagation(),s()},children:"View full answer"})]})}function Fa({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 gr({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:l=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(i=>e.jsx("button",{type:"button","aria-pressed":s===i,disabled:l,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>{i!==s&&bd("window"),n(i)},children:r?r(i):i},i))})}const Pr=lt[0],Ir=lt[1],Io=lt[2],To=lt[3],cx=["both","server","ga4"],Mo={fontSize:11,paddingTop:6},Lo=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),$o=t=>typeof t=="number"?sr(Math.round(t)):String(t),rs=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function Tr(t,s){if(!t||s<2)return Array(s).fill(null);const n=t.endIndex-t.startIndex;if(n<=0)return Array(s).fill(null);const a=(t.end-t.start)/n;return Array.from({length:s},(r,l)=>l<t.startIndex||l>t.endIndex?null:t.start+(l-t.startIndex)*a)}function Mr({label:t,value:s,caption:n,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx(Oe,{text:a})]}),e.jsx("p",{className:"text-xl font-semibold text-primary tabular-nums",children:s}),e.jsx("p",{className:"text-xs text-muted mt-0.5",children:n})]})}function dx(t,s){return n=>{const{cx:a,cy:r,index:l,key:i}=n,c=l??-1;return!(t[c]!=null&&t[c-1]==null&&t[c+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function ux({projectName:t,sinceMinutes:s}){const[n,a]=o.useState(!0),[r,l]=o.useState(!0),[i,c]=o.useState("both"),d=tp(t,{sinceMinutes:s,granularity:"day",limit:1}),m=sp(t),p=$e({...Dl({client:Y,path:{name:t}}),enabled:!!t,staleTime:vn}).data?.connected===!0,x=$e({...Ol({client:Y,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&p,staleTime:vn}),h=o.useMemo(()=>d.data?.series?.points??[],[d.data]),y=o.useMemo(()=>{const I=x.data;return new Map((I?.days??[]).map(A=>[A.date,A.sessions]))},[x.data]),f=o.useMemo(()=>{const I=w=>w.measured!==!1;if(h.length===0||I(h[0]))return null;const A=h.findIndex(I)-1;return A<0?{from:h[0].bucket,to:h[h.length-1].bucket}:{from:h[0].bucket,to:h[A].bucket}},[h]),b=d.data?.series?.coverageStart??null,N=d.data?.series?.trends,k=o.useMemo(()=>{const I=Tr(N?.crawlerContentHits,h.length),A=Tr(N?.aiUserFetchHits,h.length),w=Tr(N?.aiReferralLandedHits,h.length);return h.map((V,G)=>({...V,crawlerContentHits:V.measured!==!1?rs(V.crawlerContentHits):null,aiUserFetchHits:V.measured!==!1?rs(V.aiUserFetchHits):null,aiReferralLandedHits:V.measured!==!1?rs(V.aiReferralLandedHits):null,ga4Visits:y.get(V.bucket)??null,crawlTrend:I[G],fetchTrend:A[G],visitTrend:w[G]}))},[h,y,N]),L=d.data?.totals,S=L&&{crawlers:rs(L.crawlerContentHits),fetches:rs(L.aiUserFetchHits),visits:rs(L.aiReferralLandedHits)},g=o.useMemo(()=>h.reduce((I,A)=>({crawlers:I.crawlers+rs(A.crawlerContentHits),fetches:I.fetches+rs(A.aiUserFetchHits),visits:I.visits+rs(A.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[h]),v=S??g,C=v.crawlers>0||v.fetches>0||v.visits>0;if(d.isLoading)return e.jsx(je,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(d.isError)return e.jsxs(je,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!C){const I=m.data?.sources,A=I!==void 0&&I.length===0,w=!A&&b===null;return e.jsxs(je,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:A?"No server-side traffic source connected yet.":w?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:A?"Connect a traffic source to see how AI engines read this site over time.":w?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Mr,{label:"AI crawlers",value:sr(v.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(Mr,{label:"AI page fetches",value:sr(v.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(Mr,{label:"AI visitors",value:sr(v.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),h.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:rs(h[h.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:rs(h[h.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:rs(h[h.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(h[h.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(Oe,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:I=>a(I.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:I=>l(I.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Xs,{width:"100%",height:206,children:e.jsxs(Zs,{data:k,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(va,{stroke:ya,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Ut,stroke:us,tickFormatter:Sn,minTickGap:28}),e.jsx(tn,{tick:Ut,stroke:us,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:Pt,formatter:$o}),f&&e.jsx(ni,{x1:f.from,x2:f.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(cr,{wrapperStyle:Mo,iconType:"plainline",iconSize:14,formatter:I=>Lo.has(I)?"":I}),e.jsx(Ws,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Pr,fill:Pr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Ws,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Ir,fill:Ir,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Gs,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Pr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Gs,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Ir,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(Oe,{text:"Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other."})]}),e.jsx(gr,{windows:cx,value:i,onChange:c,label:"Visit measurement source",formatOption:I=>I==="ga4"?"GA4":I==="both"?"Both":"Server"})]}),e.jsx(Xs,{width:"100%",height:176,children:e.jsxs(Zs,{data:k,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(va,{stroke:ya,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Ut,stroke:us,tickFormatter:Sn,minTickGap:28}),e.jsx(tn,{tick:Ut,stroke:us,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:Pt,formatter:$o}),f&&e.jsx(ni,{x1:f.from,x2:f.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(cr,{wrapperStyle:Mo,iconType:"plainline",iconSize:14,formatter:I=>Lo.has(I)?"":I}),i!=="ga4"&&e.jsx(Gs,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Io,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Gs,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:To,strokeWidth:1.8,strokeDasharray:"5 3",dot:dx(k.map(I=>I.ga4Visits),To)}),r&&i!=="ga4"&&e.jsx(Gs,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Io,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const mx=6,Wn="__other__",_n="_socialTotal";function hx(t,s=mx){const n=new Map;for(const u of t)n.set(u.source,(n.get(u.source)??0)+u.sessions);const a=[...n.entries()].sort((u,p)=>p[1]!==u[1]?p[1]-u[1]:u[0].localeCompare(p[0])),r=a.slice(0,s),l=new Set(r.map(([u])=>u)),i=Math.max(0,a.length-s),c=new Map;for(const u of t){let p=c.get(u.date);p||(p={date:u.date,[_n]:0},c.set(u.date,p));const x=l.has(u.source)?u.source:Wn;p[x]=(p[x]??0)+u.sessions,p[_n]=(p[_n]??0)+u.sessions}const d=[...c.values()].sort((u,p)=>String(u.date).localeCompare(String(p.date))),m=r.map(([u])=>u);return i>0&&m.push(Wn),{data:d,sources:m,otherCount:i}}function Un(t){return t.replace(/\+/g," ")}function Sc(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const qo="_totalSessions",Eo="_organicSessions";function px(t,s){const n=new Map;for(const i of s)n.set(i.date,{[qo]:i.sessions,[Eo]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[qo]:0,[Eo]:0},n.set(i.date,c));for(const d of i.bySource)c[d.source]=(c[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([i],[c])=>i.localeCompare(c)).map(([i,c])=>({date:i,...c})),r=a.map(i=>i.date),l=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:l}}const xx=["7d","30d","90d"],gx={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Hs=lt,pi=ms.textDim,Cc=ms.textFaint,aa=25;function fx(t){return rc(t.landingPage)}const yx=25,bx=10,Lr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Ga(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function kc(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function vx({projectName:t}){const{data:s,isLoading:n,isError:a}=np(t);if(n)return e.jsx(je,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(je,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!oe()&&e.jsx(Ms,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(je,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!oe()&&e.jsxs(e.Fragment,{children:[e.jsx(Ms,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(je,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(l=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(Ne,{tone:ap(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?kc(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:oe()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Ms,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function jx({projectName:t}){const[s,n]=o.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(vx,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(gr,{windows:xx,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(Nx,{projectName:t,window:s}),e.jsx(ux,{projectName:t,sinceMinutes:gx[s]})]})}function Nx({projectName:t,window:s}){const n=hs(),a=s??"30d",[r,l]=o.useState(null),[i,c]=o.useState(null),[d,m]=o.useState(!0),[u,p]=o.useState(!1),[x,h]=o.useState(!1),[y,f]=o.useState(null),[b,N]=o.useState(null),[k,L]=o.useState("sessions"),[S,g]=o.useState("desc"),[v,C]=o.useState("sessions"),[I,A]=o.useState("desc"),[w,V]=o.useState("sessions"),[G,Q]=o.useState("desc"),[B,z]=o.useState("sessions"),[ne,F]=o.useState("desc"),[_,Z]=o.useState(Lr),[$,ee]=o.useState([]),[T,E]=o.useState([]),[te,re]=o.useState(!1);async function le(se){m(!0),f(null);try{const _e=await n.fetchQuery({...Dl({client:Y,path:{name:t}}),staleTime:vn});if(se.current)return;if(l(_e),!_e.connected){c(null),Z(Lr),ee([]),E([]),m(!1);return}const Re=a==="all"?void 0:a,ve=await n.fetchQuery({...vd({client:Y,path:{name:t},query:Re?{window:Re}:void 0}),staleTime:vn}),Tt=ve.windowStart||ve.windowEnd?{...ve.windowStart?{startDate:ve.windowStart}:{},...ve.windowEnd?{endDate:ve.windowEnd}:{}}:void 0,[Xt,Zt,Ot]=await Promise.all([n.fetchQuery({...Ol({client:Y,path:{name:t},query:Re?{window:Re}:void 0}),staleTime:vn}).catch(()=>Lr),n.fetchQuery({...jd({client:Y,path:{name:t},query:Re?{window:Re}:void 0}),staleTime:vn}).catch(()=>[]),n.fetchQuery({...Nd({client:Y,path:{name:t},query:Tt}),staleTime:vn}).catch(()=>[])]);if(se.current)return;c(ve),Z(Xt),ee(Zt),E(Ot),m(!1)}catch(_e){if(se.current)return;f(_e instanceof Error?_e.message:"Failed to load GA4 data"),m(!1)}}o.useEffect(()=>{const se={current:!1};return le(se),()=>{se.current=!0}},[t,a,n]);async function we(){p(!0),f(null),N(null);try{const se=await Fl(t);N(`Synced ${se.rowCount.toLocaleString()} page rows, ${se.aiReferralCount.toLocaleString()} AI and ${se.socialReferralCount.toLocaleString()} social referral rows (${se.days} days)`),await $t(n,"ga"),await le({current:!1})}catch(se){f(se instanceof Error?se.message:"Sync failed")}finally{p(!1)}}async function X(){h(!0),f(null),N(null);try{await wd(t),await $t(n,"ga"),l({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),N("GA4 disconnected")}catch(se){f(se instanceof Error?se.message:"Disconnect failed")}finally{h(!1)}}function ue(se){K.setPage(1),k===se?g(_e=>_e==="desc"?"asc":"desc"):(L(se),g("desc"))}function xe(se){v===se?A(_e=>_e==="desc"?"asc":"desc"):(C(se),A("desc"))}function J(se){w===se?Q(_e=>_e==="desc"?"asc":"desc"):(V(se),Q("desc"))}const he=o.useMemo(()=>i?.topPages?[...i.topPages].sort((se,_e)=>{const Re=se[k],ve=_e[k];return typeof Re=="string"&&typeof ve=="string"?S==="asc"?Re.localeCompare(ve):ve.localeCompare(Re):S==="asc"?Re-ve:ve-Re}):[],[i?.topPages,k,S]),K=wn({rows:he,getSearchText:se=>rc(se.landingPage),pageSize:bx}),pe=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((se,_e)=>{const Re=se[v],ve=_e[v];return typeof Re=="string"&&typeof ve=="string"?I==="asc"?Re.localeCompare(ve):ve.localeCompare(Re):I==="asc"?Re-ve:ve-Re}):[],[i?.aiReferrals,v,I]),qe=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((se,_e)=>{const Re=se[B],ve=_e[B];return typeof Re=="string"&&typeof ve=="string"?ne==="asc"?Re.localeCompare(ve):ve.localeCompare(Re):ne==="asc"?Re-ve:ve-Re}):[],[i?.aiReferralLandingPages,B,ne]),Ae=wn({rows:qe,getSearchText:fx,pageSize:yx}),ie=Ae.totalRows>0?`${Ae.totalRows.toLocaleString()} ${Ae.hasQuery?Ae.totalRows===1?"match":"matches":Ae.totalRows===1?"row":"rows"}`:Ae.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function fe(se){Ae.setPage(1),B===se?F(_e=>_e==="desc"?"asc":"desc"):(z(se),F("desc"))}const Ce=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((se,_e)=>{const Re=se[w],ve=_e[w];return typeof Re=="string"&&typeof ve=="string"?G==="asc"?Re.localeCompare(ve):ve.localeCompare(Re):G==="asc"?Re-ve:ve-Re}):[],[i?.socialReferrals,w,G]),{socialChartData:Ge,socialChartSources:Ee,socialOtherCount:O}=o.useMemo(()=>{const se=hx(T);return{socialChartData:se.data,socialChartSources:se.sources,socialOtherCount:se.otherCount}},[T]),{chartData:D,chartSources:H,dateRange:Me}=o.useMemo(()=>{const se=px(_,$);return{chartData:se.data,chartSources:se.sources,dateRange:se.dateRange}},[_,$]);if(d&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return oe()||Ls()?e.jsx(je,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(wx,{projectName:t,onConnected:()=>{(async()=>(await $t(n,"ga"),await le({current:!1})))()}});const Qe=i?.organicSharePctDisplay??"0%",Fe=i?.channelBreakdown?.organic.sharePctDisplay??Qe,tt=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,ge=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,vt=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Ve=i?.paidAiSessionsBySession??0,Je=i?.paidAiSharePctBySessionDisplay??"0%",Dt=i?new Set(i.aiReferrals.map(se=>se.source.toLowerCase())).size:0,ct=pe[0]??null,at=i?.totalDirectSessions??0,pt=i?.directSharePctDisplay??"0%",Ct=i?.channelBreakdown?.direct.sessions??at,It=i?.channelBreakdown?.direct.sharePctDisplay??pt,He=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,R=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Le=i?.socialSessions??0,Pe=i?.socialSharePctDisplay??"0%",Ke=i?.channelBreakdown?.social.sessions??Le,dt=i?.channelBreakdown?.social.sharePctDisplay??Pe,ze=i?new Set(i.socialReferrals.map(se=>se.source.toLowerCase())).size:0,yt=Ce[0]??null;return e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:y}),b&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:b}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!oe()&&!Ls()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:u,onClick:Ze(we),children:[e.jsx(ba,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Ze(X),children:[e.jsx(Uh,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"mb-4 flex items-start justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Oe,{text:`Aggregated traffic metrics from Google Analytics 4.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]})}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx($r,{value:Ga(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx($r,{value:Ga(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Qe} of total`,tone:"positive"}),e.jsx($r,{value:i.totalUsers===null?"—":Ga(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."}),!oe()&&!Ls()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:u,onClick:Ze(we),children:[e.jsx(ba,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Oe,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),Me&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Me.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Me.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),D.length>0&&e.jsxs(je,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:H.length>0?"AI vs. total sessions":"All sessions (baseline)"}),H.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),H.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(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:D,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:us},tickFormatter:Sn}),e.jsx(tn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ns,labelFormatter:Pt,formatter:(se,_e)=>{const Re=typeof se=="number"?se.toLocaleString():String(se??0),ve=String(_e??"");return ve==="_totalSessions"?[Re,"Total Sessions"]:ve==="_organicSessions"?[Re,"Organic Sessions"]:[Re,ve]}}),e.jsx(cr,{wrapperStyle:{fontSize:11,color:ms.text},formatter:se=>se==="_totalSessions"?"Total Sessions":se==="_organicSessions"?"Organic Sessions":se}),e.jsx(Ws,{type:"monotone",dataKey:"_totalSessions",stroke:ms.textFaint,fill:ms.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),H.map((se,_e)=>e.jsx(Ws,{type:"monotone",dataKey:se,stackId:"ai",stroke:Hs[_e%Hs.length],fill:Hs[_e%Hs.length],fillOpacity:.4,strokeWidth:1.5},se))]})})})]}),e.jsxs(je,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(xs,{label:"Organic",value:Fe,hint:`${tt.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(xs,{label:"Social",value:dt,hint:`${Ke.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(xs,{label:"Direct",value:It,hint:`${Ct.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(xs,{label:"Visitors from AI (at least)",value:vt,hint:Ve>0?`${ge.toLocaleString()} sessions · ${Ve.toLocaleString()} paid`:`${ge.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(xs,{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."})]}),ct&&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:ct.source})," via ",ct.medium,", accounting for ",ct.sessions.toLocaleString()," sessions.",Ve>0&&e.jsxs("span",{children:[" Paid AI: ",Ve.toLocaleString()," sessions (",Je,")."]})]})]}),e.jsxs(je,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${Dt} 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(is,{label:"Source",sortKey:"source",current:v,dir:I,onSort:xe,align:"left"}),e.jsx(is,{label:"Medium",sortKey:"medium",current:v,dir:I,onSort:xe,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(is,{label:"Sessions",sortKey:"sessions",current:v,dir:I,onSort:xe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:pe.map(se=>e.jsx(Cx,{referral:se},`${se.source}:${se.medium}:${se.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:ie})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Js,{value:Ae.query,onChange:Ae.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Ae.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(is,{label:"Landing Page",sortKey:"landingPage",current:B,dir:ne,onSort:fe,align:"left"}),e.jsx(is,{label:"Source",sortKey:"source",current:B,dir:ne,onSort:fe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:B,dir:ne,onSort:fe,align:"right"})]})}),e.jsx("tbody",{children:Ae.rows.map(se=>e.jsx(kx,{row:se},`${se.landingPage}:${se.source}:${se.medium}:${se.sourceDimension}`))})]})}),e.jsx(Ks,{page:Ae.page,pageSize:Ae.pageSize,visibleRows:Ae.rows.length,totalRows:Ae.totalRows,onPageChange:Ae.setPage,itemLabel:Ae.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:()=>Ae.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Oe,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(xs,{label:"Social Sessions",value:Ga(Le),hint:`${Le.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(xs,{label:"Share of Traffic",value:Pe,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(xs,{label:"Platforms",value:String(ze),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."})]}),yt&&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:`${yt.source} via ${yt.medium}`,children:Sc(Un(yt.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:yt.medium,children:["via ",Un(yt.medium)," · ",yt.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(xs,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(xs,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(xs,{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."})]})]})]}),Ge.length>0&&e.jsxs(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),O>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ee.length-1," sources · ",O," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:Ge,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:us},tickFormatter:Sn}),e.jsx(tn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ns,labelFormatter:Pt,formatter:(se,_e)=>{const Re=typeof se=="number"?se.toLocaleString():String(se??0),ve=String(_e??"");if(ve===_n)return[Re,"Total Social"];if(ve===Wn){const Tt=`Other (${O} source${O===1?"":"s"})`;return[Re,Tt]}return[Re,Un(ve)]}}),e.jsx(Ws,{type:"monotone",dataKey:_n,stroke:Cc,fill:ms.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ee.map((se,_e)=>{const ve=se===Wn?pi:Hs[_e%Hs.length];return e.jsx(Ws,{type:"monotone",dataKey:se,stackId:"social",stroke:ve,fill:ve,fillOpacity:.4,strokeWidth:1.5},se)})]})})}),e.jsx(Rx,{sources:Ee,otherCount:O})]}),e.jsxs(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Ce.length>aa&&!te?`Top ${aa} of ${Ce.length}`:`${Ce.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(is,{label:"Source",sortKey:"source",current:w,dir:G,onSort:J,align:"left"}),e.jsx(is,{label:"Medium",sortKey:"medium",current:w,dir:G,onSort:J,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:w,dir:G,onSort:J,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(te?Ce:Ce.slice(0,aa)).map(se=>e.jsx(Ax,{referral:se},`${se.source}:${se.medium}:${se.channelGroup}`))})]})}),Ce.length>aa&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>re(se=>!se),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:te?`Show top ${aa}`:`Show all ${Ce.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),i&&i.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Oe,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx(Js,{value:K.query,onChange:K.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(is,{label:"Landing Page",sortKey:"landingPage",current:k,dir:S,onSort:ue,align:"left"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:k,dir:S,onSort:ue,align:"right"}),e.jsx(is,{label:"Organic",sortKey:"organicSessions",current:k,dir:S,onSort:ue,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:K.rows.map(se=>e.jsx(Sx,{page:se},se.landingPage))})]})}),K.totalRows===0&&K.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Ks,{page:K.page,pageSize:K.pageSize,visibleRows:K.rows.length,totalRows:K.totalRows,onPageChange:K.setPage,itemLabel:K.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 ${kc(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function wx({projectName:t,onConnected:s}){const[n,a]=o.useState(""),[r,l]=o.useState(null),[i,c]=o.useState(null),[d,m]=o.useState(!1),[u,p]=o.useState(null),x=o.useRef(null),h=o.useCallback(f=>{const b=f.target.files?.[0];if(!b)return;p(null),l(b.name);const N=new FileReader;N.onload=()=>{const k=N.result;try{const L=JSON.parse(k);if(!L.client_email||!L.private_key){p("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),c(null);return}c(k)}catch{p("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},N.onerror=()=>{p("Failed to read file."),c(null)},N.readAsText(b)},[]);async function y(){if(p(null),!n.trim()){p("Property ID is required.");return}if(!i){p("Please upload a service account key file.");return}m(!0);try{await Sd(t,{propertyId:n.trim(),keyJson:i});try{await Fl(t)}catch{}s()}catch(f){p(f instanceof Error?f.message:"Failed to connect GA4")}finally{m(!1)}}return e.jsxs(je,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),u&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:u}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:f=>a(f.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:x,type:"file",accept:".json,application/json",onChange:h,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>x.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(Bh,{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(P,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:Ze(y),children:d?"Connecting & syncing…":"Connect GA4"})]})}function is({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 Ac={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function $r({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 ${Ac[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function xs({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Oe,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Ac[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Sx({page:t}){const s=et(t.organicShare);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:s})]})}const Rc={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Pc={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 Cx({referral:t}){const s=et(t.share),n=Rc[t.sourceDimension]??t.sourceDimension,a=Pc[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 kx({row:t}){const s=Rc[t.sourceDimension]??t.sourceDimension,n=Pc[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(ar,{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 Ax({referral:t}){const s=et(t.share),n=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Un(t.source),r=Un(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 Rx({sources:t,otherCount:s}){const n=[{key:_n,color:Cc,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Wn)n.push({key:Wn,color:pi,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Un(r);n.push({key:r,color:Hs[a%Hs.length]??pi,label:Sc(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 Px(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 Ix="Search Console is not connected yet. Your Canonry team can set this up.",Tx=["7d","30d","90d","all"],Ka=500,Do=[{key:"clicks",label:"Clicks",color:lt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:lt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Jn.caution,format:t=>et(t)},{key:"position",label:"Avg position",color:lt[2],inverted:!0,format:t=>t.toFixed(1)}],zs=25,Mx="canonry:google-oauth-complete";function Lx(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const i=t.prior[s],c=t.trailing[s];return i!==null&&c!==null&&i<=0&&c>0?`new in the last ${a}d`:i===null||i<=0?`no prior ${a}d to compare`:c===null?`no value in the last ${a}d`:"comparison unavailable"}return r===0?`→ no change vs prior ${a}d`:`${(n?r<0:r>0)?"↑":"↓"} ${et(Math.abs(r))} vs prior ${a}d`}function $x(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,l=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,c=`${r.startDate} to ${r.endDate}`,d=`Tile percentages compare these ${s} ${l} (${c}) with the ${s} ${l} before them (${i}).`;return n!=="split-window"?d:`${d} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function Oo(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Fo(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 Go(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function qx({projectName:t,refreshNonce:s}){const n=hs(),{isAdmin:a}=nn(),r=Ls(),[l,i]=o.useState(!1),[c,d]=o.useState([]),[m,u]=o.useState([]),[p,x]=o.useState([]),[h,y]=o.useState(null),[f,b]=o.useState([]),[N,k]=o.useState([]),[L,S]=o.useState(null),[g,v]=o.useState(""),[C,I]=o.useState(""),[A,w]=o.useState("30"),[V,G]=o.useState(!1),[Q,B]=o.useState("30d"),[z,ne]=o.useState(["clicks","impressions"]),[F,_]=o.useState(!0),[Z,$]=o.useState(null),[ee,T]=o.useState(0),[E,te]=o.useState({startDate:"",endDate:"",query:"",page:""}),[re,le]=o.useState(0),[we,X]=o.useState(!1),[ue,xe]=o.useState(0),[J,he]=o.useState(!1),[K,pe]=o.useState(""),[qe,Ae]=o.useState(!0),[ie,fe]=o.useState(!1),[Ce,Ge]=o.useState(!1),[Ee,O]=o.useState(!1),[D,H]=o.useState(!1),[Me,Qe]=o.useState(!1),[Fe,tt]=o.useState(!1),[ge,vt]=o.useState(null),[Ve,Je]=o.useState(!1),[Dt,ct]=o.useState(!1),[at,pt]=o.useState(null),[Ct,It]=o.useState(null),[He,R]=o.useState([]),[Le,Pe]=o.useState(new Set),[Ke,dt]=o.useState({}),[ze,yt]=o.useState(new Set),[se,_e]=o.useState(""),[Re,ve]=o.useState(null),[Tt,Xt]=o.useState(""),[Zt,Ot]=o.useState(!1),[ut,es]=o.useState(!1),[it,gs]=o.useState(!1),[ps,Bs]=o.useState(!1),[bt,Vs]=o.useState("indexed"),[Mt,as]=o.useState(null),Vt=!!(E.query.trim()||E.page.trim()||Mt),xt=Mt!==null,ts=o.useMemo(()=>{if(!Mt)return p;const{key:j,dir:W}=Mt;return[...p].sort((de,ke)=>{const rt=j===jn.CTR?Number.isFinite(de.ctr)?de.ctr:0:de[j],nt=j===jn.CTR?Number.isFinite(ke.ctr)?ke.ctr:0:ke[j];return W==="asc"?rt-nt:nt-rt})},[p,Mt]),zt=wn({rows:ts,pageSize:Os}),fs=J?zt.rows:ts,Qt=wn({rows:(at??[]).filter(j=>j.path.toLowerCase().includes(se.trim().toLowerCase())),pageSize:Os}),[gt,Lt]=o.useState([]),[Nt,ys]=o.useState(null),[bs,U]=o.useState(1),ae=o.useMemo(()=>{if(gt.length<2)return null;const j=gt[gt.length-1],W=gt[gt.length-2];return{indexed:j.indexed-W.indexed,notIndexed:j.notIndexed-W.notIndexed}},[gt]);o.useEffect(()=>{U(1)},[ge,bt,Nt]);const me=o.useMemo(()=>Nt?(ge?.reasonGroups??[]).find(j=>j.reason===Nt):void 0,[ge,Nt]),ce=o.useMemo(()=>ge?bt==="indexed"?ge.indexed:bt==="deindexed"?ge.deindexed:bt==="notIndexed"?Nt?me?.urls??[]:(ge.reasonGroups??[]).length===0?ge.notIndexed:[]:[]:[],[ge,bt,Nt,me]),Ie=Math.max(1,Math.ceil(ce.length/zs)),Ue=Math.min(Math.max(1,bs),Ie),mt=(Ue-1)*zs,kt=o.useMemo(()=>ge?.indexed.slice(mt,mt+zs)??[],[ge,mt]),vs=o.useMemo(()=>ge?.notIndexed.slice(mt,mt+zs)??[],[ge,mt]),q=o.useMemo(()=>ge?.deindexed.slice(mt,mt+zs)??[],[ge,mt]),Se=o.useMemo(()=>(me?.urls??[]).slice(mt,mt+zs),[me,mt]),[st,qt]=o.useState(!1),[Ft,Be]=o.useState(null),[wt,qs]=o.useState(null),[Xn,ss]=o.useState(null);function an(j,W){const de=rp(j),ke=Px(de);ke?(qs(ke),Be(null)):(qs(null),Be(de.message||W))}const Gt=c.find(j=>j.connectionType==="gsc"),Es=(Gt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),Ds=He.length>0?He:(at??[]).map(j=>j.path),kn=Ds.filter(j=>at?.some(W=>W.path===j&&W.isSitemapsIndex)).length,Pa=kn===1?"Resubmit sitemap index":kn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Zn=p.length>0||f.length>0||N.length>0,ea=Cd(),rn=kd();async function fr(j,W=!1){if(r){u([]);return}if(!j){u([]),v("");return}Ge(!0);try{const{sites:de}=await n.fetchQuery({...Kd({client:Y,path:{name:t}}),staleTime:W?0:Yt});u(de),v(j.propertyId??de[0]?.siteUrl??""),qs(null)}catch(de){u([]),an(de,"Failed to load Search Console properties")}finally{Ge(!1)}}async function An(j){H(!0);const W=j??re;try{const de=Vt?Ka:Os,ke=Vt?0:W,rt={limit:String(de)};E.startDate&&(rt.startDate=E.startDate),E.endDate&&(rt.endDate=E.endDate),E.query&&(rt.query=E.query),E.page&&(rt.page=E.page),ke>0&&(rt.offset=String(ke)),Q&&Q!=="all"&&!E.startDate&&(rt.window=Q);const nt=await n.fetchQuery({...Id({client:Y,path:{name:t},query:rt}),staleTime:Yt}),ht=nt.rows;Vt?(X(!1),x(ht),xe(ht.length),he(!0)):(X(ke+ht.length<nt.totalMatching),x(ht),xe(0),he(!1))}catch(de){x([]),X(!1),xe(0),Be(de instanceof Error?de.message:"Failed to load GSC performance data")}finally{H(!1)}}async function on(){try{const j={};E.startDate&&(j.startDate=E.startDate),E.endDate&&(j.endDate=E.endDate),Q&&Q!=="all"&&!E.startDate&&(j.window=Q);const W=await n.fetchQuery({...Pd({client:Y,path:{name:t},query:j}),staleTime:Yt});y(W)}catch{y(null)}}async function Rn(j=!1){Qe(!0);try{const W=K.trim()||void 0,de={limit:"20"};W&&(de.url=W);const[ke,rt]=await Promise.all([n.fetchQuery({...Fd({client:Y,path:{name:t},query:de}),staleTime:j?0:Yt}),n.fetchQuery({...Gd({client:Y,path:{name:t}}),staleTime:j?0:Yt})]);b(ke),k(rt)}catch(W){b([]),k([]),Be(W instanceof Error?W.message:"Failed to load GSC inspection history")}finally{Qe(!1)}}async function ln(j=!1){Je(!0);try{const[W,de]=await Promise.all([n.fetchQuery({...Ld({client:Y,path:{name:t}}),staleTime:j?0:Yt}),n.fetchQuery({...$d({client:Y,path:{name:t}}),staleTime:j?0:Yt}).catch(()=>[])]);vt(W),Lt(de)}catch(W){vt(null),Lt([]),Be(W instanceof Error?W.message:"Failed to load coverage data")}finally{Je(!1)}}async function cn(j){qt(!0),Be(null);try{const W=await so(t,{urls:j}),{succeeded:de,failed:ke,total:rt}=W.summary;De({title:"Indexing requested",detail:ke===0?`${de} URL${de!==1?"s":""} submitted for indexing.`:`${de}/${rt} submitted successfully, ${ke} failed.`,tone:ke===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(W){Be(W instanceof Error?W.message:"Failed to request indexing")}finally{qt(!1)}}async function ta(){qt(!0),Be(null);try{const j=await so(t,{urls:[],allUnindexed:!0}),{succeeded:W,failed:de,total:ke}=j.summary;De({title:"Indexing requested",detail:de===0?`${W} unindexed URL${W!==1?"s":""} submitted for indexing.`:`${W}/${ke} submitted successfully, ${de} failed.`,tone:de===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(j){Be(j instanceof Error?j.message:"Failed to request indexing")}finally{qt(!1)}}async function dn(){ct(!0),Be(null);try{const j=await Nr(t);n.setQueryData(qd({client:Y,path:{name:t}}),j),pt(j.sitemaps),It(j.summary),R(j.preferredSubmissionUrls),Pe(new Set),dt({}),j.sitemaps.length===0&&ss("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(j){Be(j instanceof Error?j.message:"Failed to list sitemaps")}finally{ct(!1)}}async function sa(j){const W=Le.has(j);if(Pe(de=>{const ke=new Set(de);return W?ke.delete(j):ke.add(j),ke}),!(W||Ke[j])){yt(de=>new Set(de).add(j));try{const de=await Nr(t,j);dt(ke=>({...ke,[j]:de.sitemaps}))}catch(de){Be(de instanceof Error?de.message:"Failed to load sitemap files")}finally{yt(de=>{const ke=new Set(de);return ke.delete(j),ke})}}}async function js(j){if(!Es||j.length===0)return;const W=[...new Set(j)];es(!0),Be(null),ve({completed:0,total:W.length});let de=0,ke=0,rt=0,nt=null;try{for(let Rt=0;Rt<W.length;Rt+=50){const Xe=W.slice(Rt,Rt+50);try{const Te=await Ed(t,Xe);de+=Te.summary.accepted,ke+=Te.summary.failed,rt+=Xe.length,ve({completed:rt,total:W.length})}catch(Te){rt+=Xe.length;const Ns=Xe.length,mn=W.length-rt,Tn=Te instanceof Error?Te.message:"The batch request failed",ws=`${de} accepted, ${ke} failed, ${Ns} unconfirmed, ${mn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;nt=`Sitemap submission stopped after a batch request failed. ${ws} ${Tn}`,Be(nt),De({title:"Sitemap resubmission partially completed",detail:ws,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const ht=W.length;De({title:ke===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ke===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${de}/${ht} sitemap submissions; ${ke} failed. Indexing is not guaranteed.`,tone:ke===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Xt("")}catch(ht){Be(ht instanceof Error?ht.message:"Failed to submit sitemap to Google")}finally{es(!1),ve(null),await dn(),nt&&Be(nt)}}async function Ia(){es(!0);const j=at??[];try{const W=j.filter(ke=>ke.isSitemapsIndex),de=[];for(let ke=0;ke<W.length;ke+=4)(await Promise.all(W.slice(ke,ke+4).map(async nt=>{const ht=Ke[nt.path];if(ht)return ht;const Rt=await Nr(t,nt.path);return dt(Xe=>({...Xe,[nt.path]:Rt.sitemaps})),Rt.sitemaps}))).forEach((nt,ht)=>{de.push(...nt.length>0?nt.map(Rt=>Rt.path):[W[ke+ht].path])});await js([...j.filter(ke=>!ke.isSitemapsIndex).map(ke=>ke.path),...de])}catch(W){Be(W instanceof Error?W.message:"Failed to load sitemap files"),es(!1)}}async function Ta(j){Ot(!0),Be(null);try{await Dd(t,"gsc",j),await $t(n,"google"),d(W=>W.map(de=>de.connectionType==="gsc"?{...de,sitemapUrl:j}:de)),De({title:"Default sitemap updated",detail:j,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(W){Be(W instanceof Error?W.message:"Failed to set the default sitemap")}finally{Ot(!1)}}async function Ma(j){try{await rn.mutateAsync({projectName:t,projectLabel:t,opts:j?{sitemapUrl:j}:void 0})}catch{}}async function yr(){Ae(!0),Be(null);try{const[j,W]=await Promise.all([r||!a?Promise.resolve(null):Gl().catch(()=>null),n.fetchQuery({...Ai({client:Y,path:{name:t}}),staleTime:Yt}).catch(()=>[])]);i(!!j?.google?.configured),d(W);const de=W.find(ke=>ke.connectionType==="gsc");await Promise.all([r?Promise.resolve():fr(de),An(),on(),Rn(),ln(),!r&&de?.propertyId?dn():Promise.resolve()])}finally{Ae(!1)}}o.useEffect(()=>{yr()},[t,s,a]),o.useEffect(()=>{le(0),$(null),te(j=>j.startDate||j.endDate?{...j,startDate:"",endDate:""}:j),T(j=>j+1),on()},[Q]);const un=o.useRef(!1);o.useEffect(()=>{if(!un.current){un.current=!0;return}le(0),zt.setPage(1),An(0)},[ee]);function Pn(j){const W=Z===j?null:j;$(W),te(de=>({...de,startDate:W??"",endDate:W??""})),T(de=>de+1)}const na=o.useRef(!1);o.useEffect(()=>{if(!na.current){na.current=!0;return}le(0),An(0)},[xt]);async function La(){if(!l){Be("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}fe(!0),Be(null),ss(null);try{let j=function(Te){if(Te.source!==ke||Te.origin!==rt||!Te.data||typeof Te.data!="object")return;const Ns=Te.data;Ns.type!==Mx||Ns.connectionType!=="gsc"||Xe(!0)};const{authUrl:W,redirectUri:de}=await Md(t,"gsc");if(!W.startsWith("https://accounts.google.com/")){Be("Unexpected OAuth redirect URL. Please try again.");return}const ke=window.open(W,"_blank","width=600,height=700");if(!ke){window.location.assign(W);return}const rt=de?new URL(de).origin:window.location.origin;let nt=!1,ht=null;const Rt=()=>{ht!==null&&window.clearInterval(ht),window.removeEventListener("message",j)},Xe=async Te=>{if(!nt){nt=!0,Rt(),ss(Te?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await $t(n,"google"),await yr()}finally{ss(null)}}};window.addEventListener("message",j),ss("Finish the Google consent flow in the popup. This page will refresh automatically."),ht=window.setInterval(()=>{ke.closed&&Xe(!1)},1e3)}catch(j){Be(j instanceof Error?j.message:"Failed to start OAuth flow")}finally{fe(!1)}}async function In(){Be(null),ss(null);try{await Td(t,"gsc"),await $t(n,"google"),d(j=>j.filter(W=>W.connectionType!=="gsc")),u([]),v("")}catch(j){Be(j instanceof Error?j.message:"Failed to disconnect")}}async function $a(){if(g){O(!0),Be(null);try{await _d(t,"gsc",g),await $t(n,"google"),d(j=>j.map(W=>W.connectionType==="gsc"?{...W,propertyId:g}:W)),De({title:"GSC property updated",detail:`${t} is now linked to ${g}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(j){Be(j instanceof Error?j.message:"Failed to save GSC property")}finally{O(!1)}}}async function br(){Be(null),ss(null);try{await ea.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(A,10)||void 0,full:V||void 0}}),await $t(n,"gsc")}catch{}}async function qa(){if(C.trim()){tt(!0),Be(null),ss(null);try{const j=await Od(t,C.trim());await $t(n,"gsc"),S(j),I(""),await Rn()}catch(j){Be(j instanceof Error?j.message:"Failed to inspect URL")}finally{tt(!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}),(Mn(wt.enableUrl)||Mn(wt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Mn(wt.enableUrl)&&e.jsx("a",{href:Mn(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 ↗"}),Mn(wt.indexingApiUrl)&&e.jsx("a",{href:Mn(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:()=>qs(null),children:"×"})]})}),Ft&&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:[Ft,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Be(null),children:"×"})]}),Xn&&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:[Xn,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>ss(null),children:"×"})]}),qe?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Gt?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-neutral",children:"Authorized"})]}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsx("code",{className:"text-secondary",children:Gt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",ge?.lastInspectedAt?Jt(ge.lastInspectedAt):"never"]}),!r&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ze(In),children:"Disconnect"})]}):a?e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(Ne,{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(P,{type:"button",variant:"outline",size:"sm",disabled:ie,onClick:Ze(La),children:ie?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ms,{to:"/settings",children:"Open Settings"})}),!l&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}):e.jsx(je,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:Ix})}),(Gt||Zn)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Oe,{text:`${$x(h?.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 ${Ka.toLocaleString()} matching rows while the table shows ${Os} per page.`})]}),h?.window?.startDate&&h.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[h.window.startDate," to ",h.window.endDate,(h.window.daysSinceLatestData??0)>0&&` · latest data ${h.window.daysSinceLatestData} day${h.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gr,{windows:Tx,value:Q,onChange:j=>{B(j),le(0),zt.setPage(1)},label:"Search Console time period",formatOption:j=>j==="all"?"All":j}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:D,onClick:()=>{le(0),zt.setPage(1),An(0),on()},children:D?"Loading…":"Apply filters"})]})]}),h&&h.daily.length>0&&(()=>{const{totals:j,daily:W,trends:de,periodComparison:ke}=h,nt=Do.filter(Te=>z.includes(Te.key)).map(Te=>({dataKey:Te.key,label:Te.label,color:Te.color,axisId:Te.key,inverted:Te.inverted,formatValue:Te.format,trend:F?de?.[Te.key]??null:null})),ht=Te=>j[Te]??null,Rt=new Map(W.map(Te=>[Te.date,Te])),Xe=W.length===0?[]:Ad(W[0].date,W[W.length-1].date).map(Te=>Rt.get(Te)??{date:Te});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Do.map(Te=>{const Ns=z.includes(Te.key),mn=ht(Te.key),Tn=mn===null;return e.jsxs("button",{type:"button","aria-pressed":Ns,disabled:Tn,className:`rounded-md border px-3 py-2 text-left transition-colors ${Ns?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Tn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{ne(ws=>ws.includes(Te.key)?ws.length===1?ws:ws.filter(vr=>vr!==Te.key):[...ws,Te.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:Ns?Te.color:"transparent",border:`1px solid ${Te.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:Te.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:mn===null?"—":Te.format(mn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Lx(ke,Te.key,Te.inverted)})]},Te.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:F,onChange:Te=>_(Te.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(oc,{data:Xe,xKey:"date",series:nt,xTickFormatter:Sn,labelFormatter:Pt,onSelectX:Pn,selectedX:Z})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:W.map(Te=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":Z===Te.date,onClick:()=>Pn(Te.date),children:[Pt(Te.date),": ",Te.clicks," clicks, ",Te.impressions," impressions"]},Te.date))}),Z&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Pt(Z)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Pn(Z),children:["Show all ",j.days," days"]})]}),j.position!==null&&(j.positionDays??j.days)<j.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",j.positionDays," of ",j.days," days. The rest have no property-level position recorded."]}),(j.position===null||j.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:E.startDate,onChange:j=>te(W=>({...W,startDate:j.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:E.endDate,onChange:j=>te(W=>({...W,endDate:j.target.value}))}),e.jsx(Js,{value:E.query,onChange:j=>te(W=>({...W,query:j})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Js,{value:E.page,onChange:j=>te(W=>({...W,page:j})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),p.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(jn).map(j=>e.jsx("th",{className:"text-right","aria-sort":Mt?.key===j?Mt.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:()=>{zt.setPage(1),as(W=>W?.key===j?W.dir==="desc"?{key:j,dir:"asc"}:null:{key:j,dir:"desc"})},children:[Rd[j],Mt?.key===j?Mt.dir==="desc"?" ↓":" ↑":""]})},j))]})}),e.jsx("tbody",{children:fs.map((j,W)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:j.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:j.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(ar,{value:j.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:j.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.impressions.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:et(j.ctr)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.position.toFixed(1)})]},`${j.date}:${j.query}:${j.page}:${W}`))})]})}),e.jsx(Ks,{page:J?zt.page:Math.floor(re/Os)+1,pageSize:Os,visibleRows:fs.length,totalRows:J?ue:void 0,hasNextPage:J?void 0:we,disabled:D,itemLabel:J?"matches":"rows",onPageChange:j=>{if(J){zt.setPage(j);return}const W=(j-1)*Os;le(W),An(W)}}),J&&ue>=Ka?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Ka.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Oe,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ge&&ge.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:st,onClick:()=>{ta()},children:st?"Requesting…":`Request indexing (${ge.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Ve,onClick:()=>{ln(!0)},children:Ve?"Loading…":"Reload saved coverage"})]})]}),ge&&ge.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const j=ge.summary.indexedShare??0,W=ge.summary.notIndexedShare??0,de=54,ke=2*Math.PI*de,rt=ke*(1-j),nt=ke*W,ht=ke*j;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:ms.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:Jn.positiveDeep,strokeWidth:"14",strokeDasharray:ke,strokeDashoffset:rt,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),ge.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:ms.textFaint,strokeWidth:"14",strokeDasharray:`${nt} ${ke-nt}`,strokeDashoffset:-ht,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-3xl font-bold tabular-nums text-primary",children:et(ge.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:ge.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:ge.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(ge.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(ge.reasonGroups??[]).length," ",(ge.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),ge.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:ge.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(j=>{const W=j==="indexed"?ge.indexed.length:j==="notIndexed"?ge.notIndexed.length:ge.deindexed.length,de=j==="indexed"?"Indexed":j==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":bt===j,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${bt===j?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{Vs(j),ys(null)},children:[de," (",W,")"]},j)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[bt==="indexed"&&ge.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:kt.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.crawlTime?j.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:j.isMobileFriendly===!0?"Yes":j.isMobileFriendly===!1?"No":"—"})]},j.id))})]}),bt==="notIndexed"&&!Nt&&(ge.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:(ge.reasonGroups??[]).map(j=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>ys(j.reason),onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),ys(j.reason))},tabIndex:0,role:"button","aria-label":`View ${j.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:j.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.count})]},j.reason))})]}),bt==="notIndexed"&&!Nt&&(ge.reasonGroups??[]).length===0&&ge.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:vs.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.coverageState??"Unknown"})]},j.id))})]}),bt==="notIndexed"&&Nt&&(()=>{const j=(ge.reasonGroups??[]).find(W=>W.reason===Nt);return j?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>ys(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:j.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[j.count," affected page",j.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:st,onClick:()=>{cn(j.urls.map(W=>W.url))},children:st?"Requesting…":`Request indexing (${j.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Se.map(W=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:W.url}),e.jsx("td",{className:"text-secondary",children:W.crawlTime?W.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:st,onClick:()=>{cn([W.url])},title:"Request indexing",children:"Index"})})]},W.id))})]})]}):null})(),bt==="deindexed"&&ge.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:q.map((j,W)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.previousState}),e.jsx("td",{className:"text-secondary",children:j.currentState}),e.jsx("td",{className:"text-secondary",children:j.transitionDate.split("T")[0]})]},`${j.url}-${W}`))})]}),(bt==="indexed"&&ge.indexed.length===0||bt==="notIndexed"&&!Nt&&ge.notIndexed.length===0||bt==="deindexed"&&ge.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ks,{page:Ue,pageSize:zs,visibleRows:Math.min(zs,ce.length-mt),totalRows:ce.length,onPageChange:U,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":ps,onClick:()=>Bs(j=>!j),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:ps?"Hide snapshots":gt.length>0?`View ${gt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",ge.summary.indexed.toLocaleString()," indexed, ",ge.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."]})]}),ps&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:gt.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:gt.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:j.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:j.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.notIndexed.toLocaleString()})]},j.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:Ve?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),!r&&e.jsxs(e.Fragment,{children:[e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Oe,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Dt||!Gt?.propertyId,onClick:()=>{dn()},children:Dt?"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:Tt,onChange:j=>Xt(j.target.value),onKeyDown:j=>j.key==="Enter"&&void js([Tt.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!Es||ut||!Tt.trim(),onClick:()=>{js([Tt.trim()])},children:ut?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!Es||ut||Ds.length===0,onClick:()=>{js(Ds)},children:ut?"Resubmitting…":Pa}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!Es||ut||!at?.length,onClick:()=>{Ia()},children:"Resubmit all files"}),Ct&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ct.indexes," index",Ct.indexes===1?"":"es",", ",Ct.files," file",Ct.files===1?"":"s"]}),Re&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Re.completed,"/",Re.total]})]}),!Es&&Gt&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:Ze(La),children:"Reconnect"})]}),at&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:at.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Js,{value:se,onChange:j=>{_e(j),Qt.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:Qt.rows.flatMap(j=>{const W=Oo(j),de=Fo(j),ke=Go(j),rt=Ke[j.path]??[],nt=Le.has(j.path),ht=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(ar,{value:j.path})}),e.jsx("td",{className:"text-secondary",children:j.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":nt,"aria-label":`${nt?"Collapse":"Expand"} files in ${j.path}`,onClick:()=>{sa(j.path)},children:ze.has(j.path)?"Loading…":`${nt?"▾":"▸"} Index${Ke[j.path]?` (${rt.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ke}),e.jsx("td",{className:"text-secondary",children:j.lastSubmitted?j.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:j.lastDownloaded?j.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:W.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:!Es||ut,onClick:()=>{js([j.path])},children:j.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Gt?.sitemapUrl===j.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Zt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Ta(j.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:rn.isPending,onClick:()=>{Ma(j.path)},children:"Inspect URLs"})]})})]},j.path),Rt=j.isSitemapsIndex&&nt?rt.map(Xe=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(ar,{value:Xe.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Go(Xe)}),e.jsx("td",{className:"text-secondary",children:Xe.lastSubmitted?Xe.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:Xe.lastDownloaded?Xe.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Oo(Xe).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Fo(Xe)||"—"}),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:!Es||ut,onClick:()=>{js([Xe.path])},children:"Resubmit"}),Gt?.sitemapUrl===Xe.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:Zt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Ta(Xe.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:rn.isPending,onClick:()=>{Ma(Xe.path)},children:"Inspect URLs"})]})})]},`${j.path}:${Xe.path}`)):[];return[ht,...Rt]})})]}),e.jsx(Ks,{page:Qt.page,pageSize:Os,visibleRows:Qt.rows.length,totalRows:Qt.totalRows,onPageChange:Qt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:C,onChange:j=>I(j.target.value),onKeyDown:j=>j.key==="Enter"&&void qa()}),e.jsx(P,{type:"button",size:"sm",disabled:Fe||!Gt?.propertyId||!C.trim(),onClick:Ze(qa),children:Fe?"Inspecting…":"Inspect URL"})]}),L&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:L.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:L.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:to(L.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Jt(L.crawlTime)})]})]})]})]}),e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Me,onClick:()=>{Rn(!0)},children:Me?"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:K,onChange:j=>pe(j.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Me,onClick:()=>{Rn(!0)},children:"Apply filter"})]}),f.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:f.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-neutral",children:j.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:to(j.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Jt(j.inspectedAt)})]},j.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),N.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:N.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:j.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Jt(j.transitionDate)})]},`${j.url}:${j.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Gt&&!r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>gs(j=>!j),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${it?"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"})]})}),it&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Oe,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:g,disabled:Ce||m.length===0,onChange:j=>v(j.target.value),children:m.length===0?e.jsx("option",{value:"",children:Ce?"Loading properties…":"No properties available"}):m.map(j=>e.jsxs("option",{value:j.siteUrl,children:[j.siteUrl," · ",j.permissionLevel]},j.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Ce,onClick:()=>{fr(Gt,!0)},children:Ce?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!g||Ee,onClick:Ze($a),children:Ee?"Saving…":"Save property"})]})]})]}),e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:A,onChange:j=>w(j.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:V,onChange:j=>G(j.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:ea.isPending||!Gt.propertyId,onClick:Ze(br),children:ea.isPending?"Queueing…":"Queue sync"}),!Gt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Ex=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Dx({projectName:t,projectId:s}){const n=hs(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),m=$e(Ai({client:Y,path:{name:t}})),u=m.data?.find(X=>X.connectionType==="gbp"),p=!!u,x=a?{locationName:a}:void 0,h=$e({...Ud({client:Y,path:{name:t}}),enabled:p}),y=$e({...Bd({client:Y,path:{name:t},query:x}),enabled:p}),f=$e({...Vd({client:Y,path:{name:t},query:x}),enabled:p}),b=$e({...zd({client:Y,path:{name:t},query:x}),enabled:p}),N=$e({...Qd({client:Y,path:{name:t},query:x}),enabled:p}),k=$e({...Hd({client:Y,path:{name:t},query:x}),enabled:p}),L=$e({queryKey:["gbp-section-insights",t],queryFn:()=>Wd(t),enabled:p});function S(){$t(n,"gbp")}const g=Et({...Yd(),onSuccess:X=>{Kl({id:X.runId,projectId:s,kind:Us["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),De({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=o.useSyncExternalStore(_l,ir,ir),C=Object.values(v.runs).some(X=>X.kind===Us["gbp-sync"]&&X.projectId===s),I=g.isPending||C,A=Et({...Jd(),onSuccess:()=>S()});if(o.useEffect(()=>{if(!a||!h.data)return;const X=h.data.locations.filter(ue=>ue.selected);(X.length<=1||!X.some(ue=>ue.locationName===a))&&r(null)},[a,h.data]),o.useEffect(()=>{if(!l||!h.data)return;(a?[a]:h.data.locations.filter(ue=>ue.selected).map(ue=>ue.locationName)).includes(l)||i(null)},[l,h.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(je,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:X.map((ue,xe)=>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:xe+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ue.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-bg-elevated/80 px-2 py-1 font-mono text-xs text-neutral",children:ue.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ue.note})]})]},ue.title))})]})})}const w=y.data,V=h.data?.locations??[],G=V.filter(X=>X.selected),Q=f.data?.keywords??[],B=b.data?.lodging??[],z=N.data?.placeActions??[],ne=k.data?.places??[],F=V.length>0?V[0].accountName:u.domain,_=a?V.find(X=>X.locationName===a)?.displayName??null:null,Z=a?V.filter(X=>X.locationName===a):G,$=new Set(Z.map(X=>X.locationName)),ee=B.filter(X=>$.has(X.locationName)),T=z.filter(X=>$.has(X.locationName)),E=ne.filter(X=>$.has(X.locationName)),te=new Set(G.map(X=>X.locationName)),re=a?Q:Q.filter(X=>te.has(X.locationName)),le=!a&&G.length>1,we=(L.data??[]).filter(X=>!X.dismissed&&Ex.has(X.type)&&(!_||X.query===_||X.query===a||X.title.startsWith(_)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Oe,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{tone:"positive",children:"Connected"}),!oe()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:I,onClick:()=>g.mutate({client:Y,path:{name:t},body:{}}),children:I?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[F?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:F})," · "]}):null,h.data?`${h.data.totalSelected} of ${h.data.totalDiscovered} locations tracked`:"Loading locations…"]}),G.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"}),G.map(X=>e.jsx("option",{value:X.locationName,children:X.displayName},X.id))]})]}),G.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:[we.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),we.map(X=>e.jsx("div",{className:["insight-card",Yx(X.severity),"rounded-r-lg border border-default bg-surface p-3 pl-4"].filter(Boolean).join(" "),children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-strong",children:[X.title,X.recommendation?.reason&&e.jsx(Oe,{text:X.recommendation.reason})]})},X.id))]}),w&&e.jsx(eg,{performance:w.performance,freshness:w.freshness,timeseries:w.timeseries}),w?.profileCompleteness&&e.jsx(Ox,{summary:w.profileCompleteness}),Z.length>0&&e.jsx(Fx,{locations:Z,lodging:ee,places:E,placeActions:T,expandedLocation:l,onToggleExpanded:X=>{i(ue=>ue===X?null:X)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),f.data&&f.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[et(f.data.thresholdedPct,Yn.percent)," privacy-thresholded"]})]}),re.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"}),le&&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:re.slice(0,25).map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:X.keyword}),le&&e.jsx("td",{className:"text-muted",children:V.find(ue=>ue.locationName===X.locationName)?.displayName??X.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:X.valueCount!==null?X.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",X.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[X.periodStart,"–",X.periodEnd]})]},`${X.locationName}:${X.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>d(X=>!X),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",V.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:V.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!oe()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:V.map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:X.displayName}),e.jsx("td",{className:"text-muted",children:X.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(Ne,{tone:X.selected?"positive":"neutral",children:X.selected?"Tracked":"Not tracked"})}),!oe()&&e.jsx("td",{className:"text-right",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:A.isPending,onClick:()=>A.mutate({client:Y,path:{name:t,locationName:X.locationName},body:{selected:!X.selected}}),children:X.selected?"Untrack":"Track"})})]},X.id))})]})})]})]})})}function Ox({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:ra(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:ra(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:ra(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:ra(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:ra(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-default py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(Oe,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${Wx(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Fx({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:l}){const i=new Map(s.map(m=>[m.locationName,m])),c=new Map(n.map(m=>[m.locationName,m])),d=new Map;for(const m of a){const u=d.get(m.locationName)??[];u.push(m),d.set(m.locationName,u)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Oe,{text:oe()?"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,p=c.get(m.locationName)??null,x=d.get(m.locationName)??[],h=r===m.locationName;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:m.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:m.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(Ne,{tone:m.selected?"positive":"neutral",children:m.selected?"Tracked":"Not tracked"}),m.openStatus&&m.openStatus!=="OPEN"&&e.jsx(Ne,{tone:m.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Ic(m.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Kx,{location:m})}),e.jsx("td",{children:e.jsx(_x,{lodging:u})}),e.jsx("td",{children:e.jsx(Bx,{place:p,mapsUri:m.mapsUri})}),e.jsx("td",{children:e.jsx(zx,{actions:x})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>l(m.locationName),children:h?"Hide":"Details"})})]}),h&&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(Hx,{location:m,lodging:u,place:p,placeActions:x})})})]},m.id)})})]})})]})}function Gx(t){return[{label:"Description",tone:bn(t.description)?"positive":"neutral",value:bn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:bn(t.primaryPhone)?"positive":"neutral",value:bn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:bn(t.websiteUri)?"positive":"neutral",value:bn(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 Kx({location:t}){const s=Gx(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(Ne,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function _x({lodging:t}){return e.jsx(Li,{...Ux(t)})}function Ux(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 Bx({place:t,mapsUri:s}){return e.jsx(Li,{...Vx(t,s)})}function Vx(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 zx({actions:t}){return e.jsx(Li,{...Qx(t)})}function Qx(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 Li({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(Ne,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Hx({location:t,lodging:s,place:n,placeActions:a}){const r=s?Xx(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(qr,{title:"Owner profile · Business Information",children:[e.jsx(Ht,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Ht,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Ht,{label:"Description",value:bn(t.description)?t.description:"Not returned"}),e.jsx(Ht,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Ht,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Ht,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Ht,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Ht,{label:"Open status",value:Ic(t.openStatus)}),e.jsx(Ht,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(qr,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{label:"Last checked",value:Ko(s.syncedAt)}),e.jsx(Ht,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Ht,{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(qr,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{label:"Places tier",value:n.tier}),e.jsx(Ht,{label:"Last checked",value:Ko(n.syncedAt)}),e.jsx(Ht,{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:[ur(l.placeActionType),l.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[ur(l.providerType),l.uri?` · ${Jx(l.uri)}`:""]})]},l.placeActionLinkName))})})]})]})}function qr({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 Ht({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 ra(t,s,n){return t===s?"positive":t===0?n:"caution"}function Wx(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Yx(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function bn(t){return typeof t=="string"&&t.trim().length>0}function Ic(t){return t?ur(t):"Not returned"}function ur(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Jx(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Ko(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Xx(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Zx(n)).map(([s])=>ur(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Zx(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function eg({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Xd.filter(y=>(a[y]??0)>0),l=Zd.filter(y=>(a[y]??0)>0),i=Object.keys(a).filter(y=>(a[y]??0)>0&&eu(y)==="other").sort((y,f)=>(a[f]??0)-(a[y]??0)),c=Object.keys(a).filter(y=>(a[y]??0)===0).sort(),d=n.map(y=>{const f={date:y.date};for(const[b,N]of Object.entries(y.metrics))f[b]=N;return f}),m=n.find(y=>y.pending)?.date,u=n.length>0?n[n.length-1].date:void 0,p=d.length>0,x=s.dataThroughDate?`Data through ${Pt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,h=[...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"}),x&&e.jsx("span",{className:"text-[11px] text-muted",children:x})]}),!p||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(_o,{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:h.map(y=>e.jsxs("span",{className:"text-sm text-secondary",children:[or(y)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[y]??0).toLocaleString()})]},y))})]})]}),p&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(_o,{data:d,metrics:l,kind:"area",firstPending:m,lastDate:u})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(y=>or(y)).join(", ")]})]})}function _o({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(va,{stroke:ya,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:us},tickFormatter:Sn,minTickGap:24}),e.jsx(tn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ns,labelFormatter:Pt,formatter:(l,i)=>[typeof l=="number"?l.toLocaleString():String(l??0),or(String(i??""))]}),e.jsx(cr,{wrapperStyle:{fontSize:11,color:ms.text},formatter:l=>or(l)}),a&&r&&e.jsx(ni,{x1:a,x2:r,fill:ms.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:ms.textDim,fontSize:10}}),s.map((l,i)=>n==="line"?e.jsx(Gs,{type:"monotone",dataKey:l,stroke:lt[i%lt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx(Ws,{type:"monotone",dataKey:l,stackId:"reach",stroke:lt[i%lt.length],fill:lt[i%lt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},l))]})})})}function tg(t){return Fh(Bt(String(t)))}function sg(t){return Sa(Bt(String(t)))}function Er({children:t,label:s="More info",placement:n="top",className:a}){const r=o.useId(),[l,i]=o.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":l?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:e.jsx(Wh,{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 _a=Os;function Ln(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Dr(t){return t.toLocaleString()}function ng(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 ag(t){const s=t.filter(n=>n.kind===Us["backlink-extract"]&&!Ul(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function rg(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 ig({projectName:t}){const s=Ls(),[n,a]=o.useState(null),[r,l]=o.useState(null),[i,c]=o.useState([]),[d,m]=o.useState(null),[u,p]=o.useState(null),[x,h]=o.useState(null),[y,f]=o.useState(Date.now()),[b,N]=o.useState(0),[k,L]=o.useState(!0),[S,g]=o.useState(!1),[v,C]=o.useState(null),I=o.useCallback(async()=>{L(!0),C(null);try{const[_,Z,$,ee,T]=await Promise.all([tu().catch(()=>null),su(t,{excludeCrawlers:!0}).catch(()=>null),nu(t,{limit:_a,offset:b,excludeCrawlers:!0}).catch(te=>{if(te instanceof Vn&&te.code==="NOT_FOUND")return null;throw te}),au(t).catch(()=>[]),ru(t).catch(()=>[])]);m(_),a(Z),l($),c(ee);const E=ag(T);p(E)}catch(_){C(_ instanceof Error?_.message:"Failed to load backlinks")}finally{L(!1)}},[t,b]);o.useEffect(()=>{I()},[I]),o.useEffect(()=>{if(!u)return;const _=u.id;let Z=!1;const $=async()=>{try{const T=await ti(_);if(Z)return;Ul(T.status)?(p(null),h(T),await I()):p(E=>E?.id===T.id?{...E,...T}:E)}catch{}},ee=window.setInterval(()=>{$()},3e3);return()=>{Z=!0,window.clearInterval(ee)}},[u,I]),o.useEffect(()=>{if(!u)return;const _=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(_)},[u]),o.useEffect(()=>{if(!x||x.status==="failed")return;const _=window.setTimeout(()=>h(null),1e4);return()=>window.clearTimeout(_)},[x]);async function A(){g(!0),C(null);try{const _=await ou(t);p(_)}catch(_){_ instanceof Vn&&_.code==="MISSING_DEPENDENCY"?C("DuckDB is not installed. Visit the Backlinks admin page to install it."):C(_ instanceof Error?_.message:"Failed to trigger extract")}finally{g(!1)}}const w=o.useMemo(()=>i.slice().sort((_,Z)=>_.queriedAt.localeCompare(Z.queriedAt)).map(_=>({date:_.queriedAt,linkingDomains:_.totalLinkingDomains})),[i]),V=r?.rows??[],G=r?.total??0,Q=n?.excludedLinkingDomains??0,B=Math.floor(b/_a)+1;return o.useEffect(()=>{b>0&&b>=G&&N(0)},[b,G]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),v&&e.jsx(je,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:v})}),u&&e.jsx(je,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Vh,{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(Ne,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[rg(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."})]})]})}),x&&!u&&e.jsx(je,{className:`surface-card p-4 mb-4 ${x.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.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(zh,{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 ${x.status==="failed"?"text-negative":"text-positive"}`,children:x.status==="failed"?"Extract failed":"Extract complete"}),x.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:iu(x.error)}):x.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),z()]});function z(){return k?e.jsx(je,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):ne()}function ne(){const _=n!==null&&n.totalLinkingDomains>0,Z=x?.status==="failed",$=n!==null&&n.totalLinkingDomains===0&&!Z,ee=d?.status==="ready",T=d?.status==="failed",E=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return _?F(e.jsxs(e.Fragment,{children:[!oe()&&!s&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:S||u!==null,onClick:Ze(A),children:[e.jsx(Hh,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":S?"Queuing…":"Re-run extract"]}),e.jsx(Er,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!oe()&&!s&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"Open admin"})})]})):e.jsx(je,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Qh,{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."}),!oe()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"Set up backlinks"})})})]}),E&&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."]}),!oe()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"View sync status"})})})]}),T&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:d.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!oe()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"Go to Backlinks admin"})})})]}),ee&&!E&&!$&&!Z&&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."]}),!oe()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(P,{type:"button",size:"sm",disabled:S||u!==null,onClick:Ze(A),children:[e.jsx(lr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":S?"Queuing…":"Run extract"]}),e.jsx(Er,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),Z&&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."}),!oe()&&!s&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"Go to Backlinks admin"})})})]}),$&&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."]}),!oe()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:S||u!==null,onClick:Ze(A),children:[e.jsx(lr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":S?"Queuing…":"Re-run extract"]}),e.jsxs(Er,{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 F(_){if(!n)return null;const Z="Linking hosts",$="linking hosts",ee="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:Dr(n.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",n.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",$]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Dr(n.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",$," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:et(Number(n.top10HostsShare))})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",$," 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"})," · ",ee," ",e.jsx("code",{className:"text-secondary",children:n.release})," · queried ",ng(n.queriedAt),Q>0&&e.jsxs(e.Fragment,{children:[" · ",Q," excluded domain",Q===1?"":"s"]})]}),w.length>=2&&e.jsxs(je,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:w,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:lt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:lt[0],stopOpacity:0})]})}),e.jsx(en,{dataKey:"date",tick:Ut,stroke:us,tickFormatter:tg}),e.jsx(tn,{tick:Ut,stroke:us,allowDecimals:!1}),e.jsx(sn,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:sg}),e.jsx(Ws,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:lt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(je,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:Z})]})}),e.jsxs("tbody",{children:[V.map(T=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:T.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Dr(T.numHosts)})]},T.linkingDomain)),V.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:Q>0&&G===0?`Every referring domain in this ${ee} was a crawler/proxy host (${Q} hidden).`:`No referring domains in this ${ee}.`})})]})]})}),e.jsx(Ks,{page:B,pageSize:_a,visibleRows:V.length,totalRows:G,onPageChange:T=>N((T-1)*_a)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:_})]})}}const og=["non-brand","branded","unclassified"],Uo={"non-brand":"Non-brand",branded:"Branded",unclassified:"Unclassified"};function lg(t,s){return s<=0?"neutral":t/s*100>=70?"positive":"caution"}function cg(t,s){const n=[...new Set(t.byQuery.flatMap(i=>i.providers.map(c=>c.provider)))].sort(),a=new Map,r=i=>{const c=s(i)??"unclassified";let d=a.get(c);return d||(d={key:c,queries:0,unanswered:0,engines:n.map(m=>({provider:m,answered:0,mentioned:0,cited:0})),answers:0,competitorCited:0,competitorGaps:[],citedAndNamed:0,citedNotNamed:0,namedNotCited:0,neither:0},a.set(c,d)),d},l=new Map;for(const i of t.byQuery){const c=r(i.query);if(i.providers.length===0){c.unanswered++;continue}c.queries++;for(const u of i.providers){l.set(`${i.queryId}::${u.provider}`,i.query);const p=c.engines.find(x=>x.provider===u.provider);p.answered++,u.mentioned&&p.mentioned++,u.cited&&p.cited++,c.answers++}const d=i.providers.some(u=>u.cited),m=i.providers.some(u=>u.mentioned);d&&m?c.citedAndNamed++:d?c.citedNotNamed++:m?c.namedNotCited++:c.neither++}for(const i of t.competitorGaps){const c=l.get(`${i.queryId}::${i.provider}`);if(c===void 0)continue;const d=r(c);d.competitorCited++,d.competitorGaps.push({query:c,provider:i.provider,competitors:i.citingCompetitors})}return og.map(i=>a.get(i)).filter(i=>i!==void 0&&i.queries>0)}function dg(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 ug={engine:"engine no longer configured",query:"query no longer tracked"},Bo={"non-brand":"non-brand queries",branded:"branded queries",unclassified:"unclassified queries"},mg="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 $n(t,s,n){return t===1?s:n}function hg({projectName:t,classify:s,hasCompetitors:n,providerScores:a=[]}){const r=o.useId(),[l,i]=o.useState("non-brand"),c=$e({...lu({client:Y,path:{name:t}}),staleTime:Ri}),d=c.data??null,m=d?.status==="ready"?cg(d,s):[],u=m.find(f=>f.key===l)??m.at(0);let p;c.isError?p=e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Could not load engine results: ",St(c.error)]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{c.refetch()},children:"Retry"})]}):d?d.status==="no-data"?p=e.jsx("p",{className:"text-sm text-secondary",children:d.reason==="no-queries"?"Add queries to start tracking AI citations.":ds()?zn:"Engine results appear after the first AI Visibility sweep."}):u||(p=e.jsx("p",{className:"text-sm text-secondary",children:"No engine answers yet."})):p=e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine results…"});const x=[];if(u&&d?.status==="ready"){const f=$n(u.queries,"query","queries");x.push(e.jsxs(e.Fragment,{children:["Cited and named: ",e.jsxs("strong",{children:[u.citedAndNamed," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Cited but not named: ",e.jsxs("strong",{children:[u.citedNotNamed," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Named but not cited: ",e.jsxs("strong",{children:[u.namedNotCited," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Not cited or named: ",e.jsxs("strong",{children:[u.neither," of ",u.queries]})," ",f]}));for(const L of u.engines)L.answered<u.queries&&x.push(e.jsxs(e.Fragment,{children:[ot(L.provider),": answered ",e.jsxs("strong",{children:[L.answered," of ",u.queries]})," ",f]}));u.unanswered>0&&x.push(e.jsxs(e.Fragment,{children:["No answers yet: ",e.jsx("strong",{children:u.unanswered})," ",$n(u.unanswered,"query","queries")]}));const{providersCiting:b,providersMentioning:N,providersConfigured:k}=d.summary;x.push(e.jsxs(e.Fragment,{children:["All queries: cited by ",e.jsxs("strong",{children:[b," of ",k]})," ",$n(k,"engine","engines"),", named by ",e.jsxs("strong",{children:[N," of ",k]})]}));for(const L of a)x.push(e.jsxs(e.Fragment,{children:[ot(L.provider),L.model?` (${L.model})`:""," citation rate:"," ",e.jsx("strong",{children:et(L.score,Yn.percent)}),", ",e.jsxs("strong",{children:[L.cited," of ",L.total]})," ",$n(L.total,"answer","answers"),", all queries"]}));for(const L of u.competitorGaps)x.push(`"${L.query}" (${ot(L.provider)}): ${L.competitors.join(", ")} cited instead of you`);for(const L of dg(d))x.push(`"${L.query}" (${ot(L.provider)}): ${L.competitors.join(", ")} cited instead of you, not counted (${ug[L.reason]})`)}const h=d?.status==="ready"?d.summary.latestRunAt:null,y=(f,b)=>u?.key==="non-brand"?ga[lg(f,b)]:"text-primary";return e.jsxs("section",{className:"overview-brief","aria-labelledby":r,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:r,className:"av-card-title",children:"By engine"}),u&&e.jsx(Oe,{text:mg})]}),h||u?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[h?e.jsxs("p",{className:"av-card-meta",children:["Latest run ",xr(h)]}):null,m.length>1?e.jsx(pa,{label:"Query type",className:"flex-wrap",options:m.map(f=>({value:f.key,label:Uo[f.key]})),value:u.key,onChange:i}):u?e.jsx("span",{className:"mention-share-class",children:Uo[u.key]}):null]}):null]}),e.jsx("div",{className:"av-card-body",children:p??(u&&e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":`By engine, ${Bo[u.key]}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsxs("th",{scope:"col",children:["Of ",u.queries," ",$n(u.queries,"query","queries")]}),u.engines.map(f=>e.jsx("th",{scope:"col",children:ot(f.provider)},f.provider))]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Mentioned"}),u.engines.map(f=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(f.mentioned,f.answered)}`,children:f.mentioned})},f.provider))]}),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Cited"}),u.engines.map(f=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(f.cited,f.answered)}`,children:f.cited})},f.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," ",$n(u.answers,"answer","answers")]}),e.jsxs("span",{className:"sr-only",children:[" · ",Bo[u.key]]})]}):e.jsx("span",{className:"text-[13px] text-secondary",children:"No competitors tracked"})]})]}))}),e.jsx(Ca,{items:x})]})}const pg={[Ts.queued]:{word:"queued",tone:"text-secondary"},[Ts.running]:{word:"running",tone:"text-info-300"},[Ts.completed]:{word:"completed",tone:"text-secondary"},[Ts.partial]:{word:"partial",tone:"text-caution-400"},[Ts.failed]:{word:"failed",tone:"text-negative-400"},[Ts.cancelled]:{word:"cancelled",tone:"text-secondary"}};function xg({runs:t,collapsed:s=!1}){const n=o.useId(),{openRun:a}=Ci(),r=new Set(t.map(c=>c.location??"")).size>1,l=t.some(c=>c.kind!==Us["answer-visibility"]),i=t.map(c=>`${c.startedAt}: ${c.summary}.${c.statusDetail?` ${c.statusDetail}`:""}`);return e.jsx("section",{className:"overview-brief","aria-labelledby":n,children:e.jsxs("details",{className:"av-history",open:!s||void 0,children:[e.jsxs("summary",{className:"av-card-head",children:[e.jsx("h2",{id:n,className:"av-card-title",children:"Past sweeps"}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t.length>0?e.jsxs("span",{className:"av-card-meta",children:[t.length," recent"]}):null,e.jsx(Qn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"av-card-body",children:t.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No sweeps yet."}):e.jsxs("table",{className:"av-grid av-grid-dense av-grid-sweeps","aria-labelledby":n,children:[e.jsx("thead",{className:"sr-only",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Started"}),l?e.jsx("th",{scope:"col",children:"Type"}):null,e.jsx("th",{scope:"col",children:"Trigger"}),r?e.jsx("th",{scope:"col",children:"Location"}):null,e.jsx("th",{scope:"col",children:"Duration"}),e.jsx("th",{scope:"col",children:"Status"})]})}),e.jsx("tbody",{children:t.map(c=>{const d=pg[c.status],m=c.status===Ts.partial||c.status===Ts.failed;return e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label tabular-nums",children:e.jsx("button",{type:"button",className:"av-link",onClick:()=>a(c.id),"aria-label":`View the ${c.startedAt} sweep`,children:c.startedAt})}),l?e.jsx("td",{className:"text-[13px] text-secondary",children:c.kindLabel}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.triggerLabel}),r?e.jsx("td",{className:"text-[13px] text-secondary",children:c.location??"No location"}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.duration}),e.jsxs("td",{children:[e.jsx("span",{className:`av-status ${d.tone}`,children:d.word}),m&&c.statusDetail?e.jsx("span",{className:"ml-2 text-[13px] text-secondary",children:c.statusDetail}):null]})]},c.id)})})]})}),e.jsx(Ca,{items:i})]})})}const gg=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],Vo="Measured answers",fg="Close answers",Ps={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},yg={"non-brand":"non-brand queries",branded:"branded queries",unknown:"unclassified queries"},cs={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."},ia={simpleMention:"Mentioned counts answers naming your brand in the answer text, not in the source links.",simpleCitation:"Cited counts answers linking to your site in the sources behind the answer, not in the answer text.",advancedMention:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned. An answer that could not be tied to one property is left out of the rate, never counted as not mentioned.",advancedCitation:"An answer counts when it cites a matching URL for any assigned property. This does not mean every property was cited. An answer whose sources could not be checked is left out of the rate, as neither cited nor not cited, and counted on its own line.",propertyReach:"Selected properties named in at least one measured answer, out of the selected properties that have a name to match on. It counts properties, not answers, and shows no rate while any of those properties is unmeasured."},bg="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.",mr="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 vg(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function Tc(t){return t.reason==="identity-ambiguous"?Hl.ambiguous:t.reason==="not-applicable"?"Not applicable":"Not measured"}function Cn({value:t,signal:s}){if(t.rate===null)return e.jsx("span",{className:"text-sm text-secondary",children:Tc(t)});const n=Pi(t,s);return e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:et(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator]}),n?e.jsx("span",{className:"text-sm tabular-nums text-secondary",children:n}):null]})}function zo({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 Or(t,s){if(!t||t.state==="unavailable")return null;const n=t[s];if(n.state==="unavailable")switch(n.reason){case wr["previous-unavailable"]:return{text:cs.previousUnavailable,tone:"text-secondary"};case wr["current-unavailable"]:case wr["not-applicable"]:return null}const{direction:a,magnitude:r}=Vl(n.delta);switch(a){case"up":return{text:cs.up(r),tone:"text-positive"};case"down":return{text:cs.down(r),tone:"text-negative"};case"none":return{text:cs.none,tone:"text-secondary"}}}function Qo(t,s){const n=Bt(t);return s!==null&&po(n)===po(Bt(s))?_h(n):Sa(n)}function jg(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 Ng(t,s){if(!t)return null;if(t.state==="unavailable"){const n=t.previousRun?Qo(t.previousRun.createdAt,s):null;switch(t.reason){case hn["no-selected-run"]:return null;case hn["no-previous-run"]:return cs.noPreviousRun;case hn["definition-changed"]:return cs.definitionChanged(n);case hn["model-changed"]:return cs.modelChanged(n);case hn["legacy-unknown"]:return cs.legacyUnknown;case hn["partial-run"]:return cs.partialRun;case hn["scoped-run"]:return cs.scopedRun}}return cs.comparedWith(Qo(t.previousRun.createdAt,s))}function wg(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 Fr({label:t,help:s,value:n,signal:a,unit:r,classNoun:l,change:i}){const c=e.jsx("span",{className:"sr-only",children:` · ${l}`}),d=Pi(n,a);return e.jsxs("div",{className:"report-headline-tile",children:[e.jsxs("dt",{className:"flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:t}),e.jsx(Oe,{text:s})]}),n.rate===null?e.jsxs("dd",{className:"text-lg text-secondary",children:[Tc(n),c]}):e.jsxs(e.Fragment,{children:[e.jsxs("dd",{className:"report-headline-value",children:[e.jsx("span",{className:"text-3xl font-semibold tabular-nums text-heading",children:et(n.rate)}),c,i?e.jsx("span",{className:`text-sm ${i.tone}`,children:i.text}):null]}),e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:`${n.numerator} of ${n.denominator} ${r}`}),d?e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:d}):null]})]})}const Sg={otherQueries:"Other queries"},Ua={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 Cg(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(" · ")||Sg.otherQueries}return a.sort((r,l)=>r.marketLabel.localeCompare(l.marketLabel)||r.query.localeCompare(l.query))}function Ho({value:t,signal:s,singleAnswer:n}){if(n&&t.denominator===1&&t.unattributed===void 0&&t.unchecked===void 0&&(t.rate===0||t.rate===1)){const a=t.rate===1;return e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm ${a?"text-positive":"text-secondary"}`,children:[a?e.jsx(Jh,{size:16,"aria-hidden":"true"}):e.jsx(Xh,{size:16,"aria-hidden":"true"}),a?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Cn,{value:t,signal:s}),t.reason==="evidence-incomplete"?e.jsx(Oe,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function Wo({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 kg({group:t,queryClass:s,advanced:n,targetLabels:a,marketHeading:r,onViewAnswers:l}){const i=t.rows[0],c=p=>JSON.stringify([...p.targetKeys].sort()),d=t.rows.every(p=>c(p)===c(i)),m=t.rows.every(p=>p.location===i.location),u=p=>p===null?"No location requested":`Requested search location: ${p}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[r?e.jsx("tr",{children:e.jsx("th",{colSpan:4,className:"border-t border-default py-4 text-left",children:e.jsx("h3",{className:"text-base font-semibold text-heading",children:r})})}):null,e.jsx("tr",{className:"measurement-result-heading",children:e.jsxs("th",{scope:"rowgroup",colSpan:4,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"break-words text-base font-medium text-heading",children:t.query}),e.jsx("div",{className:"text-sm font-normal",children:e.jsx(ql,{showLabel:!0,queryId:i.queryId,sourceSnapshotIds:t.rows.flatMap(p=>p.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(Wo,{targetKeys:i.targetKeys,labels:a}):null,m?e.jsx("span",{children:u(i.location)}):null]})]})}),t.rows.map(p=>e.jsxs("tr",{className:"measurement-engine-result",children:[e.jsxs("td",{className:"measurement-result-engine",children:[e.jsx("span",{className:"font-medium text-heading",children:ot(p.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:p.model??"Model not recorded"}),n&&!d?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(Wo,{targetKeys:p.targetKeys,labels:a})}):null,m?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:u(p.location)}),e.jsx(El,{showLabel:!0,showSubjects:n,queryId:p.queryId,sourceSnapshotIds:p.sourceSnapshotIds??[],queryClass:s==="unknown"?null:s,provider:p.provider,model:p.model,location:p.location})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(Ho,{value:p.mentionCoverage,signal:"mentioned",singleAnswer:p.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(Ho,{value:p.citationCoverage,signal:"cited",singleAnswer:p.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(P,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${p.query} · ${p.provider}`,onClick:x=>l(p,x.currentTarget),children:[p.answerCount===1?"View answer":"View answers",e.jsx(lc,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([p.provider,p.model,p.location])))]})}const Ag="Cited counts only answers whose sources could be checked.",Yo=[{key:"mentioned",label:"Mentioned",color:lt[1],dashed:!1},{key:"cited",label:"Cited",color:Jn.positive,dashed:!0}],Jo="var(--chart-tooltip-bg)";function Rg({population:t}){const s=o.useId(),[n,a]=o.useState({mentioned:!0,cited:!0}),r=Yo.filter(x=>n[x.key]).map(x=>x.key),l=x=>a(h=>{const y={...h,[x]:!h[x]};return y.mentioned||y.cited?y:h});let i=0;const c=t.trend.map((x,h)=>(h>0&&x.continuity.state!=="comparable"&&(i+=1),{createdAt:Date.parse(x.createdAt),[`mentioned-${i}`]:x.mentionCoverage.rate,[`cited-${i}`]:x.citationCoverage.rate})),d=Array.from({length:i+1},(x,h)=>h),m=new Set(t.trend.slice(1).map(x=>x.continuity.state)),u=[...c.length===1?["First measurement. A trend appears after another comparable run."]:[],...m.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...m.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...m.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(x=>x.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[],...t.trend.some(x=>x.citationCoverage.unchecked!==void 0)?[Ag]:[]];if(c.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const p=t.trend.some(x=>x.mentionCoverage.rate!==null||x.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[p?e.jsxs(e.Fragment,{children:[e.jsxs("fieldset",{className:"flex flex-wrap gap-x-5 py-1 text-sm text-secondary",children:[e.jsx("legend",{className:"sr-only",children:"Trend legend"}),Yo.map(x=>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[x.key],disabled:n[x.key]&&r.length===1,onChange:()=>l(x.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:x.color,strokeWidth:"2",strokeDasharray:x.dashed?"6 4":void 0}),e.jsx("circle",{cx:"12",cy:"5",r:"3",fill:x.dashed?Jo:x.color,stroke:x.color,strokeWidth:"2"})]}),x.label]},x.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":`${Ps[t.queryClass]} mention and citation trend`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:c,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(va,{stroke:ya,vertical:!1}),e.jsx(en,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Ut,tickLine:!1,axisLine:{stroke:us},tickFormatter:x=>new Date(Number(x)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(tn,{domain:[0,1],tick:Ut,tickLine:!1,axisLine:!1,width:48,tickFormatter:x=>et(Number(x))}),e.jsx(sn,{...ns,formatter:x=>typeof x=="number"?et(x):"Not measured",labelFormatter:x=>new Date(Number(x)).toLocaleDateString()}),d.map(x=>e.jsxs(o.Fragment,{children:[n.mentioned?e.jsx(Gs,{type:"linear",dataKey:`mentioned-${x}`,name:"Mentioned",stroke:lt[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:lt[1]}}):null,n.cited?e.jsx(Gs,{type:"linear",dataKey:`cited-${x}`,name:"Cited",stroke:Jn.positive,strokeWidth:2,strokeDasharray:"6 4",connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:Jo,strokeDasharray:"none"}}):null]},x))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:p?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${Ps[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(x=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(x.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(Cn,{value:x.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(Cn,{value:x.citationCoverage,signal:"cited"})}),e.jsx("td",{children:x.continuity.state.replaceAll("-"," ")})]},x.runId))})]})})]})}function xi(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function $i(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=xi(a,s)??xi(t,s),c=t.populations.find(m=>m.queryClass===i?.queryClass);if(c)return c;const d=["non-brand","branded","unknown"].map(m=>t.populations.find(u=>u.queryClass===m));return d.find(m=>m&&(m.summary.queryCount>0||m.trend.some(u=>u.queryCount>0)))??d.find(m=>m!==void 0)??t.populations[0]}const At={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"},Pg={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},Ig="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 Tg(t,s){return t&&s?At.dateRange(t.slice(0,4)===s.slice(0,4)?Kh(t):Pt(t),Pt(s)):t?At.dateFrom(Pt(t)):s?At.dateThrough(Pt(s)):null}function Mg(t,s){const n=[];t.provider&&n.push({key:"engine",label:At.engine(t.provider),patch:{measurementProvider:void 0}}),t.model&&n.push({key:"model",label:At.model(t.model),patch:{measurementModel:void 0}}),t.location&&n.push({key:"location",label:t.location==="none"?At.noLocation:At.location(t.location),patch:{measurementLocation:void 0}});const a=Tg(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?At.resultsFrom(Sa(Bt(r.createdAt))):At.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function Ba(t,s,n){return s===""||t.some(a=>a.value===s)?t:[...t,{value:s,label:n}]}function Lg({report:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}){const[l,i]=o.useState(!1),c=o.useRef(null),d=o.useId(),m=`${d}-filters`,{filterOptions:u,selection:p}=t,x=p.measurement,h=$i(t,s.queryKey,s.answer),y=s.queryClass==="all"?h.queryClass:s.queryClass,f=Mg(s,t),b=s.measurementScope==="property"?s.measurementScopeKey:void 0,N=b?r?.({id:b,label:ai(t.scopeOptions,s)?.label??b}):null,k=s.provider??"",L=s.model??"",S=s.location??"",g=s.measurementRunId??"",v=()=>c.current?.focus(),C=(A,w,V,G,Q)=>e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1",children:[e.jsx("label",{htmlFor:`${d}-${w}`,className:"text-sm font-medium text-heading",children:A}),Q?e.jsx(Oe,{text:Q}):null]}),e.jsx("select",{id:`${d}-${w}`,className:mr,value:V,onChange:B=>n({[w]:B.target.value||void 0,measurementQueryKey:void 0}),children:G.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]}),I=(A,w,V,G)=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("label",{htmlFor:`${d}-${w}`,className:"mb-1 block text-sm font-medium text-heading",children:A}),e.jsx("input",{id:`${d}-${w}`,type:"date",className:mr,value:V?.slice(0,10)??"",onChange:Q=>n({[w]:Q.target.value?`${Q.target.value}${G}`: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:At.queryType}),e.jsxs("select",{"aria-label":At.queryType,className:Ig,value:y,onChange:A=>n({queryClass:A.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(Ne,{tone:x.state==="measured"?"positive":"neutral",children:x.state==="measured"?"Complete":x.state==="partial"?"Partial":"Not measured"}),x.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:Sa(Bt(x.completedAt))}):null]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[e.jsx(P,{ref:c,type:"button",variant:"outline",className:"min-h-11","aria-expanded":l,"aria-controls":m,onClick:()=>i(A=>!A),children:At.filters(f.length)}),f.map(A=>e.jsxs(P,{type:"button",variant:"outline",className:"visibility-filter-token min-h-11 rounded-md text-sm","aria-label":At.removeFilter(A.label),onClick:()=>{n(A.patch),v()},children:[e.jsx("span",{className:"min-w-0 truncate",children:A.label}),e.jsx(Yh,{size:16,className:"shrink-0","aria-hidden":"true"})]},A.key)),N,a?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:a,children:At.manageQueries}):null]})]}),e.jsxs("div",{id:m,role:"group","aria-label":At.panel,hidden:!l,className:"border-b border-default",onKeyDown:A=>{A.key==="Escape"&&(A.target instanceof HTMLElement&&A.target.getAttribute("aria-expanded")==="true"||(i(!1),v()))},children:[e.jsxs("div",{className:"visibility-report-filters",children:[C("Answer engine","measurementProvider",k,Ba([{value:"",label:"All engines"},...u.providers.map(A=>({value:A,label:A}))],k,k)),C("Requested search location","measurementLocation",S,Ba([{value:"",label:"All requested locations"},...u.locations.flatMap(A=>A.kind==="exact"?[{value:A.value,label:A.value}]:A.kind==="none"?[{value:"none",label:At.noLocation}]:[])],S,S==="none"?At.noLocation:S)),C("AI model","measurementModel",L,Ba([{value:"",label:"All models"},...Array.from(new Set(u.models.filter(A=>!s.provider||A.provider===s.provider).map(A=>A.model))).map(A=>({value:A,label:A}))],L,L),"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),I("Start date (UTC)","measurementFrom",s.from,"T00:00:00.000Z"),I("End date (UTC)","measurementTo",s.to,"T23:59:59.999Z"),C("Results from","measurementRunId",g,Ba([{value:"",label:"Latest saved sweep"},...[...h.trend].reverse().map(A=>({value:A.runId,label:new Date(A.createdAt).toLocaleString()}))],g,"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(P,{type:"button",variant:"ghost",className:"min-h-11",disabled:f.length===0,onClick:()=>{n({...Pg}),v()},children:At.clearFilters})})]})]})}function $g({report:t,isRefreshing:s=!1,onSelectionChange:n,onPage:a,onSearch:r,search:l="",queryKey:i,answerSelection:c,evidenceReport:d,isEvidenceLoading:m=!1,evidenceError:u,onRetryEvidence:p,onEvidencePage:x}){const h=o.useRef(null),y=o.useRef(void 0),f=o.useRef(null),b=$i(t,i,c,d),N=d??t,k=N.populations.filter(w=>[...w.queries.items,...w.evidence.items].some(V=>V.queryKey===i)),L=c?[c.queryClass]:(k.length?k:m?[]:[b]).map(w=>w.queryClass),S=i?JSON.stringify([c??i,L]):void 0;o.useEffect(()=>{if(!S){s||(y.current=void 0);return}if(y.current===S)return;const w=h.current?.querySelectorAll(`[aria-label="${Vo}"]`);if(w?.length){for(const V of w){const G=V.closest("details[data-query-results]");G&&(G.open=!0)}w[0].focus({preventScroll:!0}),w[0].scrollIntoView?.({block:"start"}),y.current=S}},[S,s]);const{selection:g}=t,v=vg(g.scope),C=new Map(t.scopeOptions.filter(w=>w.kind==="property").map(w=>[w.id,w.label])),I=w=>{const V=N.populations.find(G=>G.queryClass===w.queryClass)?.evidence;return{items:V?.items.filter(G=>G.queryKey===i&&(!c||G.provider===c.provider&&G.model===c.model&&G.location===c.location&&(c.runId===null||G.runId===c.runId)))??[],nextCursor:V?.nextCursor}},A=()=>{y.current=void 0;const w=f.current;w!==null&&w.row.queryKey===i&&(!c||w.row.provider===c.provider&&w.row.model===c.model&&w.row.location===c.location)&&w?.element.isConnected?w.element.focus():h.current?.querySelector(`details[data-query-results="${b.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})};return e.jsxs("section",{ref:h,className:"visibility-report","aria-label":"AI visibility results",children:[g.provenance.kind==="legacy-simple"&&g.queryClass!=="unknown"&&g.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(P,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,[b].map(w=>{const V=Cg(w.queries.items,g.scope.kind==="property"&&!g.market&&w.queryClass==="non-brand"?new Map(t.scopeOptions.filter(F=>F.kind==="market").map(F=>[F.id,F.label])):void 0),G=I(w),Q=G.items[0]?.query??w.queries.items.find(F=>F.queryKey===i)?.query,B=g.mode==="advanced"&&g.scope.kind!=="property",z=yg[w.queryClass],ne=Ng(w.comparison,jg(g,w));return e.jsxs("section",{"aria-label":Ps[w.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head flex-wrap items-center",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("h2",{children:Ps[w.queryClass]}),e.jsx(Oe,{text:w.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":w.queryClass==="branded"?"Queries that name the measured identity.":"These queries were not labeled as branded or non-brand when measured. Their saved results remain available here, separate from branded and non-brand rates."})]}),e.jsxs("div",{className:"report-headline-caption",children:[e.jsx("span",{className:"tabular-nums",children:wg(w.summary,ne)}),e.jsx(Oe,{text:cs.explanation})]})]}),e.jsxs("dl",{className:"report-headline mt-3","data-columns":B?3:2,"aria-label":`${Ps[w.queryClass]} headline results`,children:[e.jsx(Fr,{label:B?"Answers mentioning a property":"Mentioned answers",help:g.mode==="advanced"?ia.advancedMention:ia.simpleMention,value:w.summary.mentionCoverage,signal:"mentioned",unit:"answers",classNoun:z,change:Or(w.comparison,"mentionCoverage")}),e.jsx(Fr,{label:B?"Answers citing a property":"Cited answers",help:g.mode==="advanced"?ia.advancedCitation:ia.simpleCitation,value:w.summary.citationCoverage,signal:"cited",unit:"answers",classNoun:z,change:Or(w.comparison,"citationCoverage")}),B?e.jsx(Fr,{label:"Properties mentioned",help:ia.propertyReach,value:w.summary.propertyReach,signal:"mentioned",unit:"properties",classNoun:z,change:Or(w.comparison,"propertyReach")}):null]}),e.jsx($l,{queryClass:g.queryClass,manage:!0}),e.jsx(Rg,{population:w}),B&&(w.breakdown.groups.length>0||w.breakdown.properties.length>0)?e.jsx(qg,{population:w,scope:g.scope,scopeOptions:t.scopeOptions,marketKey:g.market?.id,onSelectionChange:n},`${g.scope.kind}:${g.scope.id}`):null,g.mode==="advanced"?e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Ps[w.queryClass]} property outcomes`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Property outcomes"}),e.jsxs("span",{className:"visibility-disclosure-meta",children:[w.summary.outcomes.total," ",w.summary.outcomes.total===1?"property":"properties"]})]}),e.jsxs("div",{className:"visibility-disclosure-panel flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-x-8 gap-y-3",children:[["bothSignals","mentioned and cited"],["mentionedOnly","mentioned only"],["citedOnly","cited only"],["neither","neither signal"],["notMeasured","not measured"]].map(([F,_])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:w.summary.outcomes[F]}),e.jsx("span",{className:"text-sm text-secondary",children:_})]},F))}),e.jsx(Oe,{text:bg})]})]}):null,e.jsxs("details",{className:"visibility-disclosure","data-query-results":w.queryClass,"aria-label":`${Ps[w.queryClass]} query results`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Query results"}),e.jsxs("span",{className:"visibility-disclosure-meta",children:[w.queries.total," ",w.queries.total===1?"result":"results"," · ",v]})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-3",children:[r?e.jsx("input",{type:"search","aria-label":`Search ${Ps[w.queryClass]}`,placeholder:"Search queries",className:`${mr} max-w-sm`,value:l,onChange:F=>r(F.target.value)}):null,e.jsx(Oe,{text:g.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":`${Ps[w.queryClass]} engine results`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Answer engine"}),e.jsx("th",{scope:"col",children:"Mentioned"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),V.map((F,_)=>e.jsx(kg,{group:F,queryClass:w.queryClass,marketHeading:F.marketLabel!==V[_-1]?.marketLabel?F.marketLabel:void 0,advanced:g.mode==="advanced",targetLabels:C,onViewAnswers:(Z,$)=>{f.current={row:Z,element:$},n({measurementQueryKey:Z.queryKey,measurementAnswer:JSON.stringify({queryKey:Z.queryKey,queryClass:w.queryClass,provider:Z.provider,model:Z.model,location:Z.location,runId:g.run.id,revision:g.revision})})}},F.queryKey))]})}),w.queries.items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:"No measured queries match this selection."}):e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:[V.length," ",V.length===1?"query":"queries"," · ",w.queries.items.length," ",w.queries.items.length===1?"engine result":"engine results"," shown of ",w.queries.total," results"]}),w.queries.nextCursor&&a?e.jsx(P,{variant:"outline",onClick:()=>a(w.queries.nextCursor),children:"Next queries"}):null,i&&L.includes(w.queryClass)?e.jsxs("section",{tabIndex:-1,className:"scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-label":Vo,"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:Q??"Answers"}),e.jsx(P,{variant:"ghost",className:"min-h-11",onClick:A,children:fg})]}),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]}),p?e.jsx(P,{variant:"outline",onClick:p,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[G.items.map(F=>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:F.provider}),F.model?e.jsx("span",{className:"text-[13px] text-secondary",children:F.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:F.location===null?At.noLocation:At.location(F.location)}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(F.createdAt).toLocaleDateString()}),e.jsx(Ne,{tone:"neutral",children:F.mentioned===null?F.mentionUnavailableReason==="identity-ambiguous"?Hl.ambiguous:"Mention not checked":F.mentioned?"Mentioned":"Not mentioned"}),e.jsx(Ne,{tone:"neutral",children:F.cited===null?"Citation not checked":F.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Ti,{headingLevel:4,copyable:!!F.answerText?.trim(),children:F.answerText??"Answer text unavailable."})}),F.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:[Eh," (",F.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:F.sources.map(_=>e.jsx("li",{className:"min-w-0",children:e.jsx(ki,{url:_})},_))})]}):null]},F.answerId)),I(w).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:I(w).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,I(w).nextCursor&&x?e.jsx(P,{variant:"outline",onClick:()=>x(I(w).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Ps[w.queryClass]} competitors`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Competitors"}),e.jsx("span",{className:"visibility-disclosure-meta",children:w.competitorAvailability.state==="unavailable"?"Not available":`${w.competitors.length} measured`})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[w.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):w.competitors.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No measured competitors in this selection."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Competitor"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:w.competitors.map(F=>e.jsxs("tr",{children:[e.jsx("td",{children:F.domain}),e.jsx("td",{children:e.jsx(Cn,{value:F.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(Cn,{value:F.citationCoverage,signal:"cited"})})]},F.domain))})]})}),w.observedCompetitors.length>0?e.jsxs("details",{className:"mt-4 text-sm",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-heading",children:"Other names in answers"}),e.jsx("ul",{className:"divide-y divide-default",children:w.observedCompetitors.map(F=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:F.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[F.answerCount," ",F.answerCount===1?"answer":"answers"]})]},F.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},w.queryClass)})]})}function qg({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const l=new Map(n.filter(p=>p.kind==="group").map(p=>[p.id,p])),i=[...l.values()].some(p=>p.parentGroupIds?.length),c=t.breakdown.groups.filter(p=>{const x=l.get(p.id)?.parentGroupIds??[];return s.kind==="project"?x.length===0:s.kind==="group"&&i?x.includes(s.id):!0}),[d,m]=o.useState(()=>s.kind==="project"&&c.length>0?"groups":"properties"),u=wn({rows:d==="groups"?c:t.breakdown.properties,getSearchText:p=>p.label});return e.jsxs("section",{className:"border-t border-default py-5","aria-label":"Scope breakdown",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsx("div",{className:"flex gap-2",children:["groups","properties"].map(p=>e.jsx(P,{variant:d===p?"secondary":"ghost",onClick:()=>{m(p),u.setPage(1)},children:p==="groups"?"Groups":"Properties"},p))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:u.query,onChange:p=>u.setQuery(p.target.value),className:`${mr} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:d==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:u.rows.map(p=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("button",{className:"min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>r({measurementScope:d==="groups"?"group":"property",measurementScopeKey:p.id,measurementMarketKey:a}),children:p.label})}),e.jsx("td",{children:p.queryCount}),e.jsxs("td",{children:[e.jsx(Cn,{value:p.mentionCoverage,signal:"mentioned"}),e.jsx(zo,{value:p.mentionCoverage})]}),e.jsxs("td",{children:[e.jsx(Cn,{value:p.citationCoverage,signal:"cited"}),e.jsx(zo,{value:p.citationCoverage})]})]},p.id))})]})}),u.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",d," match this search."]}):null,e.jsx(Ks,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:d,onPageChange:u.setPage})]})}function Mc(t,s,{enabled:n}){return $e({...nr({client:Y,path:{name:t},query:si(s)}),enabled:n,staleTime:Bl,retry:!1,placeholderData:wi})}function Lc(t,s){return s&&t.selection.mode==="simple"&&t.selection.measurement.state==="not-measured"}function Eg({projectName:t,selection:s,onSelectionChange:n,fallback:a,showUnmeasuredFallback:r=!1}){const[l,i]=o.useState(),[c,d]=o.useState(""),[m,u]=o.useState(),p=hs(),x=o.useMemo(()=>({scope:s.measurementScope,scopeKey:s.measurementScopeKey,marketKey:s.marketKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId}),[s.measurementScope,s.measurementScopeKey,s.marketKey,s.queryClass,s.provider,s.model,s.location,s.from,s.to,s.revision,s.measurementRunId]),h=$e({...nr({client:Y,path:{name:t},query:{...si(s),cursor:l,search:c||void 0}}),staleTime:Bl,retry:!1,placeholderData:wi}),y={...x,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??h.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??h.data?.selection.revision??s.revision,limit:50},f=JSON.stringify(y),b=$e({...nr({client:Y,path:{name:t},query:{...y,cursor:m?.selection===f?m.cursor:void 0}}),enabled:!!s.queryKey&&!!h.data&&!h.isPlaceholderData,retry:!1});if(o.useEffect(()=>{if(s.queryClass!=="all"||!h.data||h.isPlaceholderData||h.isFetching||h.isError||h.data.selection.availability.state==="unsupported"||h.data.populations.length===0||s.queryKey&&!s.answer&&!xi(h.data,s.queryKey)&&!b.data)return;const N=$i(h.data,s.queryKey,s.answer,b.data);if(!l&&!c){const{queryKey:k}=nr({client:Y,path:{name:t},query:si({...s,queryClass:N.queryClass})});p.setQueryData(k,{...h.data,selection:{...h.data.selection,queryClass:N.queryClass},populations:[N]},{updatedAt:h.dataUpdatedAt})}n({queryClass:N.queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}},{replace:!0})},[s.queryClass,s.queryKey,s.answer,h.data,h.dataUpdatedAt,h.isPlaceholderData,h.isFetching,h.isError,b.data,n,p,t,x,l,c]),h.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:a});if(h.data&&Lc(h.data,r))return e.jsx(e.Fragment,{children:a});if(h.error){const N=zl(Ql(h.error)),k=N?.reason===uu["retired-market"];return e.jsxs("section",{className:"page-section-divider",role:"alert",children:[e.jsx("h2",{children:"AI visibility unavailable"}),e.jsx("p",{className:"my-3 text-sm text-secondary",children:k?Ua.retiredMarket:N?Ua.retiredScope:fa(h.error)}),k?e.jsx(P,{variant:"outline",onClick:()=>{i(void 0),n({measurementMarketKey:void 0})},children:Ua.showAllMarkets}):N?e.jsx(P,{variant:"outline",onClick:()=>{i(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:Ua.showWholeSite}):e.jsx(P,{variant:"outline",onClick:()=>{i(void 0),h.refetch()},children:"Retry"})]})}return h.data?e.jsx("div",{"aria-busy":h.isFetching,children:e.jsx($g,{report:h.data,isRefreshing:h.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:b.data,isEvidenceLoading:b.isFetching||!!s.queryKey&&b.isPending,evidenceError:b.error?fa(b.error):void 0,onRetryEvidence:()=>{b.refetch()},onEvidencePage:b.isFetching?void 0:N=>u({selection:f,cursor:N}),search:c,onSearch:N=>{d(N),i(void 0)},onPage:h.isFetching?void 0:i,onSelectionChange:N=>{(!("measurementQueryKey"in N)||Object.keys(N).some(k=>k!=="measurementQueryKey"&&k!=="measurementAnswer"))&&i(void 0),u(void 0),n(N)}})}):e.jsx("section",{className:"page-section-divider",role:"status","aria-label":"Loading AI visibility",children:e.jsx("div",{className:"h-64 animate-pulse rounded-md bg-surface"})})}function Dg({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,fallback:l,showUnmeasuredFallback:i=!1}){const c=Mc(t,s,{enabled:!0}),d=c.error?void 0:c.data,m=!c.isPlaceholderData&&d?.selection.availability.state==="available"?d.selection.run.id:null;du(m,null);const u=!!(d&&d.selection.availability.state==="available"&&!Lc(d,i));return e.jsxs(e.Fragment,{children:[u?e.jsx(Lg,{report:d,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}):null,!u&&(d||c.error)?e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsx(Ll,{})}):null,e.jsx(Eg,{projectName:t,selection:s,onSelectionChange:n,fallback:l,showUnmeasuredFallback:i},`${t}:${JSON.stringify({...s,queryKey:void 0,answer:void 0})}`)]})}const Og=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Fg=[{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."}],qi=lt[2],Gg=lt[4],Kg="var(--chart-tooltip-bg)",_g={up:"text-positive-400",down:"text-negative-400",none:"text-muted"};function $c({direction:t,magnitude:s}){switch(t){case"up":return`up ${s} points`;case"down":return`down ${s} points`;case"none":return"no change"}}function Ug(t){return t.direction==="none"?"no change over the period":`${$c(t)} over the period`}function Bg(t){return t===ka||t===Aa||t===_s}function qc(t){return t===ka?"Cited":t===Aa?"Mentioned":t===_s?"Mention share":ot(t)}function ca(t,s){return t===ka?Jn.positive:t===Aa?lt[1]:t===_s?qi:Gh(Na(t),s)}function Ei(t){return t==="non-brand"?"non-brand answers":"all answers"}function gi(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function Di(t,s){return t==="mentionShare"?`Mention share in ${Ei(s)}`:gi(t)}function Vg(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 Ec(t){return t==="cited"?"citationRate":"mentionRate"}function Oi(t,s){return s==="cited"?t.cited:t.mentionedCount}function Dc(t,s,n){const a=t.byProvider[s];return a?{count:n==="cited"?a.cited:a.mentionedCount,total:a.total,rate:n==="cited"?a.citationRate:a.mentionRate}:null}function zg(t,s){if(s==="mentionShare"){const{projectMentionSnapshots:n,competitorMentionSnapshots:a}=t.mentionShare;return`${n} of ${n+a} tracked-brand mentions`}return`${Oi(t,s)} of ${t.total} answers`}function Qg(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Oc(t){const s=gc(t);return s===null?[]:Object.entries(s).sort(([n],[a])=>Na(n).localeCompare(Na(a))).map(([n,a])=>`${ot(n)}: ${wa(a)}`)}function Fc(t,s){return new Date(t).toDateString()===new Date(s).toDateString()}function Xo(t){return`${t} ${t===1?"query":"queries"}`}function Fi(t){const{added:s,removed:n}=t;return[...s.length>0?[`${Xo(s.length)} added`]:[],...n.length>0?[`${s.length>0?n.length:Xo(n.length)} removed`]:[]].join(", ")}function Gc(t,s){const n=$s(t),a=Ra(t),r=jc(t,s);if(!n||!a||!r)return null;const l=ex(r.moves),i=Fc(n.start,n.end),c=d=>xr(d,i?n.start:null);return n.sweepCount===2?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes the ",e.jsx("strong",{children:c(n.start)})," sweep and the ",e.jsx("strong",{children:c(n.end)})," sweep, with ",l," between them"]}):r.moves.added.length+r.moves.removed.length>0?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes sweeps with ",l," between them"]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point pools ",e.jsx("strong",{children:n.sweepCount})," sweeps, with ",l," between the first and last"]})}function Hg(t,s,n){const a=Gc(s,n);return a?e.jsxs(e.Fragment,{children:["Not the same queries: ",a]}):t.changes.length>0?e.jsxs(e.Fragment,{children:["Not the same queries: ",t.changes.map((r,l)=>e.jsxs(o.Fragment,{children:[l>0?", ":"",Fi(r)," ",e.jsx("strong",{children:ja(Bt(r.at))})]},r.at)),"; first and latest points cover different queries"]}):e.jsxs(e.Fragment,{children:["Not the same queries: first and latest points have answers for ",e.jsx("strong",{children:t.firstCount})," and ",e.jsx("strong",{children:t.latestCount})," queries"]})}function Zo(t){return t.replace(/ /g," ")}function hr({state:t,from:s=!1}){return e.jsx("span",{className:s?"av-model av-model-from":"av-model",children:wa(t)})}function Wg(t,s){return t.reroute?"Same preset, answered with a different model.":dr(t.provider,t.to)?t.served?`Preset picks its own model. Answered with ${wa(t.served.to)} (was ${wa(t.served.from)}).`:s&&s.length>0?`Preset picks its own model. Answered with ${s.join(", ")}.`:"Preset picks its own model.":null}function Yg({buckets:t,queryChanges:s,modelRows:n,served:a,pointerNotices:r,truncated:l,incompleteHistory:i,queryName:c,sweepTimes:d}){const m=t.at(-1),u=g=>ja(g),p=new Map;for(const[g,v]of r){const C=n.find(I=>I.provider===g&&!I.reroute&&I.to.status==="known"&&v.modelIds.includes(I.to.model));C&&p.set(g,C)}const x=[];s.length>0&&x.push({key:"queries",label:"Queries",rows:s.map(g=>({key:`queries-${g.at}`,at:g.at,onOrBefore:!1,from:null,to:e.jsx("span",{className:"text-strong",children:Fi(g)}),toHelp:null}))});const h=[...new Set(n.map(g=>g.provider))].sort((g,v)=>ot(g).localeCompare(ot(v)));for(const g of h){const C=a[g]?.latestServedModelIds??null,I=n.filter(A=>A.provider===g);x.push({key:g,label:ot(g),rows:I.map((A,w)=>{const V=p.get(g)===A?r.get(g).text:null,G=[Wg(A,w===0?C:null),V].filter(Boolean).join(" ");return{key:`${g}-${A.at}-${A.reroute?"served":"set"}`,at:A.at,onOrBefore:A.onOrBefore,from:e.jsx(hr,{state:A.from,from:!0}),to:e.jsx(hr,{state:A.to}),toHelp:G||null}})})}const y=x.reduce((g,v)=>g+v.rows.length,0),f=[];for(const g of s)g.added.length>0&&f.push(e.jsxs(e.Fragment,{children:["Added ",e.jsx("strong",{children:u(g.at)}),": ",g.added.map(c).join(", ")]})),g.removed.length>0&&f.push(e.jsxs(e.Fragment,{children:["Removed ",e.jsx("strong",{children:u(g.at)}),": ",g.removed.map(c).join(", ")]}));const b=m?Ra(m):null;for(const[g,v]of Object.entries(m?gc(m)??{}:{}).sort(([C],[I])=>C.localeCompare(I)))v.status==="mixed"&&b&&f.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:b})," point mixes ",ot(g)," models: ",Ep(v)]}));const N=new Map;for(const g of n.filter(v=>v.onOrBefore)){const v=g.anchorAt?u(g.anchorAt):"";N.set(v,[...new Set([...N.get(v)??[],ot(g.provider)])])}for(const[g,v]of N)f.push(g?e.jsxs(e.Fragment,{children:["Changed before this date range, after the ",e.jsx("strong",{children:g})," sweep: ",xa(v)]}):`Changed before this date range: ${xa(v)}`);for(const g of l)f.push(`${ot(g.provider)}: most recent ${g.shown} of ${g.total} changes`);for(const g of i)f.push(`${ot(g)}: may be missing older changes`);for(const[g,v]of r)p.has(g)||f.push(e.jsxs("span",{className:"inline-flex items-center gap-1",children:[ot(g),": no model updates on record",e.jsx(Oe,{text:v.text})]}));if(y===0&&f.length===0)return null;for(const[g,v]of Object.entries(a).sort(([C],[I])=>ot(C).localeCompare(ot(I)))){const C=v.latestServedModelIds??[],I=C.length>0?C.join(", "):wa(v.latestObservation.state);f.push(e.jsxs(e.Fragment,{children:[ot(g)," last answered with ",e.jsx("strong",{children:I})," on ",e.jsx("strong",{children:u(Bt(v.latestObservation.observedAt))})]}))}const k=x.flatMap(g=>g.rows.map(v=>v.at));let L="First sweep on the new model or query set.";if(k.length>0){const g=u(k.reduce((V,G)=>Date.parse(G)>Date.parse(V)?G:V)),v=[...new Set(k.filter(V=>u(V)===g))].sort(),C=v.map(V=>xr(V,V));L+=` ${g} = the ${xa(C)} ${C.length===1?"sweep":"sweeps"}.`;const I=n.flatMap(V=>V.anchorAt?[V.anchorAt]:[]),A=I.length>0?I.reduce((V,G)=>Date.parse(G)>Date.parse(V)?G:V):null,w=Yp(v[0],d,t,A);w&&(L+=` Sweep before: ${u(w)}.`)}const S=Wp({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:S}),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(Oe,{text:L})]})}),e.jsx("th",{scope:"col",children:"From"}),e.jsx("th",{scope:"col",children:"To"})]})}),x.map(g=>e.jsx("tbody",{children:g.rows.map((v,C)=>e.jsxs("tr",{children:[C===0?e.jsx("th",{scope:"row",className:"av-engine",children:g.label}):e.jsx("td",{className:"av-engine",children:e.jsx("span",{className:"sr-only",children:g.label})}),e.jsx("td",{className:"av-date",children:v.onOrBefore?`on or before ${Zo(u(v.at))}`:Zo(u(v.at))}),v.from===null?null:e.jsx("td",{children:v.from}),e.jsx("td",{colSpan:v.from===null?2:void 0,children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[v.to,v.toHelp?e.jsx(Oe,{text:v.toHelp}):null]})})]},v.key))},g.key))]})}),e.jsx(Ca,{items:f})]}):e.jsx("ul",{className:"av-details-list",children:f.map((g,v)=>e.jsx("li",{children:g},v))})})]})}function Jg({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:ot(s)}),e.jsxs("span",{className:"text-secondary",children:["selected ",e.jsx(hr,{state:n.configured})," · answered ",e.jsx(hr,{state:n.served})]}),e.jsx("span",{className:"av-status text-caution-400",children:"substituted"})]},s))})}function Xg({active:t,label:s,payload:n,metric:a,mode:r,buckets:l,basketChanges:i}){if(!t)return null;const c=Qg(l,s);if(!c)return null;const d=$s(c),m=d!==null&&Fc(d.start,d.end)?d.start:null,u=bc(c,i),p=Oc(c),x=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-tooltip-label",children:Mi(c)}),u.map(f=>e.jsxs("p",{className:"trend-tooltip-detail trend-tooltip-note",children:[Fi(f)," ",xr(f.at,m)]},f.at))]}),h=p.length>0&&e.jsx("p",{className:"trend-tooltip-detail trend-tooltip-models",children:p.map((f,b)=>e.jsxs(o.Fragment,{children:[b>0?"; ":"",e.jsx("span",{className:"whitespace-nowrap",children:f})]},b))});if(a==="mentionShare"){const f=c.mentionShare.projectMentionSnapshots,b=c.mentionShare.competitorMentionSnapshots,N=f+b;return e.jsxs("div",{className:"trend-tooltip",children:[x,e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:qi},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Di("mentionShare",c.mentionShare.scope)}),e.jsx("span",{className:"trend-tooltip-value",children:et(c.mentionShare.rate)})]}),e.jsx("p",{className:"trend-tooltip-detail",children:N>0?`You ${f} of ${N} tracked-brand mentions. Competitors ${b}.`:"No tracked-brand mentions in this point"}),h]})}const y=r==="byProvider"?(n??[]).filter(f=>f.dataKey!==void 0):[{dataKey:a==="cited"?ka:Aa}];return e.jsxs("div",{className:"trend-tooltip",children:[x,y.map((f,b)=>{const N=String(f.dataKey??f.name??""),k=r==="byProvider"?Dc(c,N,a):null,L=k?.count??Oi(c,a),S=k?.total??c.total,g=k?k.rate:c[Ec(a)],v=f.color??ca(N,b);return e.jsx("div",{className:"trend-tooltip-block",children:e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:v},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:qc(N)}),e.jsx("span",{className:"trend-tooltip-value",children:et(g)}),e.jsxs("span",{className:"trend-tooltip-count",children:[L," of ",S]})]})},`${N}-${b}`)}),h]})}function Zg({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:[Di(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,p=Ei(l.mentionShare.scope);i=u>0?`${et(l.mentionShare.rate)} mention share in ${p}, ${d} of ${u} tracked-brand mentions were you`:`mention share undefined in ${p}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(d=>{const m=Dc(l,d,s);return m?`${ot(d)} ${et(m.rate)} ${gi(s).toLowerCase()}, ${m.count} of ${m.total} answers`:`${ot(d)} no data`}).join("; "):i=`${et(l[Ec(s)])} ${gi(s).toLowerCase()}, ${Oi(l,s)} of ${l.total} answers`;const c=Oc(l);return c.length>0&&(i+=`; models: ${c.join("; ")}`),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Mi(l)}),e.jsx("td",{children:i})]},l.startDate)})})]})})}function ef({projectName:t,competitorDomains:s=[],competitorAliases:n,analyticsRevision:a="none",queryTexts:r=[],classifyQuery:l,sweepTimes:i=[]}){const[c,d]=o.useState("all"),[m,u]=o.useState("mentioned"),[p,x]=o.useState("byProvider"),h=o.useId(),y=o.useMemo(()=>Pp(s,n),[s,n]),f=$e({queryKey:["analytics-metrics",t,c,y,a],queryFn:()=>cu(t,c),staleTime:Ri}),b=f.data??null,N=f.error,k=m==="mentionShare"?"overall":p,L=o.useMemo(()=>b?Kp(b,m,k):null,[b,m,k]),S=b?Mp(b):null,g=o.useMemo(()=>Op(S??{}),[S]),v=o.useMemo(()=>Fp(S??{}),[S]),C=o.useMemo(()=>Object.entries(S??{}).filter(([,fe])=>fe.anchorUnavailable).map(([fe])=>fe).sort(),[S]),I=o.useMemo(()=>b?Lp(b):{},[b]),A=o.useMemo(()=>b?Vp($p(b)):[],[b]),w=o.useMemo(()=>b?yc(b):[],[b]),V=o.useMemo(()=>b?zp(b):[],[b]),G=o.useMemo(()=>Hp(S??{},I),[S,I]),Q=o.useMemo(()=>b?qp(b):{},[b]),B=o.useMemo(()=>no(Q,{engineName:ot}),[Q]),z=o.useMemo(()=>{const fe=new Map;for(const[Ce,Ge]of Object.entries(Q).sort(([Ee],[O])=>Ee.localeCompare(O))){const Ee=no({[Ce]:Ge},{engineName:ot});Ee?.kind==="no-known-change"&&fe.set(Ce,{text:`${Ee.text} ${Ee.detail}`,modelIds:Ge.modelIds??[]})}return fe},[Q]),ne=o.useMemo(()=>{const fe=new Map(r.map(Ce=>[Bn(Ce),Ce]));return Ce=>fe.get(Bn(Ce))??Ce},[r]),F=m!=="mentionShare"&&k==="byProvider",_=b?.buckets??[],Z=_[_.length-1]?.mentionShare.scope??b?.mentionShareScope??"pooled",$=Di(m,Z),ee=F?ms.textDim:m==="cited"?Jn.positive:m==="mentionShare"?qi:lt[1],T=o.useMemo(()=>{const fe=new Map(_.map(Ce=>[Ce.startDate,Rp(Ce)]));return Ce=>fe.get(String(Ce))??""},[_]),E=m==="mentionShare"?_.filter(fe=>typeof fe.mentionShare.rate=="number"&&Number.isFinite(fe.mentionShare.rate)):_,te=E.at(-1),le=(b?_p(b,m):[]).at(-1)??null,we=b?Up(b,m):null,X=Zp(E,w),ue=jo(X,m,Z,l),xe=le!==null&&we!==null?Vl(we.delta):null,J=xe!==null&&!ue,he=s.length,K=[];if(te&&we!==null&&X&&!ue&&K.push(Hg(X,te,w)),te&&E.length===1){const fe=Gc(te,w);fe&&!jo(jc(te,w),m,Z,l)&&K.push(fe)}if(xe!==null&&E[0]){const fe=Ra(E[0]);fe&&K.push(e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:fe})," point"]}))}F&&le!==null&&K.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:et(le)})," pools all answers; not an average of engines"]}));const pe=[...new Set([...g.buckets.map(fe=>fe.bucketStartDate),..._.filter(fe=>bc(fe,w).length>0).map(fe=>fe.startDate)])].sort(),qe=le!==null&&te&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:ee},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:$}),e.jsx("span",{className:"visibility-trend-current-value",children:et(le)}),xe!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${J?"text-muted":_g[xe.direction]}`,children:[$c(xe),J?" (not the same queries)":""]}),e.jsxs("span",{className:"visibility-trend-current-detail",children:["· ",zg(te,m)]})]}),Ae=e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(pa,{options:Fg,value:m,onChange:u,label:"Metric",className:"visibility-trend-metric-control"}),m!=="mentionShare"&&e.jsx(pa,{options:Og,value:p,onChange:x,label:"Series"}),e.jsx(pa,{options:gg,value:c,onChange:d,label:"Time window",className:"sm:ml-auto"})]});let ie;if(N)ie=e.jsx("p",{className:"text-sm text-negative-400",children:fa(N)});else if(f.isLoading&&!b)ie=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(m==="mentionShare"&&he===0)ie=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!b||!L)ie=null;else{const{rows:fe,series:Ce,hasData:Ge}=L;if(!Ge)ie=e.jsx("p",{className:"text-sm text-secondary",children:m==="mentionShare"?`No answer-text brand mentions for you or tracked competitors in ${Ei(Z)} in this window yet.`:ds()?zn:"Run a sweep to start tracking citations and mentions over time."});else if(F&&Ce.length===0)ie=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 Ee=`${$} rate across ${fe.length} ${fe.length===1?"sweep":"sweeps"}. Latest ${et(le)}${xe!==null?`, ${Ug(xe)}${J?", not the same queries":""}`:""}.`;ie=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:Ee}),e.jsx(Zg,{buckets:_,metric:m,mode:k,series:Ce,mentionShareScope:Z}),F&&Ce.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:Ce.map((O,D)=>{const H=Bp(b,O,m);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:ca(O,D)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:qc(O)}),H!==null&&e.jsx("span",{className:"trend-legend-value",children:et(H)})]},O)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${$} trend chart over ${fe.length} ${fe.length===1?"point":"points"}`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:fe,margin:{top:8,right:20,bottom:0,left:0},children:[e.jsx(va,{stroke:ya,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:us},tickFormatter:T,minTickGap:24}),e.jsx(tn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:O=>et(O,Yn.percent),tick:Ut,tickLine:!1,axisLine:!1,width:40}),e.jsx(sn,{cursor:{stroke:us,strokeWidth:1},content:e.jsx(Xg,{metric:m,mode:k,buckets:_,basketChanges:w})}),pe.map(O=>e.jsx(ip,{x:O,stroke:Gg,strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`setup-change-${O}`)),Ce.map((O,D)=>e.jsx(Gs,{type:"monotone",dataKey:O,name:O,stroke:ca(O,D),strokeDasharray:O===_s?"5 4":void 0,strokeWidth:Bg(O)?2.5:2,dot:O===_s?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:ca(O,D),strokeWidth:1.5}:{r:2.5,fill:ca(O,D),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Kg},connectNulls:O!==_s,isAnimationActive:!1},O))]})})}),pe.length>0&&e.jsxs("p",{className:"visibility-trend-key",children:[e.jsx("span",{className:"visibility-trend-key-swatch","aria-hidden":"true"}),"Setup changed"]})]})}}return e.jsxs("div",{className:"visibility-trend-stack",children:[e.jsxs("section",{className:"visibility-trend","aria-labelledby":h,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:h,className:"av-card-title",children:"AI answers over time"}),e.jsx(Oe,{text:Vg(Z)})]}),te?e.jsx("p",{className:"av-card-meta",children:Mi(te)}):null]}),e.jsxs("div",{className:"visibility-trend-body",children:[B?.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:B.text}),qe,Ae,ie]}),e.jsx(Ca,{items:K})]}),b&&!N?e.jsxs(e.Fragment,{children:[e.jsx(Yg,{buckets:_,queryChanges:V,modelRows:G,served:I,pointerNotices:z,truncated:v,incompleteHistory:C,queryName:ne,sweepTimes:i}),e.jsx(Jg,{substitutions:A})]}):null]})}const el=new Set([ha.queued,ha.running]),_t={queryPlaceholder:"Write one research query per line",runAction:"Run queries",historyTitle:"Research history",historyMore:"Load older runs",historyLoading:"Loading older runs…",historyMoreError:"Could not load older research. Try again.",resultsTitle:"Research results",emptyHistory:"No saved research.",resultsEmpty:"Choose a saved run.",methodologySummary:"How matching works",methodology:"Brand-name matches use configured project names or domains in answer text. Project-domain citations use source links. Neither verifies property identity.",refreshPreview:"Regenerate preview",templateProvenance:"Query pattern details",brandedQuery:"Branded",discoveryQuery:"Discovery",unclassifiedQuery:"Unclassified"};function tl({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d=[],viewerResearchConfig:m=null}){const u=hs(),{account:p,canWrite:x}=nn(),h=p?.role==="viewer"&&m!==null,y=!x,f=Ls(),[b,N]=o.useState(""),[k,L]=o.useState(""),[S,g]=o.useState(null),[v,C]=o.useState([]),I=o.useRef(null),A=o.useRef(!1),[w,V]=o.useState(0),G=$e({...mu({client:Y,path:{name:t}}),staleTime:6e4}),Q=$e({...hu({client:Y}),enabled:!y&&!f,staleTime:6e4}),B={client:Y,path:{name:t},query:{limit:20}},z=Ml({...pu(B),initialData:void 0,initialPageParam:B,getNextPageParam:K=>K.nextCursor?{path:B.path,query:{...B.query,cursor:K.nextCursor}}:void 0,refetchInterval:K=>K.state.data?.pages.some(pe=>pe.runs.some(qe=>el.has(qe.status)))?3e3:!1}),ne=z.isError&&!z.isFetchNextPageError,F=z.data?.pages.at(-1),_=ne?[]:[...new Map((z.data?.pages.flatMap(K=>K.runs)??[]).map(K=>[K.id,K])).values()],Z=F?.access?.canRun??(x||h),$=F?.access?F.access.dailyRunLimit:h?m.viewerDailyRunLimit:null;o.useEffect(()=>{!S&&_[0]&&g(_[0].id)},[_,S]);const ee=_.find(K=>K.id===S)??null,T=$e({...xu({client:Y,path:{name:t,runId:S??""}}),enabled:!ne&&!!S,refetchInterval:ee&&el.has(ee.status)?3e3:!1}),E=ne||T.isError?null:T.data??null,te=G.data?.locations??[],re=o.useMemo(()=>{if(y)return(F?.providers??[]).map(pe=>({...pe,catalog:pe}));const K=new Map((Q.data?.providerCatalog??[]).map(pe=>[pe.name,pe]));return(Q.data?.providers??[]).filter(pe=>pe.configured&&K.get(pe.name)?.mode==="api").map(pe=>({...pe,catalog:{...K.get(pe.name),defaultModel:pe.model||K.get(pe.name).defaultModel}}))},[y,F?.providers,Q.data]),le=!(y?z.isPending:Q.isPending)&&re.length===0,we=re.find(K=>K.name===b)??null;o.useEffect(()=>{if(!b&&G.data&&!G.isError&&!Q.isError){const K=G.data.providers.find(pe=>re.some(qe=>qe.name===pe));N(K??re[0]?.name??"")}},[b,re,G.data,G.isError,Q.isError]);const X=we?.catalog.modelConfigurable??!1,ue=y?we?.catalog.defaultModel:(we?G.data?.providerModels[we.name]:"")||we?.catalog.defaultModel,xe=(X?k.trim():"")||ue,J=we?[...new Map([{id:we.catalog.defaultModel,displayName:we.catalog.defaultModel},...k.trim()?[{id:k.trim(),displayName:k.trim()}]:[],...we.catalog.knownModels].map(K=>[K.id,K])).values()]:[],he=Et({...gu(),onSuccess:async K=>{I.current=null,V(pe=>pe+1),C(K.runs),g(K.runs[0]?.id??null),await uf(u),De({title:"Research batch saved",detail:`${K.runs.length} ${K.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${K.runs.map(pe=>pe.id).join(":")}`,dedupeMode:"replace"})},onError:K=>{De({title:"Could not start research",detail:K instanceof Error?K.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{A.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[f?e.jsx(je,{className:"surface-card min-w-0",children:e.jsx("p",{className:"text-sm text-secondary",children:"This public demo shows saved research results. Running research is unavailable."})}):e.jsxs(e.Fragment,{children:[e.jsx(tf,{projectName:t,canWrite:x,researchAllowed:Z&&!ne,limitedAccess:y,isEmbed:oe(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d,locations:te,defaultLocation:G.data?.defaultLocation??null,providerOptions:re,provider:b,onProviderChange:K=>{N(K),L("")},resolvedModel:xe,visibilityModel:ue,configurableModel:X,model:k,onModelChange:L,modelOptions:J,settingsReady:y?!z.isPending&&!ne:!Q.isPending&&!Q.isError&&!Q.isFetching,projectReady:!G.isPending&&!G.isError&&!G.isFetching,isPending:he.isPending,errorMessage:he.isError?"The request could not be confirmed.":void 0,onSubmit:(K,pe)=>{!Z||ne||oe()||A.current||(I.current?.fingerprint!==pe&&(I.current={fingerprint:pe,key:crypto.randomUUID()}),A.current=!0,he.mutate({client:Y,path:{name:t},body:{...K,idempotencyKey:I.current.key}}))}},`${t}:${w}`),$!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",$," destination runs per project per day."]}),!y&&Q.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(P,{variant:"outline",onClick:()=>{Q.refetch()},children:"Retry providers"})]}):null,G.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(P,{variant:"outline",onClick:()=>{G.refetch()},children:"Retry locations"})]}):null,!(y?ne:Q.isError)&&le&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:y?"No research engines are available. Ask your Canonry team to configure one.":"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."}),v.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",v.map((K,pe)=>e.jsxs("span",{children:[pe>0?", ":"",e.jsxs("a",{href:`#research-run-${K.id}`,className:"text-link underline",onClick:()=>g(K.id),children:[K.scope?.label??"Whole site",K.location?`, ${K.location.label}`:", No location"]})]},K.id))]})]}),e.jsxs(je,{className:"surface-card min-w-0",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsx("div",{children:e.jsx("h3",{children:_t.historyTitle})}),z.isFetching&&e.jsx(Ne,{tone:"neutral",children:"Loading"})]}),ne?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(P,{variant:"outline",onClick:()=>{z.refetch()},children:"Retry history"})]}):z.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):_.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:_t.emptyHistory}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Destination"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:_.map(K=>e.jsxs("tr",{className:S===K.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:()=>g(K.id),children:lf(K.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:K.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:K.requestedModel??K.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:K.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:K.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[K.completedQueries+K.failedQueries,"/",K.totalQueries]}),e.jsx("td",{children:e.jsx(Ne,{tone:Kc(K.status),children:K.status})})]},K.id))})]})}),z.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:_t.historyMoreError}),z.hasNextPage&&e.jsx(P,{className:"mt-3",variant:"outline",disabled:z.isFetching,onClick:()=>{z.fetchNextPage()},children:z.isFetchingNextPage?_t.historyLoading:_t.historyMore})]})]}),!ne&&T.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(P,{variant:"outline",onClick:()=>{T.refetch()},children:"Retry results"})]}):ne?null:e.jsx(rf,{detail:E,isLoading:T.isFetching,onReviewForTracking:f?void 0:s})]})}const Is="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",Fn="__none__";function tf(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:l}=t,i=hs(),[c,d]=o.useState("once"),[m,u]=o.useState(""),[p,x]=o.useState(""),[h,y]=o.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[f,b]=o.useState(null),[N,k]=o.useState([]),[L,S]=o.useState(""),[g,v]=o.useState({}),[C,I]=o.useState(null),[A,w]=o.useState([]),[V,G]=o.useState(null),[Q,B]=o.useState(!1),[z,ne]=o.useState(!1),[F,_]=o.useState(""),[Z,$]=o.useState(""),ee=o.useRef(null),T=o.useRef(!1),E=o.useRef(null),te=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";o.useEffect(()=>{y(te),I(null)},[te]);const re=t.scopeOptions.filter(R=>R.kind==="market"||R.kind==="property"),le=c==="markets"?"market":"property",we=re.filter(R=>R.kind===le),X=R=>({kind:R.kind,key:R.id,label:R.label,planRevision:l??t.initialScope?.planRevision??0}),ue=R=>R===Fn?null:n.find(Le=>Le.label===R),xe=f??t.defaultLocation??Fn,J=re.find(R=>`${R.kind}:${R.id}`===h),he=J?X(J):null,K=c==="once"?[{scope:he,location:ue(xe)}]:c==="locations"?N.map(R=>({scope:null,location:ue(R)})):N.map(R=>we.find(Le=>`${Le.kind}:${Le.id}`===R)).map(R=>R?{scope:X(R),location:ue(g[`${R.kind}:${R.id}`]??Fn)}:null),pe=[...new Map([...A,...t.templates].map(R=>[R.id,R])).values()],qe=C?pe.find(R=>R.id===C.id):null,Ae=C!==null&&qe?.version!==C.version,ie=c==="once"?m:p,fe=ie.split(/\r?\n/).filter(R=>R.trim()),Ce=ao(fe),Ge=[...new Set([...p.matchAll(/\{([^{}]+)\}/g)].map(R=>R[1]))],Ee=/[{}]/.test(p.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),O=[];fe.length||O.push(c==="once"?"Enter at least one query.":"Enter at least one query pattern."),fe.some(R=>R.length>4e3)&&O.push("Keep each query under 4,001 characters."),c!=="once"&&Ee&&O.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),K.length||O.push(c==="locations"?"Select at least one location.":"Select at least one destination."),K.some(R=>!R||R.location===void 0)&&O.push("A selected destination or location is no longer available. Update your selection.");const D=c==="once"&&h!=="project"||c==="markets"||c==="properties";D&&(t.scopePending||t.scopeError||!l||K.some(R=>!R?.scope))&&O.push("Load the current published markets and properties before running scoped research.");const H=(c==="once"?Ce.length:fe.length)*K.length;if(K.length>Ea&&O.push(`Select at most ${Ea} destinations.`),H>Cr&&O.push(`${H} queries selected. Reduce the selection to ${Cr} or fewer.`),Ae&&O.push("This saved pattern changed. Select its current version from Saved patterns."),c!=="once"&&!Ee){for(const R of K)if(!(!R||R.location===void 0))try{Sr(C??{pattern:p,variables:Ge},R.scope,R.location)}catch{O.push(`Choose a location for {location}, or use only variables available for ${c==="markets"?"markets":c==="properties"?"properties":"locations"}.`);break}}const Me=JSON.stringify({mode:c,source:ie,contexts:K,provider:a,resolvedModel:r,template:C,...D?{planRevision:l}:{}}),Qe=V!==null&&V.signature!==Me,Fe=c==="once"?Ce.map((R,Le)=>({id:String(Le),query:R,scope:he,location:K[0]?.location??null})):V?.rows??[],tt=af(Fe),ge=[];c!=="once"&&V&&(Qe&&ge.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),Fe.some(R=>!R.query.trim()||R.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(R.query))&&ge.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),Fe.some(R=>R.location&&!n.some(Le=>JSON.stringify(Le)===JSON.stringify(R.location)))&&ge.push("A preview location changed. Regenerate the preview."),tt.some(R=>ao(R.queries).length!==R.queries.length)&&ge.push("Remove duplicate queries within each destination and location."),tt.length>Ea&&ge.push(`The preview exceeds ${Ea} runs.`));const vt=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!O.length&&!ge.length&&(c==="once"||V!==null),Ve=()=>({runs:tt.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}:{}}))}),Je=()=>{if(B(!0),O.length)return;const R=K.flatMap((Le,Pe)=>fe.map((Ke,dt)=>({id:`${Pe}:${dt}`,scope:Le.scope,location:Le.location,...C?{template:{templateId:C.id,templateVersion:C.version,bindingLocation:Le.location}}:{},query:Sr({pattern:Ke,variables:[...new Set([...Ke.matchAll(/\{([^{}]+)\}/g)].map(ze=>ze[1]))]},Le.scope,Le.location).output})));G({signature:Me,rows:R})},Dt=R=>{d(R),k([]),I(null),S(""),B(!1)},ct=R=>{if($(""),c==="once")try{u(Sr(R,he,ue(xe)).output)}catch{$("Select a matching market, property, or location before using this pattern.");return}else x(R.pattern);I(R)},at=R=>{const Le=E.current,Pe=Le?.selectionStart??p.length,Ke=Le?.selectionEnd??Pe;x(`${p.slice(0,Pe)}{${R}}${p.slice(Ke)}`),I(null),requestAnimationFrame(()=>{Le?.focus(),Le?.setSelectionRange(Pe+R.length+2,Pe+R.length+2)})},pt=Et({...yu(),onSuccess:async R=>{const Le={id:R.id,version:R.updatedAt,label:R.name,pattern:R.pattern,variables:R.variables};w(Pe=>[...Pe.filter(Ke=>Ke.id!==R.id),Le]),I(Le),ne(!1),_(""),$(""),ee.current=null,await i.invalidateQueries({queryKey:fu({client:Y,path:{name:s}})}),De({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>$("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{T.current=!1}}),Ct=()=>{if(!t.canWrite||t.isEmbed||T.current)return;const R=c==="once"?m:p,Le=c==="once"?[]:Ge;if(!F.trim()||!R.trim()||R.length>4e3||c!=="once"&&Ee){$("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const Pe={name:F.trim(),pattern:R,variables:Le},Ke=JSON.stringify(Pe);ee.current?.fingerprint!==Ke&&(ee.current={fingerprint:Ke,id:crypto.randomUUID()}),T.current=!0,pt.mutate({client:Y,path:{name:s,templateId:ee.current.id},body:Pe})},It=[...new Set([...Q||ie.trim()?O:[],...ge])],He=pe.filter(R=>{const Le=c==="once"?ro(he,ue(xe)):ro(c==="markets"?{kind:"market",label:"Market"}:c==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return R.variables.every(Pe=>Le[Pe]!==void 0)});return e.jsxs(je,{className:"surface-card min-w-0",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Test queries"}),e.jsx("p",{className:"mt-1 max-w-prose text-sm text-secondary",children:"See how an answer engine responds. Results are saved separately from tracked queries and AI Visibility metrics."})]})}),e.jsxs("fieldset",{"aria-label":"Research setup",className:"mt-5 min-w-0 space-y-5",disabled:t.isPending||pt.isPending,children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Run mode"}),e.jsxs("select",{className:Is,value:c,disabled:t.isPending,onChange:R=>Dt(R.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!re.some(R=>R.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!re.some(R=>R.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),c==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(re.length>0||h!=="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:Is,value:h,onChange:R=>{y(R.target.value),I(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),h!=="project"&&!J&&e.jsx("option",{value:h,disabled:!0,children:"Selected destination unavailable"}),re.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:xe,locations:n,onChange:R=>{b(R),I(null)}})]}),c!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:c==="locations"?"Select locations":`Select ${c}`}),e.jsx("p",{className:"text-sm text-secondary",children:"Choose each destination explicitly. Each selected destination gets its own saved research run."}),e.jsx("input",{type:"search","aria-label":"Search destinations",className:Is,placeholder:`Search ${c}`,value:L,onChange:R=>S(R.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(c==="locations"?n.map(R=>({key:R.label,label:R.label})):we.map(R=>({key:`${R.kind}:${R.id}`,label:R.label}))).filter(R=>R.label.toLocaleLowerCase().includes(L.toLocaleLowerCase())).map(R=>{const Le=N.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:Le,onChange:()=>k(Pe=>Le?Pe.filter(Ke=>Ke!==R.key):[...Pe,R.key])}),R.label]}),Le&&c!=="locations"&&e.jsx(fi,{label:`Answer engine location for ${R.label}`,value:g[R.key]??Fn,locations:n,onChange:Pe=>v(Ke=>({...Ke,[R.key]:Pe}))})]},R.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[N.length," selected. A market or property name changes query text, not the answer engine's location."]})]}),t.scopeError&&e.jsxs("p",{className:"text-sm text-caution",children:["Markets and properties could not load. Whole-site and location research remain available. ",e.jsx(P,{variant:"outline",onClick:t.onRetryScope,children:"Retry destinations"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block",htmlFor:"research-query-editor",children:e.jsx("span",{className:"text-sm font-medium text-heading",children:c==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:c==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${c==="markets"?"market":c==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:E,className:`${Is} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:ie,placeholder:c==="once"?_t.queryPlaceholder:c==="markets"?"Best apartments in {market}":c==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:R=>{c==="once"?u(R.target.value):(x(R.target.value),I(null))}}),c!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(P,{size:"sm",variant:"outline",onClick:()=>at(c==="markets"?"market":c==="properties"?"property":"location"),children:["Insert ",c==="markets"?"market":c==="properties"?"property":"location"," name"]}),e.jsx("span",{className:"self-center text-sm text-secondary",children:"One pattern per line."})]}),e.jsxs("p",{id:"research-query-count",className:"mt-2 text-sm text-secondary",children:[H," / ",Cr," queries",c==="once"?"":` across ${K.length} destinations`]})]}),c!=="once"&&e.jsxs("details",{className:"border-t border-default pt-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading focus-visible:outline focus-visible:outline-2",children:["Saved patterns ",e.jsx("span",{className:"font-normal text-secondary",children:"(optional)"})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries."}),He.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:He.map(R=>e.jsx(P,{size:"sm",variant:"outline",onClick:()=>ct(R),children:R.label},R.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),C&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",C.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(P,{size:"sm",variant:"outline",onClick:()=>ne(!z),children:z?"Cancel save":"Save as a pattern"}),z&&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:Is,value:F,maxLength:120,onChange:R=>_(R.target.value)})]}),e.jsx(P,{size:"sm",disabled:pt.isPending||!F.trim()||!ie.trim(),onClick:Ct,children:pt.isPending?"Saving…":"Save pattern"})]})]}),Z&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:Z})]})]}),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:Is,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:Is,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:Is,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))})]})]})]}),It.length>0&&e.jsx(nf,{errors:It}),c!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:Je,children:[e.jsx(ba,{size:14}),V?_t.refreshPreview:"Preview queries"]}),V&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Queries to run"}),e.jsxs("p",{className:"text-sm text-secondary",children:[Fe.length," query executions in ",tt.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(sf,{rows:Fe,locations:n,onChange:(R,Le)=>G(Pe=>Pe&&{...Pe,rows:Pe.rows.map(Ke=>Ke.id===R?{...Ke,...Le}:Ke)})})]})]}),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(P,{size:"sm",disabled:!vt,onClick:()=>{if(vt){const R=Ve();t.onSubmit(R,JSON.stringify({projectName:s,...R}))}},children:[e.jsx(lr,{size:14}),t.isPending?"Starting…":_t.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[c==="once"?`${Ce.length} queries`:`${Fe.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:Is,value:s,onChange:r=>a(r.target.value),children:[e.jsx("option",{value:Fn,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function sf({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:`${Is} 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??Fn,locations:s,onChange:l=>n(a.id,{location:s.find(i=>i.label===l)??null})})]},a.id))})}function nf({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 af(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 rf({detail:t,isLoading:s,onReviewForTracking:n}){const[a,r]=o.useState(null);o.useEffect(()=>{r(t?.queries[0]?.id??null)},[t?.id]);const l=t?.queries.find(i=>i.id===a)??t?.queries[0]??null;return e.jsxs(je,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":_t.resultsTitle,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Results"}),e.jsx("h3",{children:t?`Research run ${cf(t.id)}`:_t.resultsEmpty})]}),t&&e.jsx(Ne,{tone:Kc(t.status),children:t.status})]}),t&&e.jsxs("div",{className:"mt-3 space-y-3 text-sm text-secondary",children:[e.jsxs("dl",{className:"flex flex-wrap gap-x-6 gap-y-2 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Answer engine"}),e.jsx("dd",{children:t.provider})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Requested model"}),e.jsx("dd",{className:"font-mono",children:t.requestedModel??t.resolvedModel})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Location"}),e.jsx("dd",{children:t.location?.label??"No location"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Destination"}),e.jsx("dd",{children:t.scope?.label??"Whole site"})]})]}),t.template&&e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:_t.templateProvenance}),e.jsxs("dl",{className:"mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Saved pattern"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.template})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Names used"}),e.jsx("dd",{children:Object.entries(t.template.bindings).map(([i,c])=>`${i}: ${c}`).join(" · ")||"No variables"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Original resolved text"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.output})]})]}),e.jsx("p",{className:"mt-2",children:"The queries below are the final text sent to the answer engine, including any edits."}),e.jsxs("p",{className:"mt-2 font-mono text-xs",children:[t.template.templateId," · ",t.template.templateVersion]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:_t.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:_t.methodology})]})]}),t?e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Class"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Brand-name match"}),e.jsx("th",{children:"Project domain cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:l?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>r(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(Ne,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?_t.brandedQuery:i.queryClass==="non-brand"?_t.discoveryQuery:_t.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(Ne,{tone:df(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(Ne,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===Nn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===Nn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(Ne,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===Nn.failed?"negative":"caution",children:i.citationState===null?i.status===Nn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(of,{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 of({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})]}),!oe()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(Ye,{type:"button",size:"sm",onClick:()=>a({researchRunQueryId:t.id,scope:n}),children:"Review for tracking"}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Only this saved query text enters tracking review. Its answer remains research evidence."})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("div",{className:"mt-1",children:e.jsx(Ti,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===Nn.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(ki,{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 lf(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 cf(t){return t.length>8?t.slice(0,8):t}function Kc(t){return t===ha.completed?"positive":t===ha.partial?"caution":t===ha.failed?"negative":"neutral"}function df(t){return t===Nn.completed?"positive":t===Nn.failed?"negative":"neutral"}async function uf(t){await $t(t,"researchRuns")}const yi=new Set(["queued","seeding","probing"]);function mf({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:l={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d}){const{account:m}=nn(),[u,p]=o.useState("tracked"),[x,h]=o.useState("find"),[y,f]=o.useState(null),b=m?.role==="viewer"?Wl():null,N=dc(m?.role,b),L=uc(s??u,N),S=a??x,g=I=>{s===void 0&&p(I),n?.(I)},v=I=>{a===void 0&&h(I),r?.(I)},C=(I,A)=>{const w=A===void 0?{...l}:{...l,measurementScope:A?.kind??"project",measurementScopeKey:A?.key};f({...I,trackingSelection:w}),A!==void 0&&i?.({measurementScope:w.measurementScope,measurementScopeKey:w.measurementScopeKey}),g("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(pr,{active:L==="tracked",label:"Tracked",onClick:()=>g("tracked")}),N?e.jsx(pr,{active:L==="research",label:"Research",onClick:()=>g("research")}):null]}),e.jsx("div",{className:"mt-4",children:L==="tracked"?e.jsx(Mf,{projectName:t,selection:l,onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d,pendingTrackingSource:y,onPendingTrackingSourceHandled:()=>f(null)}):e.jsx(hf,{projectName:t,selection:l,mode:S,onModeChange:v,onReviewSavedSource:C,onSelectionChange:i,viewerResearchConfig:b})})]})}function pr({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 hf({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:l}){const{canWrite:i}=nn(),c=!i||n==="test",d=$e({...Ii({client:Y,path:{name:t}}),enabled:c,staleTime:6e4}),m=$e({...Yl({client:Y,path:{name:t}}),enabled:c,staleTime:6e4}),u=o.useMemo(()=>{const h=d.data;if(!h)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const y=new Map(h.targets.map(b=>[b.stableKey,[]]));for(const b of h.groups)for(const N of b.targetKeys)y.get(N)?.push(b.stableKey);const f=new Map(h.markets.map(b=>[b.stableKey,new Set]));for(const b of h.markets)for(const N of b.usageEdges)for(const k of y.get(N.targetKey)??[])f.get(b.stableKey)?.add(k);return[{id:"project",label:"Whole site",kind:"project",targetCount:h.targets.length},...h.groups.map(b=>({id:b.stableKey,label:b.label,kind:"group",targetCount:b.targetKeys.length,...b.parentGroupKey?{parentGroupIds:[b.parentGroupKey]}:{}})),...h.markets.map(b=>{const N=[...f.get(b.stableKey)??[]];return{id:b.stableKey,label:b.label,kind:"market",targetCount:0,...N.length?{parentGroupIds:N}:{}}}),...h.targets.map(b=>({id:b.stableKey,label:b.label,kind:"property",targetCount:1,...y.get(b.stableKey)?.length?{parentGroupIds:y.get(b.stableKey)}:{}}))]},[d.data]),p=o.useMemo(()=>(m.data?.templates??[]).map(h=>({id:h.id,version:h.updatedAt,label:h.name,pattern:h.pattern,variables:h.variables})),[m.data]),x={projectName:t,scopeOptions:u,planRevision:d.data?.active?.revision??null,selectedScope:(()=>{const h=u.find(f=>f.kind===s.measurementScope&&f.id===s.measurementScopeKey),y=d.data?.active?.revision;return h&&y&&(h.kind==="market"||h.kind==="property")?{kind:h.kind,key:h.id,label:h.label,planRevision:y,expectedPlanRevision:y}:(s.measurementScope==="market"||s.measurementScope==="property")&&s.measurementScopeKey?{kind:s.measurementScope,key:s.measurementScopeKey,label:s.measurementScopeKey,planRevision:y??0,expectedPlanRevision:y??0}:null})(),scopePending:d.isPending||d.isFetching,scopeError:d.isError,onRetryScope:()=>{d.refetch()},templates:p};return i?e.jsxs("div",{children:[e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(pr,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(pr,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(Lf,{projectName:t,onReviewDiscoveryProbe:h=>r({source:"discovery",discoveryProbeId:h})}):e.jsx(tl,{...x,onReviewForTracking:({researchRunQueryId:h,scope:y})=>r({source:"research",researchRunQueryId:h},y??null)})})]}):e.jsx(tl,{...x,viewerResearchConfig:l})}function pf({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:c,preview:d,isPreviewing:m,isCommitting:u,onPreview:p,onCommit:x}){const[h,y]=o.useState(null),[f,b]=o.useState(()=>rr(s)),[N,k]=o.useState(null),L=o.useRef(null),S=o.useRef(null),g=mc(t,s),v=o.useMemo(()=>yf(t.tracked,s,t.mode),[s,t.mode,t.tracked]),C=wn({rows:v,getSearchText:z=>`${z.queryText} ${z.provenance?.source??"legacy"} ${z.assignments.map(ne=>ne.queryClass??"unknown").join(" ")}`});o.useEffect(()=>{if(g)return;if(!a){S.current=null;return}const z=`${a}:${_r(s)}`;if(S.current===z)return;const ne=t.tracked.find(F=>F.queryId===a);ne&&(S.current=z,y({kind:"edit",row:ne,audience:t.mode==="advanced"?Gr(s):void 0,scopeLabel:Kr(s,t)}),b(sl(ne,s)),k(null))},[s,a,g,t]),o.useEffect(()=>{if(g||!l)return;const z=rr(l.trackingSelection??s);y({kind:"add"}),b(l.source==="research"?{...z,source:"research",researchRunQueryId:l.researchRunQueryId}:{...z,source:"discovery",discoveryProbeId:l.discoveryProbeId}),k(null),i()},[i,l,s,g]),o.useEffect(()=>{g&&(y(null),k(null),a!==void 0&&r?.(void 0))},[r,a,g]),o.useEffect(()=>{if(!h||h.kind==="remove")return;const z=L.current;z&&(z.scrollIntoView?.({block:"start"}),z.focus({preventScroll:!0}))},[h]);function I(z="manual"){y({kind:"add"}),b({...rr(s),source:z}),k(null),r?.(void 0)}function A(z){S.current=`${z.queryId}:${_r(s)}`,y({kind:"edit",row:z,audience:t.mode==="advanced"?Gr(s):void 0,scopeLabel:Kr(s,t)}),b(sl(z,s)),k(null),r?.(z.queryId)}function w(z){S.current=`${z.queryId}:${_r(s)}`,y({kind:"remove",row:z,audience:t.mode==="advanced"?Gr(s):void 0,scopeLabel:Kr(s,t)}),k(null),r?.(z.queryId)}function V(){y(null),k(null),r?.(void 0)}const G=h?xf(h,f,t.mode):null,Q=h!==null&&h.kind==="add"&&t.mode==="advanced"&&!Gi(f),B=G!==null&&(!Q||f.contexts.length>0)&&!m;return g?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(P,{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(bf,{selection:s,onSelectionChange:n}):null,e.jsx(Js,{value:C.query,onChange:C.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!oe()&&e.jsxs(Ye,{type:"button",size:"sm",onClick:()=>I(),children:[e.jsx(Zh,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[C.totalRows.toLocaleString("en-US")," saved query ",C.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."}),C.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:C.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:C.rows.map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:z.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(jf,{row:z,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(wf,{row:z})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:vf(z)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Sf,{row:z,outsidePlan:t.mode==="advanced"&&z.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!oe()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${z.queryText}`,onClick:()=>A(z),children:[e.jsx(ep,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${z.queryText}`,onClick:()=>w(z),children:[e.jsx(cc,{"aria-hidden":"true",size:13})," Remove"]})]})})]},z.queryId))})]})}),e.jsx(Ks,{page:C.page,pageSize:C.pageSize,visibleRows:C.rows.length,totalRows:C.totalRows,itemLabel:"queries",onPageChange:C.setPage})]}),h&&!oe()&&e.jsx(Cf,{workspace:t,templates:c,action:h,draft:f,onDraftChange:z=>{b(z),k(null)},onClose:V,canReview:B,isPreviewing:m,editorHeadingRef:L,onReview:()=>{G&&(k(G),p(G))}}),d&&N&&h&&e.jsx(Pf,{preview:d,workspace:t,isCommitting:u,onConfirm:()=>{x({...N,expectedWorkspaceVersion:d.workspaceVersion,previewToken:d.previewToken,reviewedAt:d.reviewedAt})}})]})}function rr(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 sl(t,s){return{...rr(s),text:t.queryText,queryClass:"keep"}}function xf(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=gf(s);if(!a||bi(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=ff(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!Gi(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function gf(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 ff(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 Gi(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function bi(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function Gr(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 Kr(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 Ki(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 yf(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=>Ki(r,s)))}function bf({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 _r(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function vf(t){switch(t.provenance?.source){case"manual":return"Manual";case"template":return"Template";case"research":return"Saved research";case"discovery":return"Discovery";default:return"Legacy"}}function _c(t,s,n){const a=new Map(s.targets.map(f=>[f.stableKey,f.label])),r=new Map(s.groups.map(f=>[f.stableKey,f.label])),l=new Map(s.markets.map(f=>[f.stableKey,f.label])),i=new Set(t.assignments.map(f=>f.targetKey));if(i.size===0)return"Whole site";const c=n?t.assignments.filter(f=>Ki(f,n)):t.assignments,d=new Set(c.map(f=>f.targetKey));if(n?.measurementScope==="group"){const f=d.size,b=Math.max(0,i.size-f);return[`${f} ${f===1?"property":"properties"} in this group`,...b?[`Shared with ${b} other ${b===1?"property":"properties"}`]:[]].join(" · ")}const m=new Set,u=new Set;for(const f of c)f.groupKeys.forEach(b=>m.add(b)),f.marketKeys.forEach(b=>u.add(b));const x=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`],h=m.size===1?r.get([...m][0])??[...m][0]:null,y=u.size===1?l.get([...u][0])??[...u][0]:null;return h&&y&&h===y?x.push(`${h} (group and market)`):(h?x.push(`Group: ${h}`):m.size>1&&x.push(`${m.size} groups`),y?x.push(`Market: ${y}`):u.size>1&&x.push(`${u.size} markets`)),x.join(" · ")}function jf({row:t,workspace:s,selection:n}){const a=Nf(t,s,n);return e.jsxs("details",{className:"group min-w-48",children:[e.jsx("summary",{className:"cursor-pointer rounded px-1 py-1 text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:_c(t,s,n)}),e.jsxs("div",{className:"mt-2 rounded border border-default bg-surface p-2 text-xs leading-5 text-secondary",children:[e.jsx("p",{className:"font-medium text-strong",children:"Assigned relationships"}),e.jsx("ul",{className:"mt-1 list-disc space-y-1 pl-4",children:a.map(r=>e.jsx("li",{children:r},r))})]})]})}function Nf(t,s,n){const a=new Map(s.targets.map(d=>[d.stableKey,d.label])),r=new Map(s.groups.map(d=>[d.stableKey,d.label])),l=new Map(s.markets.map(d=>[d.stableKey,d.label])),c=t.assignments.filter(d=>Ki(d,n)).map(d=>{const m=a.get(d.targetKey)??d.targetKey??"Whole site",u=n.measurementScope==="group"&&n.measurementScopeKey?d.groupKeys.filter(x=>x===n.measurementScopeKey).map(x=>r.get(x)??x):d.groupKeys.map(x=>r.get(x)??x),p=n.measurementScope==="market"&&n.measurementScopeKey?d.marketKeys.filter(x=>x===n.measurementScopeKey).map(x=>l.get(x)??x):d.marketKeys.map(x=>l.get(x)??x);return[m,u.length?`Groups: ${u.join(", ")}`:null,p.length?`Markets: ${p.join(", ")}`:null].filter(x=>x!==null).join(" · ")});return[...new Set(c)].length?[...new Set(c)]:["Whole site"]}function wf({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(Ne,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function Sf({row:t,outsidePlan:s=!1}){return s?e.jsx(Ne,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(Ne,{tone:"positive",children:"Measured"}):e.jsx(Ne,{tone:"caution",children:"Awaiting sweep"})}function Cf({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:l,canReview:i,isPreviewing:c,editorHeadingRef:d,onReview:m}){const u=s.length>0;return n.kind==="remove"?e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Remove query"}),e.jsxs("p",{className:"mt-1 text-sm leading-6 text-secondary",children:["Remove “",n.row.queryText,"” from future tracking?"]}),e.jsxs("p",{className:"mt-1 text-sm leading-5 text-secondary",children:[n.audience?`Only assignments in ${n.scopeLabel} will be removed.`:"All assignments will be removed."," Earlier results stay unchanged."]})]})}),e.jsx(Ur,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]}):n.kind==="edit"?e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Edit query"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("p",{className:"mt-3 text-sm leading-6 text-secondary",children:[n.audience?`Changes apply only to assignments in ${n.scopeLabel}.`:"Changes apply to every assignment of this query."," Earlier results stay unchanged."]}),e.jsxs("div",{className:"mt-4 max-w-2xl space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Query text"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.text,onChange:p=>r({...a,text:p.target.value})})]}),t.mode==="advanced"&&e.jsxs("label",{className:"block",htmlFor:"tracking-query-class",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:p=>r({...a,queryClass:p.target.value}),children:[e.jsx("option",{value:"keep",children:"Keep existing classifications"}),e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Existing locations and engines are preserved. Use Add query to create assignments in another scope."})]}),e.jsx(Ur,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]}):e.jsxs(je,{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(P,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-[minmax(250px,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[a.source==="manual"?e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Question"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",placeholder:"e.g. How do teams compare AEO platforms?",value:a.text,onChange:p=>r({...a,text:p.target.value})})]}):null,a.source==="template"?e.jsx(kf,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(nl,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(p=>({id:p.researchRunQueryId,label:p.queryText,detail:p.researchRunId})),onChange:p=>r({...a,researchRunQueryId:p})}):null,a.source==="discovery"?e.jsx(nl,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(p=>({id:p.discoveryProbeId,label:p.queryText,detail:p.discoverySessionId})),onChange:p=>r({...a,discoveryProbeId:p})}):null,e.jsxs("label",{className:"block",htmlFor:"tracking-query-source",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Query source"}),e.jsxs("select",{id:"tracking-query-source","aria-describedby":u?void 0:"tracking-query-source-no-templates",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.source,onChange:p=>r({...a,source:p.target.value}),children:[e.jsx("option",{value:"manual",children:"Write a question"}),u?e.jsx("option",{value:"template",children:"Saved template"}):null,e.jsxs("option",{value:"research",disabled:t.savedSources.research.length===0,children:["Saved research",t.savedSources.research.length===0?" (none available)":""]}),e.jsxs("option",{value:"discovery",disabled:t.savedSources.discovery.length===0,children:["Discovery result",t.savedSources.discovery.length===0?" (none available)":""]})]})]}),u?null:e.jsx("p",{id:"tracking-query-source-no-templates",className:"text-sm leading-6 text-secondary",children:"No saved templates are set up for this portfolio. Write a question, or use saved research or a discovery result."})]}),e.jsx(Rf,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!Gi(a)?e.jsx("div",{className:"mt-4",children:e.jsx(Af,{workspace:t,draft:a,onDraftChange:r})}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Measurement options"}),e.jsx("div",{className:"grid gap-4 pb-3 sm:grid-cols-2",children:t.mode==="advanced"?e.jsxs("div",{className:"block",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",htmlFor:"tracking-query-class",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:p=>r({...a,queryClass:p.target.value}),children:[e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}):e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:"Automatic"})]})})]}),a.source==="research"&&e.jsx("p",{className:"mt-4 rounded-md border border-default bg-surface-subtle px-3 py-2 text-sm text-secondary",children:"Only the saved query is added."}),e.jsx(Ur,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]})}function kf({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":bi(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]}),bi(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 nl({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 _i(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function da(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 Uc(t){return[...new Map(t.map(s=>[da(s),s])).values()]}function Ui(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 Af({workspace:t,draft:s,onDraftChange:n}){const a=o.useMemo(()=>Uc([...t.defaultContexts.map(_i),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?da(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=>da(d)===l.target.value),c=l.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:c})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(l=>e.jsx("option",{value:da(l),children:Ui(l)},da(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 Rf({workspace:t,draft:s,onDraftChange:n}){const[a,r]=o.useState(""),[l,i]=o.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),c=o.useMemo(()=>[...t.targets.map(h=>({kind:"target",key:h.stableKey,label:h.label,detail:"Property"})),...t.groups.map(h=>({kind:"group",key:h.stableKey,label:h.label,detail:"Group"})),...t.markets.map(h=>({kind:"market",key:h.stableKey,label:h.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),d=a.trim().toLocaleLowerCase(),m=d?c.filter(h=>`${h.label} ${h.detail}`.toLocaleLowerCase().includes(d)):c,u=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function p(h,y,f){const b=h==="target"?"targetKeys":h==="group"?"groupKeys":"marketKeys",N=s[b];n({...s,wholeSite:!1,[b]:f?[...N,y]:N.filter(k=>k!==y)})}function x(h,y){return(h==="target"?s.targetKeys:h==="group"?s.groupKeys:s.marketKeys).includes(y)}if(!l){const h=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: ",h?.label??s.targetKeys[0]]}),e.jsx(P,{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:h=>{n({...s,wholeSite:h.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(Js,{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(h=>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":`${h.label}, ${h.detail}`,checked:x(h.kind,h.key),onChange:y=>p(h.kind,h.key,y.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:h.label}),e.jsx("span",{className:"text-xs text-muted",children:h.detail})]},`${h.kind}:${h.key}`))})]})}function Ur({canReview:t,isPreviewing:s,onCancel:n,onReview:a}){return e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[e.jsx(Ye,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(P,{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 Pf({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=o.useRef(null);o.useEffect(()=>{const c=r.current;c&&(typeof c.scrollIntoView=="function"&&c.scrollIntoView({block:"start"}),c.focus({preventScroll:!0}))},[t]);const l=!t.diff.noOp,i=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(c=>c.rows.length>0);return e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{ref: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(Ne,{tone:l?"caution":"neutral",children:l?"Ready to confirm":"No-op"})]}),i.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:i.map(c=>e.jsx(al,{label:c.label,rows:c.rows,workspace:s,tracked:t.tracked},c.label))}):null,t.diff.unchanged.length>0?e.jsxs("details",{className:"mt-4 border-t border-default pt-2 text-sm text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3",children:[t.diff.unchanged.length," unchanged ",t.diff.unchanged.length===1?"query":"queries"]}),e.jsx(al,{label:"Unchanged",rows:t.diff.unchanged,workspace:s,tracked:t.tracked})]}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Next sweep workload"}),e.jsxs("p",{className:"leading-6",children:["Next sweep: ",t.workload.nextSweepProviderCalls," provider requests (+",t.workload.addedProviderCalls,", −",t.workload.removedProviderCalls,")."]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:e.jsx(Ye,{type:"button",size:"sm",disabled:!l||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function al({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`:Tf(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(If,{row:a.find(l=>l.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function If({row:t,workspace:s}){if(!t?.assignments.length)return null;const n=new Set(t.assignments.map(a=>a.targetKey)).size;return e.jsxs("details",{className:"mt-2 text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:["Classifications · ",n," ",n===1?"property":"properties"]}),e.jsx("ul",{className:"mt-1 max-h-40 space-y-1 overflow-y-auto",children:t.assignments.map((a,r)=>{const l=s.targets.find(d=>d.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",c=a.contexts.map(d=>Ui(_i(d))).join("; ");return e.jsx("li",{children:[l,i,c].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function Tf(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=Uc(a.assignments.flatMap(i=>i.contexts).map(_i)),l=r.length===1?Ui(r[0]):r.length>1?`${r.length} contexts`:null;return[_c(a,n),l].filter(i=>i!==null).join(" · ")}function Mf({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i}){const c=hs(),[d,m]=o.useState(null),u=$e({...Ii({client:Y,path:{name:t}})}),p=$e({...Yl({client:Y,path:{name:t}}),staleTime:6e4}),x=Et({...vu(),onSuccess:y=>m(y),onError:async y=>{m(null),await c.invalidateQueries({queryKey:bu({client:Y,path:{name:t}})}),De({title:"Could not review tracking changes",detail:y instanceof Error?y.message:"Update the draft and review it again.",tone:"negative"})}}),h=Et({...ju(),onSuccess:async y=>{m(null),r?.(void 0),await io(c,t),De({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 io(c,t),De({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(je,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):u.isError||!u.data?e.jsxs(je,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{u.refetch()},children:"Try again"})]}):e.jsx(pf,{workspace:u.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:p.data?.templates??[],preview:d,isPreviewing:x.isPending,isCommitting:h.isPending,onPreview:y=>{m(null),x.mutate({client:Y,path:{name:t},body:{...y,expectedWorkspaceVersion:u.data.workspaceVersion}})},onCommit:y=>h.mutate({client:Y,path:{name:t},body:y})})}function Lf({projectName:t,onReviewDiscoveryProbe:s}){const n=hs(),[a,r]=o.useState(null),[l,i]=o.useState(""),[c,d]=o.useState("100"),m=$e({...Nu({client:Y,path:{name:t},query:{limit:"10"}}),refetchInterval:k=>k.state.data?.some(S=>yi.has(S.status))?3e3:!1}),u=m.data??[];o.useEffect(()=>{!a&&u[0]&&r(u[0].id)},[a,u]);const p=u.find(k=>k.id===a)??null,x=$e({...wu({client:Y,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:p&&yi.has(p.status)?3e3:!1}),h=x.data??null,y=Et({mutationFn:()=>{const k={},L=l.trim();L&&(k.icpDescription=L);const S=Number.parseInt(c,10);return Number.isFinite(S)&&S>0&&(k.maxProbes=S),Su(t,k)},onSuccess:async k=>{r(k.sessionId),i(""),await Df(n,t,k.sessionId),De({title:"Discovery started",detail:`Run ${Br(k.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${k.sessionId}`,dedupeMode:"replace"})},onError:k=>{De({title:"Discovery failed to start",detail:k instanceof Error?k.message:"Could not start discovery.",tone:"negative"})}}),f=h??p,b=o.useMemo(()=>(h?.probes??[]).slice(0,30),[h?.probes]);async function N(){try{const k=await m.refetch();if(k.error)throw k.error;const L=k.data?.length??0;De({title:"Discovery sessions refreshed",detail:`${L} recent session${L===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(k){De({title:"Discovery refresh failed",detail:k instanceof Error?k.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:oe()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{N()},children:[e.jsx(ba,{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(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(Ne,{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:k=>i(k.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:c,onChange:k=>d(k.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."})]}),!oe()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:y.isPending,onClick:()=>y.mutate(),children:[e.jsx(lr,{size:14}),y.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),m.isFetching&&e.jsx(Ne,{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(k=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===k.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(k.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:Br(k.id)}),e.jsx(Ne,{tone:rl(k.status),children:k.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",k.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",k.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",k.wastedCount??0]})]})]},k.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:f?Br(f.id):"No run selected"})]}),f&&e.jsx(Ne,{tone:rl(f.status),children:f.status})]}),f?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Va,{label:"Questions tested",value:f.probeCount??0}),e.jsx(Va,{label:"Cited queries",value:f.citedCount??0,tone:"positive"}),e.jsx(Va,{label:"Worth tracking",value:f.aspirationalCount??0,tone:"caution"}),e.jsx(Va,{label:"Skip",value:f.wastedCount??0,tone:"negative"})]}),f.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:f.error}),f.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:f.warning}),f.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:f.icpDescription})]}),f.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:f.competitorMap.slice(0,8).map(k=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[k.domain," ",e.jsx("span",{className:"text-muted",children:k.hits})]},k.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),f?.status==="completed"&&e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Review a discovery question for tracking"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:"Choose a Cited query or Worth tracking result below. Tracking opens with the saved discovery source, where you choose its scope and review the exact next-sweep change."})]})}),e.jsx("p",{className:"mt-3 text-xs leading-5 text-muted",children:"Discovery remains research. This review does not add competitors or start a sweep."})]}),e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),x.isFetching&&e.jsx(Ne,{tone:"neutral",children:"Loading"})]}),b.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Tracking review"})})]})}),e.jsx("tbody",{children:b.map(k=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:k.query}),e.jsx("td",{children:e.jsx(Ne,{tone:$f(k.bucket),children:Ef(k.bucket)})}),e.jsx("td",{className:"text-secondary",children:k.citedDomains.length>0?k.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!oe()&&s&&(k.bucket==="cited"||k.bucket==="aspirational")&&e.jsx(Ye,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(k.id),children:"Review for tracking"})})]},k.id))})]})})]})]})]})]})}function Va({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 rl(t){return t==="completed"?"positive":t==="failed"?"negative":yi.has(t)?"caution":"neutral"}function $f(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const qf={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Ef(t){return t?qf[t]:"Not classified"}function Br(t){return t.length>8?t.slice(0,8):t}async function Df(t,s,n){await Promise.all([$t(t,"discovery"),t.invalidateQueries({queryKey:Cu({client:Y})})])}function Of({projectName:t}){const[s,n]=o.useState("changes"),[a,r]=o.useState(null),[l,i]=o.useState(null),c=$e({...ku({client:Y,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=$e({...Au({client:Y,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),m=(d.data??[]).filter(b=>(b.status==="completed"||b.status==="partial")&&b.trigger!=="probe").reverse(),u=l??m[0]?.id??"",p=a??m.find(b=>b.id!==u)?.id??"",x=!!(p&&u&&p!==u),h=$e({...Ru({client:Y,path:{name:t},query:{run1:p,run2:u}}),enabled:s==="compare"&&x}),y=c.data??[],f=h.data?.diff.filter(b=>b.changed||b.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([b,N])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===b,className:`filter-chip ${s===b?"filter-chip-active":""}`,onClick:()=>n(b),children:N},b))}),s==="changes"?e.jsx(op,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),c.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!c.isLoading&&y.length===0?e.jsxs(je,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:ds()?zn:"Complete an answer visibility sweep to create the first snapshot."})]}):null,y.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:y.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(b.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.mentionedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:et(b.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.citedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:et(b.overallCitedRate)})]},b.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:p,onChange:b=>r(b.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:m.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:u,onChange:b=>i(b.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:m.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]})]}),d.isLoading||h.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!d.isLoading&&m.length<2?e.jsxs(je,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:ds()?zn:"Run another answer visibility sweep before comparing historical evidence."})]}):null,h.data&&f.length===0?e.jsxs(je,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,f.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:f.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:b.query??"Archived query"}),e.jsx("td",{children:e.jsxs(Ne,{tone:b.changed?"caution":"neutral",children:[b.run1State??"none"," → ",b.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(Ne,{tone:b.visibilityChanged?"caution":"neutral",children:[b.run1MentionState??"none"," → ",b.run2MentionState??"none"]})})]},b.queryId??b.query??"unknown"))})]})}):null]}):null]})}const il={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},Ff={contract:null,assessment:null,googleAds:il,gtm:il,snapshots:[]};function Gf(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Bf(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Kf(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 _f(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 Uf(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 Bc(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"&&Vf(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 Bf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Vf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Vc(t){switch(t){case"connected":return{label:"Connected",tone:"positive"};case"stale":return{label:"Needs refresh",tone:"caution"};case"selection-required":return{label:"Selection needed",tone:"caution"};case"not-connected":return{label:"Not connected",tone:"neutral"};case"unavailable":return{label:"Unavailable",tone:"negative"}}}function zf(t,s){return t==="configured"?s==="not-configured"||s==="contract-selection-required"?"neutral":"positive":t==="static"?s==="assessment-unavailable"?"negative":s==="assessment-loading"?"neutral":s==="static-mismatch"?"negative":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"positive":s==="configured"?"caution":"neutral":s==="observed"?"positive":s==="runtime-unverified"?"caution":"neutral"}function Qf(t,s){return t==="configured"?s==="not-configured"?"Not declared":s==="contract-selection-required"?"Choose conversion":"Declared":t==="static"?s==="assessment-unavailable"?"Unavailable":s==="assessment-loading"?"Checking":s==="static-mismatch"?"Mismatch":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"Consistent":s==="configured"?"Needs review":"Not checked":s==="observed"?"Observed":s==="runtime-unverified"?"Not observed":"Not checked"}function xn(t){return t.length<=12?t:`…${t.slice(-10)}`}function Hf(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 Wf(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 Vr={"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 ol(t){return t.outcome==="pass"?{label:Vr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Vr[t.code],tone:"negative",outcome:"Fail"}:{label:Vr[t.code],tone:"caution",outcome:"Unknown"}}function Yf(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Jf(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 Xf(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function ll({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const l=Vc(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(Ne,{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 ${Jt(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const Zf="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.",ey="Available once Google Ads and Tag Manager are connected.",ty="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 sy({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:l}){const i=t.googleAds.state==="connected",c=t.gtm.state==="connected",d=t.googleAds.state==="unavailable",m=t.gtm.state==="unavailable",u=d||m||t.gtm.state==="unavailable",p={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},x=!i&&!c,h=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:d?p:_f(t)},{title:"Tag Manager",state:t.gtm.state,ready:c,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:m?p:Uf(t)}],y=i&&c&&!u?Bc(t):null;return e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("h2",{id:"conversion-integrity-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx(Oe,{text:"Canonry reads your Google configuration and never changes or publishes it. Connect Google Ads and Tag Manager, then choose one website conversion to check across both."})]}),x?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:ty}):null]})}),e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-y border-default py-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Conversion to check"}),e.jsx(Oe,{text:Zf})]}),y&&s?e.jsx(Ye,{type:"button",disabled:r,onClick:()=>s(y.id),children:r?"Working…":y.label}):e.jsx("p",{className:"text-sm text-secondary",children:ey})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:h.map(f=>{const b=f.ready?{label:"Ready",tone:"positive"}:Vc(f.state),N=f.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:f.title}),e.jsx(Ne,{tone:b.tone,children:b.label}),f.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:f.summary}):null,N&&s?N.id==="retry-connection-status"?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(N.id),children:r?"Working…":N.label}):e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(N.id),children:r?"Working…":N.label}):null,f.summary&&f.onChange?e.jsx(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":f.changeLabel,disabled:r,onClick:f.onChange,children:"Change"}):null]},f.title)})}),l?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:l}):null]})]})}function ny({workspace:t=Ff,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:l=null,onSelectContract:i,contractError:c=null,onRetryContracts:d,onRetryEvidence:m,onChangeGoogleAdsSelection:u,onChangeGtmSelection:p,onAddContract:x}){const h=Gf(t),y=Kf(h),f=Bc(t),b=t.assessment?.findings??[],N=b.filter(g=>g.outcome!=="pass"),k=b.filter(g=>g.outcome==="pass"),L=N.some(g=>g.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&c===null?e.jsx(sy,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:u,onChangeGtmSelection:p,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ne,{tone:y.tone,children:y.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Jt(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(g=>e.jsxs("li",{className:"break-words",children:[Xf(g)," ",g.kind,", captured ",Jt(g.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",g.id,")"]})]},g.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?f.id==="review-findings"||f.id==="review-runtime-verification"||f.id==="retry-connection-status"||f.id==="select-contract"||f.id==="retry-integrity"||f.id==="waiting-for-integrity"?e.jsx(P,{type:"button",disabled:n||f.id==="waiting-for-integrity",onClick:()=>s(f.id),children:n?"Working…":f.label}):e.jsx(Ye,{type:"button",disabled:n,onClick:()=>s(f.id),children:n?"Working…":f.label}):f.id==="review-findings"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):h==="runtime-unverified"?e.jsx(P,{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:f.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&&x?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:x,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:g=>i?.(g.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(g=>e.jsx("option",{value:g.id,children:g.name},g.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:Hf(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:Wf(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:xn(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:xn(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:xn(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:xn(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),c?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:c}),d?e.jsx(P,{type:"button",variant:"outline",onClick:d,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),N.length>0?e.jsxs("section",{id:"conversion-integrity-findings",tabIndex:-1,className:"page-section-divider","aria-labelledby":"conversion-integrity-findings-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Assessment findings"}),e.jsx("h3",{id:"conversion-integrity-findings-title",className:"text-base font-semibold text-heading",children:"Checks to review"})]}),e.jsxs(Ne,{tone:L,children:[N.length," ",N.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:N.map(g=>{const v=ol(g);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:v.label}),e.jsx(Ne,{tone:v.tone,children:v.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",g.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",g.code]}),g.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",g.evidenceIds.join(", ")]}):null]},`${g.code}:${g.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(Oe,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(g=>{const v=zf(g.key,h);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${v==="positive"?"bg-positive-fill":v==="caution"?"bg-caution-fill":v==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:g.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:g.detail}),e.jsx(Ne,{tone:v,children:Qf(g.key,h)})]},g.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:[ll({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:u}:{},actionPending:n}),ll({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:p}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&m?e.jsx(P,{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(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:g.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:g.kind}),e.jsx("td",{className:"text-secondary",children:Jt(g.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:xn(g.id)})]},g.id))})]})})]}):null,k.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[k.length," ",k.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:k.map(g=>{const v=ol(g);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:v.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",g.code]}),g.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",g.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(Ne,{tone:v.tone,children:v.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:g.subject})]},`${g.code}:${g.subject}`)})})]})})]}):null,h==="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 ",Yf(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:xn(t.contract.gtm.tagId)})," fires with ",Jf(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:xn(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const gn=3e4,cl={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Kt="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",ls="text-sm font-medium text-secondary";function dl(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:St(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function za(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function ay(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 ry(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function iy(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:ry(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 oy(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:za(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:za(t.triggerIds),variableIds:za(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:za(t.productionHosts)}}}function ul(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 Qa(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 Ha(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Wa({id:t,label:s,value:n,onChange:a,children:r,disabled:l=!1}){return e.jsxs("label",{htmlFor:t,className:ls,children:[s,e.jsx("select",{id:t,className:Kt,value:n,onChange:i=>a(i.target.value),disabled:l,children:r})]})}function qn({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 ml({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1),[c,d]=o.useState(null),m=o.useRef(null),u=o.useRef(null),p=o.useRef(!1);o.useEffect(()=>{const f=p.current;p.current=a,a?u.current?.focus():f&&m.current?.querySelector("button")?.focus()},[a]);function x(){d(null),r(!0)}function h(){d(null),r(!1)}async function y(){i(!0),d(null);try{await n()}catch(f){d(St(f)),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(P,{ref:u,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:l,onClick:h,children:"Keep connected"}),e.jsx(Ye,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||l,onClick:()=>{y()},children:l?"Disconnecting…":`Disconnect ${t}`})]}),c?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:c}):null]}):e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:x,children:["Disconnect ",t]})})}function hl({id:t,label:s,options:n,synced:a,loading:r,failed:l,onRetry:i,emptyHint:c,value:d,onChange:m}){const u=n.some(f=>f.id===d),[p,x]=o.useState(!1),h=p||d!==""&&!u&&n.length>0,y=e.jsx("label",{htmlFor:t,className:ls,children:s});return r?e.jsxs("div",{children:[y,e.jsx("select",{id:t,className:Kt,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):l?e.jsxs("div",{children:[y,e.jsx("input",{id:t,required:!0,className:Kt,value:d,onChange:f=>m(f.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:Kt,value:d,onChange:f=>m(f.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":c})]}):e.jsxs("div",{children:[y,h?e.jsx("input",{id:t,required:!0,className:Kt,value:d,onChange:f=>m(f.target.value)}):e.jsxs("select",{id:t,required:!0,className:Kt,value:d,onChange:f=>m(f.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(f=>e.jsxs("option",{value:f.id,children:[f.name,f.detail?` (${f.detail})`:"",f.active?"":" — inactive"]},f.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{x(!h),m("")},children:h?"Choose from synced list":"Enter an ID manually"})]})}function ly({projectId:t,projectName:s}){const n=nn(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),[m,u]=o.useState(""),[p,x]=o.useState(null),[h,y]=o.useState(!1),[f,b]=o.useState(!1),[N,k]=o.useState(""),[L,S]=o.useState(""),[g,v]=o.useState(""),[C,I]=o.useState(""),[A,w]=o.useState(""),[V,G]=o.useState(!1),[Q,B]=o.useState(cl),[z,ne]=o.useState(null),F=o.useRef(null),_=$e({...Pu({client:Y,path:{name:s}}),staleTime:gn}),Z=$e({...Iu({client:Y,path:{name:s}}),staleTime:gn}),$=$e({...Tu({client:Y,path:{name:s}}),staleTime:gn}),ee=$e({...Mu({client:Y,path:{name:s}}),staleTime:gn}),T=ee.data,E=$e({...Lu({client:Y,path:{name:s},query:{limit:5}}),staleTime:gn}),te=$e({...$u({client:Y,path:{name:s},query:{limit:5}}),staleTime:gn}),re=$.data??[],we=(z?re.find(q=>q.id===z)??null:null)??(re.length===1?re[0]??null:null),X=re.length>1&&!we,ue=$e({...qu({client:Y,path:{name:s,contractId:we?.id??""}}),enabled:!!we,staleTime:gn}),xe=$e({...Eu({client:Y,path:{name:s}}),enabled:p==="google-ads"&&_.data?.connected===!0,staleTime:0}),J=$e({...Du({client:Y,path:{name:s}}),enabled:p==="gtm"&&Z.data?.connected===!0,staleTime:0}),he=$e({...Ou({client:Y,path:{name:s,accountId:g}}),enabled:p==="gtm"&&!!g,staleTime:0}),K=$e({...Fu({client:Y,path:{name:s,accountId:g,containerId:C}}),enabled:p==="gtm"&&!!g&&!!C,staleTime:0}),pe=Et(Gu({client:Y})),qe=Et(Ku({client:Y})),Ae=Et(_u({client:Y})),ie=Et(Uu({client:Y})),fe=Et(Bu({client:Y})),Ce=Et(Vu({client:Y})),Ge=Et(zu({client:Y})),Ee=Et(Qu({client:Y})),O=Et(Hu({client:Y}));o.useEffect(()=>{if(p!=="google-ads"||h||!_.isSuccess)return;const q=_.data.connection?.selection;k(q?.customerId??""),S(q?.loginCustomerId??""),y(!0)},[h,_.data,_.isSuccess,p]),o.useEffect(()=>{if(p!=="gtm"||f||!Z.isSuccess)return;const q=Z.data.selection;v(q?.accountId??""),I(q?.containerId??""),w(q?.workspaceId??""),b(!0)},[f,Z.data,Z.isSuccess,p]),o.useEffect(()=>{!z||!$.data||$.data.some(q=>q.id===z)||ne(null)},[$.data,z]);const D=o.useMemo(()=>{const q=E.data?.snapshots??[],Se=te.data?.snapshots??[],st=[...q.map(wt=>({id:wt.id,provider:"google-ads",kind:wt.kind,capturedAt:wt.capturedAt})),...Se.map(wt=>({id:wt.id,provider:"gtm",kind:wt.kind,capturedAt:wt.capturedAt}))].sort((wt,qs)=>qs.capturedAt.localeCompare(wt.capturedAt)).slice(0,5),qt=[],Ft=ue.data?.googleAdsSnapshot,Be=ue.data?.gtmSnapshot;return Ft&&qt.push({id:Ft.id,provider:"google-ads",kind:Ft.kind,capturedAt:Ft.capturedAt}),Be&&qt.push({id:Be.id,provider:"gtm",kind:Be.kind,capturedAt:Be.capturedAt}),{contract:ue.data?.assessment.contract??we,assessment:ue.data?.assessment??null,contractSelectionRequired:X,assessmentState:we?ue.isError?"unavailable":ue.isLoading?"loading":void 0:void 0,assessmentError:ue.isError?St(ue.error):null,googleAds:ay(_.data,dl(E.data?.total??0,E.isLoading,E.isError,E.error),_.isError),gtm:iy(Z.data,dl(te.data?.total??0,te.isLoading,te.isError,te.error),Z.isError),snapshots:st,assessmentEvidenceSnapshots:qt}},[we,X,E.data,E.error,E.isError,E.isLoading,_.data,_.isError,te.data,te.error,te.isError,te.isLoading,Z.data,Z.isError,ue.data,ue.error,ue.isError,ue.isLoading]),H=o.useSyncExternalStore(_l,ir,ir),Me=Object.values(H.runs).some(q=>q.projectId===t&&(q.kind===Us["google-ads-sync"]||q.kind===Us["gtm-sync"])),Qe=pe.isPending||qe.isPending||Ae.isPending||ie.isPending||fe.isPending||Ce.isPending||Ge.isPending||Ee.isPending||O.isPending||Me;async function Fe(){await Promise.all([_.refetch(),Z.refetch(),$.refetch(),E.refetch(),te.refetch(),ee.refetch(),we?ue.refetch():Promise.resolve()])}async function tt(q){await Fe();for(let Se=0;Se<10&&!q();Se+=1)await new Promise(st=>setTimeout(st,1500)),await Fe()}function ge(){const q=document.activeElement;F.current=q instanceof HTMLElement?q:null}function vt(q){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(q);return}globalThis.setTimeout(q,0)}function Ve(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Je(q){if(!q)return;!q.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!q.hasAttribute("tabindex")&&(q.tabIndex=-1),q.focus({preventScroll:!0})}function Dt(q,Se=q){const st=document.getElementById(q);st instanceof HTMLDetailsElement&&(st.open=!0);const qt=st?.scrollIntoView;typeof qt=="function"&&qt.call(st,{behavior:Ve()?"auto":"smooth",block:"start"}),Je(document.getElementById(Se)??st)}function ct(q,Se){ge(),vt(()=>Dt(q,Se))}function at(){const q=F.current;F.current=null,q&&vt(()=>{q.isConnected&&q.focus({preventScroll:!0})})}function pt(){r(null),d(!1),at()}function Ct(){r(null),x(null),at()}function It(){r(null),G(!1),at()}function He(){r(null),x(null),d(!0),ct("google-ads-connect-panel","google-ads-connect-title")}function R(){r(null),k(""),S(""),y(!1),x("google-ads"),d(!1),ct("google-ads-selection-panel","google-ads-selection-title")}function Le(){r(null),v(""),I(""),w(""),b(!1),x("gtm"),d(!1),ct("gtm-selection-panel","gtm-selection-title")}function Pe(){r(null),G(!0),ct("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Ke(q,Se){Kl({id:q.id,projectId:q.projectId,kind:q.kind,projectLabel:s,sourceAction:Se}),De({title:Se==="google-ads-sync"?"Google Ads sync queued":"Tag Manager sync queued",detail:`${s} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`google-marketing-sync:${q.id}`,dedupeMode:"replace"})}async function dt(){Cs(n),r(null);try{const q=await pe.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."),ul(q.authorizationUrl,()=>{Fe(),i(null),at()})}catch(q){r(St(q))}}async function ze(){Cs(n),r(null);try{const q=await qe.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."),ul(q.authorizationUrl,()=>{Fe(),i(null),at()})}catch(q){r(St(q))}}async function yt(){if(Cs(n),!N){r("Select a Google Ads customer before saving.");return}r(null);try{await Ae.mutateAsync({path:{name:s},body:{customerId:N,...L.trim()?{loginCustomerId:L.trim()}:{}}}),x(null),at(),await tt(()=>_.data?.selectedCustomer!=null)}catch(q){r(St(q))}}async function se(){if(Cs(n),!g||!C){r("Select a Tag Manager account and container before saving.");return}r(null);try{await ie.mutateAsync({path:{name:s},body:{accountId:g,containerId:C,...A?{workspaceId:A}:{}}}),x(null),at(),await tt(()=>Z.data?.status==="connected")}catch(q){r(St(q))}}async function _e(){Cs(n),r(null),await Ge.mutateAsync({path:{name:s}}),x(null),d(!1),k(""),S(""),y(!1),i(null),await Fe(),De({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),F.current=null,vt(()=>Je(document.getElementById("conversion-integrity-title")))}async function Re(){Cs(n),r(null),await Ee.mutateAsync({path:{name:s}}),x(null),v(""),I(""),w(""),b(!1),i(null),await Fe(),De({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),F.current=null,vt(()=>Je(document.getElementById("conversion-integrity-title")))}async function ve(){Cs(n),r(null);try{const q=await fe.mutateAsync({path:{name:s}});Ke(q,"google-ads-sync")}catch(q){r(St(q))}}async function Tt(){Cs(n),r(null);try{const q=await Ce.mutateAsync({path:{name:s}});Ke(q,"gtm-sync")}catch(q){r(St(q))}}async function Xt(){Cs(n),r(null);try{const q=await Promise.allSettled([fe.mutateAsync({path:{name:s}}),Ce.mutateAsync({path:{name:s}})]),[Se,st]=q;Se.status==="fulfilled"&&Ke(Se.value,"google-ads-sync"),st.status==="fulfilled"&&Ke(st.value,"gtm-sync");const qt=q.find(Ft=>Ft.status==="rejected");if(qt?.status==="rejected")throw qt.reason}catch(q){r(St(q))}}async function Zt(){Cs(n);const q=_.data?.connection?.selection.customerId,Se=Z.data?.selection;if(!q||!Se?.accountId||!Se.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const st=await O.mutateAsync({path:{name:s},body:oy(Q,q,{accountId:Se.accountId,containerId:Se.containerId})});B(cl),G(!1),at(),(await $.refetch()).data?.some(Ft=>Ft.id===st.id)&&ne(st.id)}catch(st){r(St(st))}}function Ot(q){switch(q){case"connect-google-ads":He();return;case"connect-gtm":ge(),ze();return;case"select-google-ads":R();return;case"select-gtm":Le();return;case"sync-google-ads":ve();return;case"sync-gtm":Tt();return;case"sync-static-evidence":Xt();return;case"declare-contract":Pe();return;case"review-findings":ct("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":ct("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Fe();return;case"select-contract":ct("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ue.refetch();return;case"waiting-for-integrity":return}}const ut=xe.data?.customers??[],es=J.data?.accounts??[],it=he.data?.containers??[],gs=K.data?.workspaces??[],ps=!!N&&!ut.some(q=>q.customerId===N),Bs=!!g&&!es.some(q=>q.id===g),bt=!!C&&!it.some(q=>q.id===C),Vs=!!A&&!gs.some(q=>q.id===A),Mt=ps&&xe.isSuccess&&xe.data.truncated===!1,as=Bs&&J.isSuccess&&J.data.truncated===!1,Vt=bt&&he.isSuccess&&he.data.truncated===!1,xt=Vs&&K.isSuccess&&K.data.truncated===!1,ts=as||Vt||xt,zt=as?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Vt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":xt?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,fs=Ha(Mt,xe.data,xe.isError),Qt=Ha(as,J.data,J.isError),gt=Ha(Vt,he.data,he.isError),Lt=Ha(xt,K.data,K.isError),Nt=xe.isError?St(xe.error):null,ys=J.isError?St(J.error):he.isError?St(he.error):K.isError?St(K.error):null,bs=p==="google-ads"?Nt:p==="gtm"?ys:null,U=Qa("customer",xe.data,ut.length),ae=Qa("account",J.data,es.length),me=Qa("container",he.data,it.length),ce=Qa("draft workspace",K.data,gs.length),Ie=J.isError||he.isError||K.isError&&!!A,Ue=c||p!==null||V;function mt(){xe.refetch()}function kt(){if(J.isError){J.refetch();return}if(he.isError){he.refetch();return}K.isError&&K.refetch()}return _.isLoading||Z.isLoading||$.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(q=>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"})]},q))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):$.isError&&!$.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: ",St($.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{$.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ny,{workspace:D,onPrimaryAction:Ot,actionPending:Qe,actionError:Ue?null:a,contracts:re,selectedContractId:we?.id??null,onSelectContract:q=>ne(q||null),contractError:$.isError?St($.error):null,onRetryContracts:()=>{$.refetch()},onRetryEvidence:()=>{Promise.all([E.refetch(),te.refetch()])},onChangeGoogleAdsSelection:R,onChangeGtmSelection:Le,onAddContract:()=>Ot("declare-contract")}),l?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:l}):null,c?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:Ze(async q=>{q.preventDefault(),await dt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:ls,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:m,onChange:q=>u(q.target.value),className:Kt,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:pe.isPending,children:pe.isPending?"Starting…":"Continue to Google"}),e.jsx(P,{type:"button",variant:"outline",onClick:pt,children:"Cancel"})]})]})]}):null,p==="google-ads"?e.jsxs("section",{id:"google-ads-selection-panel",className:"page-section-divider","aria-labelledby":"google-ads-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select customer context"})]})}),bs?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:bs}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:mt,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Mt?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(Wa,{id:"google-ads-customer",label:"Customer account",value:N,onChange:q=>{y(!0),k(q);const Se=ut.find(st=>st.customerId===q);S(Se?.parentCustomerId??"")},disabled:xe.isLoading,children:[e.jsx("option",{value:"",children:xe.isLoading?"Loading accessible customers…":"Select a customer"}),ps?e.jsxs("option",{value:N,disabled:Mt,children:["Saved customer ",N," (",fs,")"]}):null,ut.map(q=>e.jsx("option",{value:q.customerId,children:q.descriptiveName??`Customer ${q.customerId}`},q.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:ls,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Kt,value:L,onChange:q=>{y(!0),S(q.target.value)},placeholder:"Use only when a manager context is required"})]})]}),U?e.jsx("p",{role:"status",className:`mt-3 text-sm ${xe.data?.truncated?"text-caution":"text-secondary"}`,children:U}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:Ae.isPending||xe.isLoading||xe.isError||Mt||!N,onClick:Ze(yt),children:Ae.isPending?"Saving…":"Save customer selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:Ct,children:"Cancel"})]}),_.data?.connected?e.jsx(ml,{providerLabel:"Google Ads",disabled:Qe,onDisconnect:_e}):null]}):null,p==="gtm"?e.jsxs("section",{id:"gtm-selection-panel",className:"page-section-divider","aria-labelledby":"gtm-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Tag Manager"}),e.jsx("h3",{id:"gtm-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select container context"})]})}),bs?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:bs}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:kt,children:J.isError?"Retry account list":he.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,zt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:zt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Wa,{id:"gtm-account",label:"Account",value:g,onChange:q=>{b(!0),q!==g&&(I(""),w("")),v(q)},disabled:J.isLoading,children:[e.jsx("option",{value:"",children:J.isLoading?"Loading accounts…":"Select an account"}),Bs?e.jsxs("option",{value:g,disabled:as,children:["Saved account ",g," (",Qt,")"]}):null,es.map(q=>e.jsx("option",{value:q.id,children:q.name},q.id))]}),e.jsxs(Wa,{id:"gtm-container",label:"Container",value:C,onChange:q=>{b(!0),q!==C&&w(""),I(q)},disabled:!g||he.isLoading,children:[e.jsx("option",{value:"",children:he.isLoading?"Loading containers…":"Select a container"}),bt?e.jsxs("option",{value:C,disabled:Vt,children:["Saved container ",C," (",gt,")"]}):null,it.map(q=>e.jsx("option",{value:q.id,children:q.name},q.id))]}),e.jsxs(Wa,{id:"gtm-workspace",label:"Draft workspace (optional)",value:A,onChange:q=>{b(!0),w(q)},disabled:!C||K.isLoading,children:[e.jsx("option",{value:"",children:K.isLoading?"Loading workspaces…":"No draft workspace"}),Vs?e.jsxs("option",{value:A,disabled:xt,children:["Saved draft workspace ",A," (",Lt,")"]}):null,gs.map(q=>e.jsx("option",{value:q.id,children:q.name},q.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:J.data?.truncated?"text-caution":"text-secondary",children:ae}):null,me?e.jsx("p",{role:"status",className:he.data?.truncated?"text-caution":"text-secondary",children:me}):null,ce?e.jsx("p",{role:"status",className:K.data?.truncated?"text-caution":"text-secondary",children:ce}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:ie.isPending||J.isLoading||he.isLoading||K.isLoading&&!!A||Ie||ts||!g||!C,onClick:Ze(se),children:ie.isPending?"Saving…":"Save container selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:Ct,children:"Cancel"})]}),Z.data?.connected?e.jsx(ml,{providerLabel:"Tag Manager",disabled:Qe,onDisconnect:Re}):null]}):null,V?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:Ze(async q=>{q.preventDefault(),await Zt()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:ls,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Kt,value:Q.name,onChange:q=>B(Se=>({...Se,name:q.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:ls,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Kt,value:Q.eventName,onChange:q=>B(Se=>({...Se,eventName:q.target.value})),placeholder:"booking_complete"})]}),e.jsx(hl,{id:"contract-conversion-action",label:"Google Ads conversion action",options:T?.googleAds.conversionActions??[],synced:T?.googleAds.syncedAt!=null,loading:ee.isLoading,failed:ee.isError,onRetry:()=>{ee.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:Q.conversionActionId,onChange:q=>B(Se=>({...Se,conversionActionId:q}))}),e.jsx(hl,{id:"contract-gtm-tag",label:"Tag Manager tag",options:T?.gtm.tags??[],synced:T?.gtm.syncedAt!=null,loading:ee.isLoading,failed:ee.isError,onRetry:()=>{ee.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:Q.tagId,onChange:q=>B(Se=>({...Se,tagId:q}))})]}),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:ls,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Kt,value:Q.conversionId,onChange:q=>B(Se=>({...Se,conversionId:q.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:ls,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Kt,value:Q.conversionLabel,onChange:q=>B(Se=>({...Se,conversionLabel:q.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:ls,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Kt,value:Q.triggerIds,onChange:q=>B(Se=>({...Se,triggerIds:q.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:ls,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Kt,value:Q.variableIds,onChange:q=>B(Se=>({...Se,variableIds:q.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:ls,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Kt,value:Q.campaignIds,onChange:q=>B(Se=>({...Se,campaignIds:q.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:ls,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Kt,value:Q.productionHosts,onChange:q=>B(Se=>({...Se,productionHosts:q.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(qn,{id:"contract-primary-action",checked:Q.requirePrimaryAction,onChange:q=>B(Se=>({...Se,requirePrimaryAction:q})),children:"Google Ads action is primary"}),e.jsx(qn,{id:"contract-biddable-goal",checked:Q.requireBiddableGoal,onChange:q=>B(Se=>({...Se,requireBiddableGoal:q})),children:"Google Ads goal is biddable"}),e.jsx(qn,{id:"contract-runtime-verification",checked:Q.verificationRequired,onChange:q=>B(Se=>({...Se,verificationRequired:q})),children:"Runtime proof is required"}),e.jsx(qn,{id:"contract-transaction-id",checked:Q.requireTransactionId,onChange:q=>B(Se=>({...Se,requireTransactionId:q})),children:"Transaction ID is required"}),e.jsx(qn,{id:"contract-value",checked:Q.requireValue,onChange:q=>B(Se=>({...Se,requireValue:q})),children:"Conversion value is required"}),e.jsx(qn,{id:"contract-currency",checked:Q.requireCurrency,onChange:q=>B(Se=>({...Se,requireCurrency:q})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:O.isPending,children:O.isPending?"Saving…":"Save conversion contract"}),e.jsx(P,{type:"button",variant:"outline",onClick:It,children:"Cancel"})]})]})]}):null]})}const cy=6e4,dy=["7d","14d","30d"],Bi="not available",uy='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%.',my="No Google Ads snapshot stored yet",hy="Connect a Google Ads account in Conversion Integrity below, choose the customer, then run a Google Ads sync. Spend, clicks, impressions, and conversions appear here once the first snapshot is stored.",py="No closed days yet",xy="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.",gy={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},Qs=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),zr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),fy=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function En(t,s){return t===null||!Number.isFinite(t)?Bi:s===null?fy.format(t/1e6):cp(t,s)}function Qr(t){return t===null||!Number.isFinite(t)?Bi:et(t)}function yy(t,s){return t===null||!Number.isFinite(t)?`${Bi} vs prior ${s}d`:t===0?`no change vs prior ${s}d`:`${t>0?"↑":"↓"} ${et(Math.abs(t))} vs prior ${s}d`}function by(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function vy(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function jy(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 Ny({projectName:t}){const[s,n]=o.useState("14d"),[a,r]=o.useState(()=>new Set(["costMicros","conversions"])),l=$e({...Wu({client:Y,path:{name:t},query:{window:s}}),staleTime:cy}),i=l.data,c=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Oe,{text:uy})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Pt(i.startDate)," to ",Pt(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(gr,{windows:dy,value:s,onChange:n,label:"Google Ads time period"})]});if(l.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[c,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(g=>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"})]},g))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(l.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",St(l.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{l.refetch()},children:"Retry performance"})]});const{totals:d,daily:m,campaigns:u,comparison:p,comparisonUnavailableReason:x,source:h}=i;if(!h){const g=x==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:g?py:my}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:g?xy:hy})]})]})}const y=h.currencyCode,f=h.campaignsInInventory>0&&h.campaignsQueried<h.campaignsInInventory?{queried:h.campaignsQueried,inInventory:h.campaignsInInventory}:null,b=d.costMicros>0&&d.conversions===0,N=[{key:"spend",comparable:!0,label:"Spend",value:En(d.costMicros,y),change:p?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:zr.format(d.conversions),change:p?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:b?"no conversions":En(d.costPerConversionMicros,y),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Qr(d.conversionRate),change:p?.change.conversionRate??null,direction:"up-good",seriesKey:null}],k=[{key:"clicks",label:"Clicks",value:Qs.format(d.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:Qs.format(d.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Qr(d.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:En(d.cpcMicros,y),seriesKey:null}],L={costMicros:{label:"Spend",color:lt[1],axisId:"spend",formatValue:g=>En(g,y)},conversions:{label:"Conversions",color:lt[0],axisId:"conversions",formatValue:g=>zr.format(g)},clicks:{label:"Clicks",color:lt[2],axisId:"clicks",formatValue:g=>Qs.format(g)},impressions:{label:"Impressions",color:lt[3],axisId:"impressions",formatValue:g=>Qs.format(g)}},S=[...a].map(g=>({dataKey:g,...L[g]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,f!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",Qs.format(f.queried)," of"," ",Qs.format(f.inInventory)," campaigns, so they are a subset of the account."]}):null,h.truncated?e.jsx("p",{role:"status",className:"mt-3 text-sm text-caution",children:"The provider returned a bounded result, so some rows are missing from the figures below."}):null,!p&&x==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:gy["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:N.map(g=>{const v=g.seriesKey!==null&&a.has(g.seriesKey),C=v&&a.size===1,I=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[g.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?L[g.seriesKey].color:"var(--color-mono-600)"}}):null,g.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:g.value}),p&&g.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${jy(g.change,g.direction)}`,children:yy(g.change,p.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:g.comparable?`no prior ${s} period stored`:" "})]});return g.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:I},g.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:C,onClick:()=>r(A=>{const w=new Set(A);return w.has(g.seriesKey)?w.delete(g.seriesKey):w.add(g.seriesKey),w.size===0?A:w}),className:`rounded-md border px-3 py-2 text-left transition-colors ${v?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${C?"cursor-default":""}`,children:I},g.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:k.map(g=>{const v=g.seriesKey!==null&&a.has(g.seriesKey),C=v&&a.size===1,I=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[g.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?L[g.seriesKey].color:"var(--color-mono-600)"}}):null,g.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:g.value})]});return g.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:I},g.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:C,onClick:()=>r(A=>{const w=new Set(A);return w.has(g.seriesKey)?w.delete(g.seriesKey):w.add(g.seriesKey),w.size===0?A:w}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${C?"cursor-default":"hover:bg-surface-hover"}`,children:I},g.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(oc,{data:m,xKey:"date",series:S,xTickFormatter:Sn,labelFormatter:Pt}),e.jsx("ul",{className:"sr-only",children:m.map(g=>e.jsxs("li",{children:[Pt(g.date),":"," ",S.map(v=>`${v.label} ${L[v.dataKey].formatValue(g[v.dataKey])}`).join(", "),g.origin==="filled"?", no delivery reported":""]},g.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(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:g.name??g.campaignId,children:g.name??e.jsx("span",{className:"font-mono text-secondary",children:g.campaignId})}),e.jsx("td",{children:e.jsx(Ne,{tone:by(g.status),children:vy(g.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Qs.format(g.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Qs.format(g.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:En(g.totals.costMicros,y)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:zr.format(g.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Qr(g.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:g.totals.costMicros>0&&g.totals.conversions===0?e.jsx(Ne,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:En(g.totals.costPerConversionMicros,y)})})]},g.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Sa(Bt(h.capturedAt))," · ","customer ",h.customerId," · ","latest closed day ",Pt(h.asOfDate),h.openDate?e.jsxs(e.Fragment,{children:[" · ",Pt(h.openDate)," still open, excluded"]}):null,h.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",h.timeZone]}):null]})]})]})}const Hr=20,Fs=50,wy=50,Sy=50;function Vi(t){return t==="viewer"}function zi(t){return t?.status==="unavailable"}function zc(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Qc(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 Ya(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 Cy(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 Wr(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 pl(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function xl(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 Ja(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 vi(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Yr(t){return vi(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ji({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[l,i]=o.useState(""),[c,d]=o.useState(!1),m=l.trim().toLocaleLowerCase(),u=m?t.filter(y=>y.label.toLocaleLowerCase().includes(m)):t,p=c?u:u.slice(0,wy),x=p.length<u.length;function h(){const y=new Set([...s,...p.map(f=>f.id)]);n(t.filter(f=>y.has(f.id)).map(f=>f.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(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p.length===0,onClick:h,children:"Select all shown"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),u.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",p.length," of ",u.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:p.map(y=>{const f=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:f,type:"checkbox",onChange:b=>n(zc(s,y.id,b.currentTarget.checked))}),e.jsx("span",{children:y.label})]}),y.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[y.urlCount," URLs"]})]},y.id)})}),x?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function Qi(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(Ne,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Hi({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(Ne,{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 ky({value:t}){const[s,n]=o.useState(0),[a,r]=o.useState(0),[l,i]=o.useState(null),c=t.preview,d=c?.counts.needsAttention??0,m=c?.rows.filter(C=>C.status==="matched")??[],u=c?.rows??[],p=u.filter(C=>C.status!=="matched"),x=Math.max(1,Math.ceil(u.length/Fs)),h=Math.min(s,x-1),y=u.slice(h*Fs,(h+1)*Fs),f=Math.max(1,Math.ceil(p.length/Fs)),b=Math.min(a,f-1),N=p.slice(b*Fs,(b+1)*Fs),k=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,L=m.length>0&&!t.isApplying,S=c!==null&&l===c.previewChecksum,g=p.length>0&&b===f-1;o.useEffect(()=>{n(0),r(0),i(null)},[c?.previewChecksum]);async function v(C){if(C)try{t.onCsvChange(await C.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:C=>{v(C.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:C=>t.onCsvChange(C.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(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!k,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),c?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[c.counts.matchedRows," matched · ",c.counts.groupsReady," group",c.counts.groupsReady===1?"":"s"," ready",d>0?` · ${d} need${d===1?"s":""} attention`:""]}),c.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:c.groupChanges.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:C.label}),e.jsx("td",{className:"text-secondary",children:C.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:C.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[C.addedTargetKeys.length,C.unchangedTargetKeys.length>0?` · ${C.unchangedTargetKeys.length} already members`:""]})]},C.groupKey))})]})}):null,c.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",c.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:y.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(Ne,{tone:pl(C.status),children:xl(C.status)}),Ja(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Ja(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",h+1," of ",x," · ",c.rows.length," rows"]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h===0,onClick:()=>n(C=>Math.max(0,C-1)),children:"Previous 50 rows"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h===x-1,onClick:()=>n(C=>Math.min(x-1,C+1)),children:"Next 50 rows"})]})]}):null,d>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",d," row",d===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:N.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(Ne,{tone:pl(C.status),children:xl(C.status)}),Ja(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Ja(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",b+1," of ",f]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===0,onClick:()=>r(C=>Math.max(0,C-1)),children:"Previous 50 exceptions"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===f-1,onClick:()=>r(C=>Math.min(f-1,C+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:S,disabled:t.isApplying||!g,onChange:C=>i(C.currentTarget.checked?c.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",d," row",d===1?"":"s"," will be skipped."]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!L||!S,onClick:()=>{t.onApply(m.map(C=>C.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${m.length} matched row${m.length===1?"":"s"}`})]}):e.jsx(P,{type:"button",className:"mt-3 min-h-11",disabled:!L,onClick:()=>{t.onApply(m.map(C=>C.dataRow))},children:t.isApplying?"Creating groups…":`Create ${c.counts.groupsReady} group${c.counts.groupsReady===1?"":"s"} with ${m.length} membership${m.length===1?"":"s"}`})]}):null]})}const Ay="—";function Ry({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:l=!1,isBusy:i=!1,canContinue:c=!0,onSelectedQueryIdsChange:d,onApplySelectedQueries:m,onClearQueryAssignments:u,onRemoveQuery:p,onCreateQueries:x,onCreateAndPairQuestions:h,isCreatingQueries:y=!1,createQueriesError:f=null,onManageProjectQueries:b,groups:N,audience:k,onAudienceChange:L,assignmentImpact:S=null,isPreviewingAssignmentImpact:g=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:C,assignmentNotice:I=null,onReplaceAssignments:A,isReplacingAssignments:w=!1,onBack:V,onContinue:G}){const[Q,B]=o.useState(""),[z,ne]=o.useState(!1),[F,_]=o.useState(!1),[Z,$]=o.useState(""),[ee,T]=o.useState(""),[E,te]=o.useState(null);if(zi(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Hi,{message:s.message})});const re=Vi(t),le=k,we=L,X=Ya(le,n,N),ue=X.length,xe=ue>0&&r.length>0&&!l&&!i&&!g&&S!==null&&v===null,J=u??p,he=Q.trim().toLocaleLowerCase(),K=he?a.filter(H=>Yr(H).toLocaleLowerCase().includes(he)):a,pe=K.filter(H=>(H.propertyIds?.length??0)===0),qe=F?pe:K,Ae=z?qe:qe.slice(0,Sy),ie=Ae.filter(H=>!vi(H)),fe=[...new Set(Z.split(`
4
- `).map(H=>H.trim()).filter(Boolean))],Ce=[...ee.matchAll(/\{([a-z][\w-]*)\}/gi)].map(H=>H[1]),Ge=n.filter(H=>X.includes(H.id)),Ee=Ce.length===0||ee.trim()===""?[]:Ge.map(H=>({propertyId:H.id,text:Ce.reduce((Me,Qe)=>Me.replaceAll(`{${Qe}}`,H.label),ee.trim())})),O=[...new Set(Ee.map(H=>H.text))];function D(){const H=new Set([...r,...ie.map(Me=>Me.id)]);d(a.filter(Me=>H.has(Me.id)).map(Me=>Me.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."})]})}),re?e.jsx(Qi,{}):null,re?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:le.kind==="all"?"all":le.kind==="specific"?"specific":`group:${le.groupIds[0]??""}`,onChange:H=>{const Me=H.currentTarget.value;Me==="all"?we({kind:"all"}):Me==="specific"?we({kind:"specific",propertyIds:[]}):Me.startsWith("group:")&&we({kind:"groups",groupIds:[Me.slice(6)]})},className:"block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsxs("option",{value:"all",children:["All Properties · ",n.length]}),N.length>0?e.jsx("optgroup",{label:"Groups",children:N.map(H=>{const Me=Ya({kind:"groups",groupIds:[H.id]},n,N).length;return e.jsx("option",{value:`group:${H.id}`,disabled:Me===0,children:Wr(H,n)},H.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),le.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:le.groupIds.map(H=>{const Me=N.find(Qe=>Qe.id===H);return Me?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:[Wr(Me,n),e.jsx("button",{type:"button","aria-label":`Remove ${Me.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 Qe=le.groupIds.filter(Fe=>Fe!==Me.id);we(Qe.length>0?{kind:"groups",groupIds:Qe}:{kind:"all"})},children:"×"})]},Me.id):null})}),N.some(H=>!le.groupIds.includes(H.id)&&Ya({kind:"groups",groupIds:[H.id]},n,N).length>0)?e.jsxs("label",{className:"block max-w-sm",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Add another group"}),e.jsxs("select",{"aria-label":"Add another group",value:"",onChange:H=>{H.currentTarget.value&&we({kind:"groups",groupIds:[...le.groupIds,H.currentTarget.value]})},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",children:"Choose a group"}),N.filter(H=>!le.groupIds.includes(H.id)).map(H=>{const Me=Ya({kind:"groups",groupIds:[H.id]},n,N).length;return e.jsx("option",{value:H.id,disabled:Me===0,children:Wr(H,n)},H.id)})]})]}):null,ue===0?e.jsx("p",{role:"alert",className:"text-sm text-caution",children:"This group has no included Properties. Add Properties to the group, then try again."}):null]}):null,le.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(ji,{legend:"Specific Properties",properties:n,selectedPropertyIds:le.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:H=>{we({kind:"specific",propertyIds:H})}})}):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."})]}),re||!x?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:Z,onChange:H=>$(H.currentTarget.value),placeholder:`best apartments in dallas
1
+ import{j as e,r as o,t as id,u as Le,L as Ts,h as hs,o as Dt,B as wi,C as Ml,D as od,k as ld,l as cd}from"./vendor-tanstack-ZXXkndVj.js";import{T as je,t as dd,a as ud,s as Si,M as fa,I as Fe,f as Ze,R as Qn,m as md,B as P,c as hd,b as pd,d as xd,S as $l,e as Ll,u as Ci,g as gd,n as Kn,C as fd,h as ql,i as El,j as ki,k as yd,l as bd,o as vd,p as yn,q as Dl,r as Ol,v as ve,w as nr,x as Y,y as le,z as ms,A as Et,D as Xe,E as jd,F as Nd,G as wd,H as Fl,J as Sd,K as Cd,L as rn,N as bn,O as kd,P as Ad,Q as Pn,U as Wt,V as Rd,W as Pd,X as to,Y as Gl,Z as Ht,_ as Ai,$ as Id,a0 as Td,a1 as Md,a2 as $d,a3 as so,a4 as De,a5 as Ld,a6 as qd,a7 as Nr,a8 as Ed,a9 as Dd,aa as Od,ab as Fd,ac as Gd,ad as Kd,ae as _d,af as Ud,ag as Bd,ah as Vd,ai as zd,aj as Qd,ak as Hd,al as Wd,am as Yd,an as Kl,ao as Gs,ap as Jd,aq as _l,ar as or,as as Xd,at as Ye,au as Zd,av as eu,aw as tu,ax as lr,ay as su,az as nu,aA as au,aB as _n,aC as ru,aD as iu,aE as ou,aF as Ul,aG as ti,aH as lu,aI as Ri,aJ as cu,aK as Un,aL as cs,aM as gr,aN as Is,aO as Bl,aP as ar,aQ as si,aR as du,aS as no,aT as Vl,aU as ya,aV as uu,aW as zl,aX as Ql,aY as mu,aZ as Hl,a_ as un,a$ as Pi,b0 as wr,b1 as hu,b2 as pu,b3 as xu,b4 as gu,b5 as fu,b6 as pa,b7 as ao,b8 as Da,b9 as Sr,ba as yu,bb as bu,bc as ro,bd as Cr,be as vn,bf as Wl,bg as Ii,bh as Yl,bi as vu,bj as ju,bk as io,bl as Nu,bm as wu,bn as Su,bo as Cu,bp as ku,bq as Au,br as Ru,bs as Pu,bt as Iu,bu as Tu,bv as Mu,bw as $u,bx as Lu,by as qu,bz as Eu,bA as Du,bB as Ou,bC as Fu,bD as Gu,bE as Ku,bF as _u,bG as Uu,bH as Bu,bI as Vu,bJ as zu,bK as Qu,bL as Hu,bM as Wu,bN as Ss,bO as Yu,bP as wt,bQ as Ju,bR as Xu,bS as Zu,bT as em,bU as tm,bV as sm,bW as nm,bX as am,bY as rm,bZ as im,b_ as om,b$ as lm,c0 as cm,c1 as dm,c2 as um,c3 as mm,c4 as hm,c5 as pm,c6 as xm,c7 as gm,c8 as fm,c9 as ym,ca as oo,cb as bm,cc as vm,cd as jm,ce as Nm,cf as wm,cg as Jl,ch as Sm,ci as Cm,cj as km,ck as Xl,cl as kr,cm as Am,cn as Rm,co as lo,cp as Pm,cq as Im,cr as Tm,cs as Mm,ct as $m,cu as Lm,cv as qm,cw as Zl,cx as Em,cy as ec,cz as tc,cA as sc,cB as nc,cC as Dm,cD as Om,cE as Fm,cF as Gm,cG as Km,cH as _m,cI as Um,cJ as co,cK as Bm,cL as Vm,cM as zm,cN as Qm,cO as Hm,cP as Wm,cQ as Ym,cR as Jm,cS as uo,cT as Xm,cU as Zm,cV as eh,cW as th,cX as sh,cY as nh,cZ as ah,c_ as rh,c$ as ih,d0 as oh,d1 as lh,d2 as ch,d3 as Ar,d4 as dh,d5 as uh,d6 as mh,d7 as hh,d8 as ph,d9 as xh,da as gh,db as fh,dc as yh,dd as bh,de as vh,df as jh,dg as Nh,dh as ac,di as wh,dj as Sh,dk as Ch,dl as kh,dm as Ah,dn as Rh,dp as Oa,dq as Ph,dr as Ih,ds as Th,dt as mo,du as Mh}from"./index-DR_kNdE4.js";import{u as jn,D as Zs,a as Os,b as rc,M as rr,c as qs,F as $h,P as ic,s as Lh,p as qh,S as Eh}from"./SiteHealthSection-DMHWsfM4.js";import{A as Ti,a as Dh,b as Oh,c as Fh,V as ho}from"./v2-overview-adapter-CLF10Pij.js";import{o as Bt,C as ba,f as Nn,a as ds,b as Ut,c as Tt,d as ts,e as ct,g as us,h as Hn,M as oc,i as Gh,j as Ca,p as Kh,k as _h,l as po,m as Uh}from"./ChartPrimitives-CYlrwLJs.js";import{g as lc,y as va,U as Bh,z as Vh,L as zh,D as Qh,l as Hh,j as cr,I as Wh,J as Yh,C as Bn,X as Jh,e as Xh,K as Zh,P as ep,N as tp,O as cc}from"./vendor-lucide-N6vOpZmh.js";import{u as sp,a as np,b as ap,t as rp,e as ip,c as Ct}from"./extract-error-message-Cyc59Xi7.js";import{R as en,C as tn,a as ja,X as sn,Y as nn,T as an,b as ni,L as dr,A as Js,d as Ds,e as op}from"./vendor-recharts-D-cUuLZo.js";import{A as lp}from"./AuditHistoryPanel-BYxGn9mS.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B4giJcws.js";import"./vendor-yaml-GWJz5H2G.js";const cp=1e6;function dp(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/cp);if(n.showTinyAsLessThan&&t>0&&r===a.format(0)){const l=10**-(a.resolvedOptions().maximumFractionDigits??0);return`<${a.format(l)}`}return r}const Fa={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 dc(t,s){return t!=="viewer"||s!==null}function uc(t,s){return t==="research"&&!s?"tracked":t}function mc(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 ai(t,s){return t.find(n=>n.kind===s.measurementScope&&(n.kind==="project"||n.id===s.measurementScopeKey))}function up(t){return t.measurementScope!=="project"||t.marketKey!==void 0}function mp(t){if(t.embedded)return{kind:"none"};const{tab:s}=t;switch(s){case"overview":return t.surface==="advanced-overview"?{kind:"report-picker"}:{kind:"none"};case"queries":case"discovery":{const{tracking:n}=t;return t.queryWorkspace!=="tracked"||n.state!=="ready"||n.mode!=="advanced"?{kind:"none"}:n.scopeUnavailable?{kind:"scope-unavailable"}:{kind:"tracking-picker"}}case"search-console":case"activity":case"technical-aeo":case"conversions":case"local":case"backlinks":case"history":return t.scoped&&t.surface==="advanced-overview"?{kind:"project-wide"}:{kind:"none"};case"settings":case"portfolio":return{kind:"none"};default:return s}}function ri({state:t,label:s,className:n}){return e.jsx(je,{tone:ud(t),className:n,children:s??dd(t)})}const mn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],xo={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},hp={"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."},pp="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function xp(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:Ze(t.score,Qn.percent),numeric:!0,detail:`${t.projectMentionSnapshots} of ${t.combinedMentionSnapshots} brand mentions`,showRows:!0}:{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1}}function gp({breakdown:t,projectLabel:s}){if(t.ranking.length===0)return null;const n=t.ranking.map(a=>({label:a.kind==="project"?`${s} (you)`:a.domain??"",mentions:a.mentionSnapshots,share:a.share,isYou:a.kind==="project"}));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Fe,{text:pp})]}),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:Ze(a.share)})]},a.label))})]})}function fp({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=o.useState("non-brand"),l=o.useId(),i=t.scope==="pooled",c=!i&&t.branded.snapshotsTotal>0,d=c?a:"non-brand",m=i?"pooled":d,u=d==="branded"?t.branded:t.breakdown,p=d==="branded"?t.breakdown:t.branded,x=xp(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:p.snapshotsTotal>0}),h=Si(x.headline),y=m==="non-brand"?fa[t.tone]:"text-secondary";function f(b){const N=mn.findIndex($=>$.value===d);let k=null;b.key==="ArrowRight"||b.key==="ArrowDown"?k=(N+1)%mn.length:b.key==="ArrowLeft"||b.key==="ArrowUp"?k=(N-1+mn.length)%mn.length:b.key==="Home"?k=0:b.key==="End"&&(k=mn.length-1),k!==null&&(b.preventDefault(),r(mn[k].value),b.currentTarget.querySelectorAll('[role="radio"]')[k]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:l,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Fe,{text:hp[m]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":l,className:"segmented flex-wrap",onKeyDown:f,children:mn.map(b=>{const N=b.value===d;return e.jsx("button",{type:"button",role:"radio","aria-checked":N,tabIndex:N?0:-1,onClick:()=>r(b.value),className:`segmented-option min-h-11 ${N?"segmented-option-active":""}`,children:b.label},b.value)})}):e.jsx("span",{className:"mention-share-class",children:xo[m]})]}),x.numeric?e.jsxs("p",{className:`mention-share-value ${y}`,children:[h.figure,h.sign?e.jsx("span",{className:"text-faint",children:h.sign}):null]}):e.jsx("p",{className:"mention-share-value-text",children:x.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:xo[m]}),` · ${x.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),x.showRows&&e.jsx(gp,{breakdown:u,projectLabel:s})]})}function ka({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 xa({options:t,value:s,onChange:n,label:a,className:r=""}){const l=o.useId();function i(c){const d=t.findIndex(u=>u.value===s);let m=null;c.key==="ArrowRight"||c.key==="ArrowDown"?m=(d+1)%t.length:c.key==="ArrowLeft"||c.key==="ArrowUp"?m=(d-1+t.length)%t.length:c.key==="Home"?m=0:c.key==="End"&&(m=t.length-1),m!==null&&(c.preventDefault(),n(t[m].value),c.currentTarget.querySelectorAll('[role="radio"]')[m].focus())}return e.jsx("div",{role:"radiogroup","aria-label":a,className:`segmented ${r}`.trim(),onKeyDown:i,children:t.map(c=>{const d=c.value===s,m=c.description?`${l}-${c.value}`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button",role:"radio","aria-checked":d,"aria-describedby":m,tabIndex:d?0:-1,onClick:()=>n(c.value),className:`segmented-option pointer-coarse:min-h-11 ${d?"segmented-option-active":""}`,children:c.label}),c.description?e.jsx("span",{id:m,className:"sr-only",children:c.description}):null]},c.value)})})}const yp=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],bp={"7d":"last 7 days","30d":"last 30 days","90d":"last 90 days",all:"all sweeps"},vp={"non-brand":"Non-brand",branded:"Branded",all:"All queries"},jp={"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."},Np={"select-query-class":"no query type selected","answer-selection":"answers selected by the brands they named","no-competitors":"no competitors configured","insufficient-observed":"needs 3 observed competitors, each named in 3 or more answers","no-answers":"no answer text","no-mentions":"no brands named",unavailable:"competitor data unavailable"},go="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.",ii=100;function wp(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function hc(t){return t==="unavailable"?"Unavailable":"Not measured"}function oi(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 Cs(t,s,n){return t===1?s:n}function pc(t){const s=t.label.trim(),n=hd(t.domain);return s&&s.toLowerCase()!==t.domain.toLowerCase()&&s.toLowerCase()!==n.toLowerCase()?s:null}function xc({row:t,aliases:s=[],autoAliases:n=[]}){const a=pc(t),r=[...s.map(i=>({alias:i,auto:!1})),...n.map(i=>({alias:i,auto:!0}))],l=r.length>0?e.jsxs("span",{className:"av-of block",children:["Also named"," ",r.map(({alias:i,auto:c},d)=>e.jsxs("span",{children:[d>0?", ":"",i,c?e.jsx("span",{className:"av-alias-auto",title:"Detected automatically from this project's stored answers",children:" (auto)"}):null]},`${c?"auto":"curated"}:${i}`))]}):null;return a?e.jsxs(e.Fragment,{children:[a," ",e.jsx("span",{className:"av-of",children:t.domain}),l]}):e.jsxs(e.Fragment,{children:[t.domain,l]})}function Sp(t){const s=pc(t);return s?`${s} (${t.domain})`:t.domain}function fo(t,s){return s&&t>=ii?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:t})]}):e.jsx("strong",{children:t})}function li({action:t,domain:s,mutation:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(null);async function c(){if(!a){r(!0),i(null);try{await n(s)===!1&&i(`Could not ${t} competitor. Try again.`)}catch{i(`Could not ${t} competitor. Try again.`)}finally{r(!1)}}}return e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",size:"sm",variant:"outline",disabled:a,onClick:()=>{c()},children:[t==="pin"?"Pin":"Unpin"," ",e.jsx("span",{className:"sr-only",children:s})]}),l?e.jsx("span",{role:"alert",className:"sr-only",children:l}):null]})}function Cp({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 qn({count:t,of:s,state:n,toneClass:a}){return n!=="measured"?e.jsx("span",{className:"text-[13px] text-secondary",children:hc(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 yo({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":hc(s)});const{figure:a,sign:r}=Si(Ze(t,Qn.percent));return e.jsxs("span",{className:`av-n-sm ${n}`,children:[a,r?e.jsx("span",{className:"text-faint",children:r}):null]})}function kp({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(xc,{row:l})}),e.jsx("td",{className:"text-[13px] text-secondary",children:oi(l.surfaceClass)}),e.jsx("td",{children:e.jsx(qn,{count:l.mentionCount,of:n,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(qn,{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(Cp,{urls:l.sampleUrls}):null,r?e.jsx(li,{action:"pin",domain:l.domain,mutation:r}):null]})})]},l.domain))})]})})}function Ap({onAddCompetitor:t}){const s=o.useId(),[n,a]=o.useState(""),[r,l]=o.useState(!1),[i,c]=o.useState(null);async function d(){const m=n.trim();if(!(!m||r)){l(!0),c(null);try{if(await t(m)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("Could not add competitor. Try again.")}finally{l(!1)}}}return e.jsxs("details",{className:"inline-disclosure",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:m=>{m.preventDefault(),d()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:m=>a(m.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(P,{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 Rp({window:t,landscape:s,pinnedFallback:n=[],competitorAliases:a={},competitorAutoAliases:r={},canWrite:l,isEmbed:i,onWindowChange:c,onPin:d,onUnpin:m,onAddCompetitor:u,error:p,onRetry:x,isLoading:h=!1,scopeLabel:y}){const f=o.useId(),b=l&&!i,N=s?.pinned??n,k=s?.observed??[],$=s?.otherSources??[],S=s?.evidence,g=wp(s),v=s?.basis==="observed",C=v?k.filter(E=>E.shareOfVoice!==null):N,I=v?k.filter(E=>E.shareOfVoice===null):k,A=s?.filters.queryClass,w=s?.marketState?.draft?.pendingCompetitorDomains.length??0,V=s?.truncated===!0,G=S?.answeredResults??0,Q=S?S.answeredResults+S.missingAnswerTextResults:0,B=A==="non-brand"&&s?.project.shareOfVoice!=null?fa[md(s.project.shareOfVoice)]:"text-primary",z=E=>b?E.pinned?m?e.jsx(li,{action:"unpin",domain:E.domain,mutation:m}):null:d?e.jsx(li,{action:"pin",domain:E.domain,mutation:d}):null:null,ne=C.some(E=>z(E)!==null),F=[y,A?vp[A]:null,bp[t],s?.basis?v?"observed competitors only":"tracked competitors only":null].filter(Boolean).join(" · "),_=[];if(s&&!v&&C.length===0&&_.push({key:"no-pins",text:"No pinned competitors."}),s?.reason&&_.push({key:"reason",text:`Mention share: ${Np[s.reason]}`}),s&&I.length>0){const E=I.length;_.push({key:"others",text:V&&E>=ii?`${ii} or more other competitors seen`:`${E} other ${Cs(E,"competitor","competitors")} seen`})}w>0&&_.push({key:"pending",text:`${s?.scope.kind==="all-markets"?"Pending publication across markets":"Pending publication"}: ${w} ${Cs(w,"competitor","competitors")}`});const Z=[S&&S.missingAnswerTextResults>0?"Answer data incomplete":null,S&&S.incompleteSourceResults>0?"Citation data incomplete":null].filter(Boolean);Z.length>0&&_.push({key:"incomplete",text:Z.join(" · "),className:fa.caution});const L=[];if(s&&S){L.push(s.runCount!==void 0?e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:s.runCount})," ",Cs(s.runCount,"sweep","sweeps"),", ",e.jsx("strong",{children:S.answeredResults})," ",Cs(S.answeredResults,"answer","answers")]}):e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:S.answeredResults})," ",Cs(S.answeredResults,"answer","answers")]})),!s.reason&&g==="measured"&&s.project.shareOfVoice!==null&&L.push(e.jsxs(e.Fragment,{children:["Mention share: you ",e.jsx("strong",{children:s.project.mentionCount}),C.map(te=>e.jsxs(id.Fragment,{children:[", ",te.domain," ",e.jsx("strong",{children:te.mentionCount})]},te.domain))," ","of ",e.jsx("strong",{children:S.mentionCredits})," ",v?"brand mentions":"tracked-brand mentions"]})),L.push(e.jsxs(e.Fragment,{children:["Answers with source links: ",e.jsx("strong",{children:S.sourceResults})]})),I.length===0&&L.push("Other competitors seen: none"),S.missingAnswerTextResults>0&&L.push(e.jsxs(e.Fragment,{children:["No answer text: ",e.jsx("strong",{children:S.missingAnswerTextResults})," ",Cs(S.missingAnswerTextResults,"answer","answers"),", left out of mention share"]})),S.incompleteSourceResults>0&&L.push(e.jsxs(e.Fragment,{children:["Incomplete source lists: ",e.jsx("strong",{children:S.incompleteSourceResults})," ",Cs(S.incompleteSourceResults,"answer","answers"),", not counted as misses"]}));const E=S.excludedProbeResults+S.excludedNonCompletedResults;E>0&&L.push(e.jsxs(e.Fragment,{children:["Left out: ",e.jsx("strong",{children:E})," ",Cs(E,"answer","answers")," from spot checks or unfinished sweeps"]}))}const ee=[...s?[{name:"You",row:s.project}]:[],...C.map(E=>({name:E.domain,row:E}))].filter(E=>E.row.sampleUrls.length>0);g==="measured"&&ee.length>0&&L.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsx("summary",{children:"Sample pages cited"}),e.jsx("div",{className:"av-subdetails-body",children:ee.map(({name:E,row:te})=>e.jsxs("div",{children:[e.jsx("p",{children:E}),e.jsx("ul",{className:"space-y-1 font-mono text-[11px] text-muted",children:te.sampleUrls.map(re=>e.jsx("li",{className:"break-all",children:re},re))})]},te.domain))})]})),s&&I.length>0&&L.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other competitors seen: ",fo(I.length,V)]}),e.jsx("div",{className:"av-subdetails-body",children:e.jsx(kp,{rows:I,state:g,named:G,cited:Q,onPin:b?d:void 0})})]}));const T=s?.observedNames??[];if(T.length>0){const E=s?.observedNamesTotal??T.length;L.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Company names in answers: ",E>T.length?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:T.length})," of ",e.jsx("strong",{children:E})]}):e.jsx("strong",{children:T.length})]}),e.jsx("ul",{className:"av-subdetails-body",children:T.map(te=>e.jsxs("li",{children:[te.name," · ",te.answerCount," ",Cs(te.answerCount,"answer","answers")]},te.name))})]}))}return $.length>0&&L.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other sites cited: ",fo($.length,V)]}),e.jsx("ul",{className:"av-subdetails-body",children:$.map(E=>e.jsxs("li",{children:[e.jsxs("span",{children:[Sp(E)," · ",oi(E.surfaceClass)," · ",E.citationCount," ",Cs(E.citationCount,"citation","citations")]}),E.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:E.sampleUrls.map(te=>e.jsx("li",{className:"break-all",children:te},te))}):null]},E.domain))})]})),e.jsxs("section",{"aria-labelledby":f,"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:f,className:"av-card-title",children:"Competitors over time"}),e.jsx(Fe,{text:A?`${jp[A]} ${go}`:go})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsx("p",{className:"av-card-meta",children:F}),e.jsx(xa,{label:"Competitors over time window",className:"flex-wrap",options:yp,value:t,onChange:c})]})]}),e.jsxs("div",{className:"av-card-body space-y-3",children:[p?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:p}),x?e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:x,children:"Retry competitors over time"}):null]}):null,h&&!s&&N.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||C.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"}),ne?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(yo,{percent:s.project.shareOfVoice,state:g,toneClass:B})}),e.jsx("td",{children:e.jsx(qn,{count:s.project.mentionCount,of:G,state:g,toneClass:B})}),e.jsx("td",{children:e.jsx(qn,{count:s.project.citationCount,of:Q,state:g,toneClass:B})}),ne?e.jsx("td",{className:"av-brand-actions"}):null]}):null,C.map(E=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(xc,{row:E,aliases:E.pinned?a[E.domain]:void 0,autoAliases:E.pinned?r[E.domain]:void 0})}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:oi(E.surfaceClass)}),e.jsx("td",{children:e.jsx(yo,{percent:E.shareOfVoice,state:g,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(qn,{count:E.mentionCount,of:G,state:g,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(qn,{count:E.citationCount,of:Q,state:g,toneClass:"text-primary"})}),ne?e.jsx("td",{className:"av-brand-actions",children:z(E)}):null]},E.domain))]})]}):null,_.length>0?e.jsx("div",{className:"space-y-1 text-[13px] text-secondary",children:_.map(E=>e.jsx("p",{className:E.className,children:E.text},E.key))}):null]}),e.jsx(ka,{items:L}),b&&u?e.jsx("div",{className:"border-t border-subtle px-5 py-3",children:e.jsx(Ap,{onAddCompetitor:u})}):null]})}function bo({history:t,maxDots:s=12,signal:n="citations"}){const a=t.slice(-s);if(a.length===0)return e.jsx("span",{className:"text-[13px] text-secondary",children:"No data"});const r=n==="mentions"?"Mention":"Citation",l=n==="mentions"?{cited:"mentioned","not-cited":"not mentioned",lost:"mention lost",emerging:"new mention",pending:"mention pending"}:{cited:"cited","not-cited":"not cited",lost:"citation lost",emerging:"new citation",pending:"citation pending"},i={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},c={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},d=a.length-1,m=new Date(a[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(a[d].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),p=`${a.length} ${a.length===1?"run":"runs"}`,x=a.map((h,y)=>{const f=new Date(h.createdAt).toLocaleDateString();return`${y===d?"Latest run, ":""}${f}: ${l[h.citationState]??h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"inline-flex w-max items-center gap-2 whitespace-nowrap",role:"img","aria-label":`${r} history across ${p}. ${x}`,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:p,"aria-hidden":"true",children:a.map((h,y)=>{const f=!!(h.model&&y>0&&a[y-1]?.model&&a[y-1].model!==h.model),b=y===d;return e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 ${c[h.citationState]??"rounded-sm"} ${i[h.citationState]??"bg-mono-700"} ${f?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[l[h.citationState]??h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,f?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[11px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{children:"latest"})]})]})}function ci(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 Aa="__cited__",Ra="__mentioned__",Fs="__mentionShare__";function Ms(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Bt(n),end:Bt(a),sweepCount:s.sweepCount??1}}function Na(t,s=new Date){return xd(t,s)}function Pa(t,s=new Date){const n=Ms(t);if(!n)return null;const a=Na(n.start,s),r=Na(n.end,s);return a===r?a:`${a} to ${r}`}function Mi(t,s=new Date){const n=Ms(t),a=Pa(t,s);return!n||!a?"Sweep date unavailable":`${a} · ${n.sweepCount} ${n.sweepCount===1?"sweep":"sweeps"}`}function Pp(t){const s=Ms(t);return s?pd(s.start):""}function wa(t){return t.trim().toLowerCase()}function Ip(t,s={}){return t.map(n=>{const a=n.trim().toLowerCase(),r=(s[n]??[]).map(l=>l.trim().toLowerCase()).filter(Boolean).sort();return a&&r.length>0?`${a}=${r.join("|")}`:a}).filter(Boolean).sort().join(`
2
+ `)}const Tp={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",muse:"Muse",local:"Local"};function lt(t){const s=wa(t);return Tp[s]??t.charAt(0).toUpperCase()+t.slice(1)}function di(t){return Math.round(t*1e3)/10}function ui(t){return t.byProvider??{}}function Mp(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?Aa:Ra,m=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(p=>({date:p.startDate,[d]:di(p[m])})),series:[d],hasData:a,singleBucket:r}}const l=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys(ui(d))))].sort();return{rows:t.buckets.map(d=>{const m={date:d.startDate},u=ui(d);for(const p of i){const x=u[p];m[p]=x?di(x[l]):null}return m}),series:i,hasData:a,singleBucket:r}}function gc(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function $p(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Lp(t){return t.servedModelAttribution??{}}function qp(t){return t.modelServiceMismatch??{}}function Ep(t){return t.modelPointerChanges??{}}function ga(t){return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function Sa(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 Dp(t){return ga([...t.models,...t.includesUnknown?["an unknown model"]:[]])}function Op(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 Fp(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:Op(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Gp(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 Kp(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[Fs]:r?.rate==null?null:di(r.rate)}}),n=s.map(a=>a[Fs]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Fs],hasData:n.length>0,singleBucket:n.length===1}}function _p(t,s,n){return s==="mentionShare"?Kp(t):Mp(t,s,n)}function Up(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 Bp(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 Vp(t,s,n){const a=n==="mentioned"?"mentionRate":"citationRate";for(let r=t.buckets.length-1;r>=0;r--){const l=ui(t.buckets[r])[s];if(l)return l[a]}return null}function We(t){return Date.parse(t)}function fc(t,s){const n=Ms(t);if(!n)return!1;const a=We(s);return a>=We(n.start)&&a<=We(n.end)}function yc(t){return t.basketChanges??[]}function bc(t,s){return s.filter(n=>fc(t,n.at)).sort((n,a)=>We(n.at)-We(a.at))}function ur(t,s){return wa(t)==="perplexity"&&s.status==="known"&&!s.model.includes("/")}function zp(t){return Object.entries(t).filter(([s,n])=>!ur(s,n.configured)).sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>({provider:s,mismatch:n}))}function Qp(t){return[...yc(t)].sort((s,n)=>We(n.at)-We(s.at)).map(s=>({at:Bt(s.at),added:s.added,removed:s.removed}))}function Hp(t,s){const n=[...t.events].sort((r,l)=>We(r.observedAt)-We(l.observedAt));let a=n[0]?.from??t.latestObservation.state;for(const r of n)We(r.observedAt)<=We(s)&&(a=r.to);return a}function vo(t,s,n,a){return{provider:t,at:Bt(s.observedAt),onOrBefore:s.fromPreWindowAnchor===!0,anchorAt:s.anchorObservedAt?Bt(s.anchorObservedAt):null,from:s.from,to:s.to,served:n,reroute:a}}function Wp(t,s){const n=[];for(const[a,r]of Object.entries(t)){const i=s[a]?.events??[],c=new Set(r.events.map(d=>d.observedAt));for(const d of r.events){const m=ur(a,d.to)?i.find(u=>u.observedAt===d.observedAt):void 0;n.push(vo(a,d,m?{from:m.from,to:m.to}:null,!1))}for(const d of i)c.has(d.observedAt)||ur(a,Hp(r,d.observedAt))&&n.push(vo(a,d,null,!0))}return n.sort((a,r)=>We(r.at)-We(a.at)||a.provider.localeCompare(r.provider))}function Yp({latest:t,queryChanges:s,modelRows:n,now:a=new Date}){const r=[...s.map(x=>x.at),...n.map(x=>x.at)];if(r.length===0)return null;const l=x=>t!==void 0&&fc(t,x),i=s.filter(x=>l(x.at)),c=i.reduce((x,h)=>x+h.added.length,0),d=i.reduce((x,h)=>x+h.removed.length,0),m=n.filter(x=>l(x.at)).length,u=t?Pa(t,a):null;if(u===null||c+d+m===0){const x=r.reduce((h,y)=>We(y)>We(h)?y:h);return`No changes since ${Na(x,a)}`}const p=[u];return c>0&&p.push(`${c} ${c===1?"query":"queries"} added`),d>0&&p.push(`${d} ${d===1?"query":"queries"} removed`),m>0&&p.push(`${m} new ${m===1?"model":"models"}`),p.join(" · ")}function Jp(t,s,n,a=null){const r=We(t);if(!Number.isFinite(r))return null;const l=s.filter(m=>We(m)<r);if(l.length>0)return Bt(l.reduce((m,u)=>We(u)>We(m)?u:m));const i=n.map(m=>Ms(m)).filter(m=>m!==null).sort((m,u)=>We(m.start)-We(u.start)),c=i.findIndex(m=>We(m.start)<=r&&r<=We(m.end));if(c===-1)return null;const d=i[c];return We(d.start)===r?c>0?i[c-1].end:a&&We(a)<r?Bt(a):null:d.sweepCount===2&&We(d.end)===r?d.start:null}function Xp(t){const s=new Map,n=(a,r)=>{const l=s.get(a);l?l.push(r):s.set(a,[r])};for(const a of[...t].sort((r,l)=>r.revision-l.revision)){const r=We(a.at);for(const l of a.removed)n(l,{at:r,member:!1});for(const l of a.added)n(l,{at:r,member:!0})}return new Map([...s].filter(([,a])=>a.at(-1).member))}function Vn(t,s){let n=!t[0].member;for(const a of t)a.at<=s&&(n=a.member);return n}function Zp(t,s,n){return t.some(a=>a.at>s&&a.at<=n)}function mi(t,s){const n=We(s.start),a=We(s.end);return s.sweepCount>2?Zp(t,n,a):Vn(t,n)!==Vn(t,a)}function vc(t,s,n,a){const r=We(s),l=We(n),i={added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]},c=new Set;for(const[p,x]of Xp(t)){if(!a(x))continue;c.add(p);const h=Vn(x,r),y=Vn(x,l);h!==y?(y?i.added:i.removed).push(p):(h?i.removedAndAddedBack:i.addedAndRemovedAgain).push(p)}if(c.size===0)return null;const d=p=>[...p.added,...p.removed].some(x=>c.has(x)),m=t.filter(p=>We(p.at)>r&&We(p.at)<=l&&d(p)).sort((p,x)=>We(p.at)-We(x.at)),u=[...new Set(m.flatMap(p=>[...p.added,...p.removed]))].filter(p=>c.has(p));return{changes:m,keys:u,moves:i}}function ex(t,s){if(t.length<2)return null;const n=t[0],a=t.at(-1),r=Ms(n),l=Ms(a),i=r?.start??n.startDate,c=l?.end??a.endDate,d=vc(s,i,c,m=>Vn(m,We(i))!==Vn(m,We(c))||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 jc(t,s){const n=Ms(t);if(!n)return null;const a=vc(s,n.start,n.end,r=>mi(r,n));return a?{...a,firstCount:t.queryCount,latestCount:t.queryCount}:null}function Rr(t){return`${t} ${t===1?"query":"queries"}`}function tx(t){const s=[],n=a=>s.length===0?Rr(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(`${Rr(t.removedAndAddedBack.length)} removed and added back`),t.addedAndRemovedAgain.length>0&&s.push(`${Rr(t.addedAndRemovedAgain.length)} added and removed again`),ga(s)}function jo(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 No=320;function wo(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function So(t){return t==="non-brand"?0:t==="branded"?1:2}function sx(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 nx(t){return t.phrase}function Co(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 ko(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 ax(t,s){return t.map(n=>Nc(n,s))}function Nc(t,s){return s==="citations"?t:{...t,citationState:Co(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Co(n,s)}))}}function Ao(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,l=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",c=l==="cited"||l==="emerging";return r==="lost"||l!==null&&c&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||l!==null&&!c&&i?{key:s,label:`New ${n}`,tone:"positive"}:l===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function rx(t){const s=ci(ax(t,"mentions")),n=ci(t);return[Ao(s,"mentions"),Ao(n,"citations")]}function ix({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 Ro({items:t}){return e.jsx("div",{className:"query-evidence-signals","aria-label":"Latest run mention and citation signals",children:rx(t).map(s=>e.jsx(ix,{signal:s},s.key))})}function wc({queryClass:t,actions:s}){return e.jsxs(e.Fragment,{children:[s?e.jsx("div",{className:"query-evidence-toolbar",children:e.jsxs("div",{className:"query-evidence-actions",children:[!t&&e.jsx($l,{}),s]})}):null,t?e.jsx(Ll,{queryClass:t,manage:!!s}):null]})}function ox({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed",providerSelection:a,onProviderSelectionChange:r,addedQueries:l=[],actions:i,actionPanel:c}){const{openEvidence:d}=Ci(),m=o.useId(),[u,p]=o.useState(new Set),x=gd(),[h,y]=o.useState("mentions"),[f,b]=o.useState(n),[N,k]=o.useState("all"),[$,S]=o.useState(""),g=a??$,v=L=>{S(L),r?.(L)},C=o.useMemo(()=>[...new Set([...t.map(L=>L.provider).filter(Boolean),...g?[g]:[]])].sort(),[t,g]),I=o.useMemo(()=>{const L=new Map;for(const ee of t){if(g&&ee.provider!==g)continue;const T=ee.query,E=ee.queryClass??null,te=s?ee.location??null:null,re=JSON.stringify([T,E,te]),ce=L.get(re)??{key:re,phrase:T,queryClass:E,location:te,items:[],rawItems:[]};ce.items.push(Nc(ee,h)),ce.rawItems.push(ee),L.set(re,ce)}return[...L.values()].sort((ee,T)=>So(ee.queryClass)-So(T.queryClass))},[t,h,s,g]),A=o.useMemo(()=>I.filter(L=>N==="all"||(N==="unclassified"?L.queryClass===null:L.queryClass===N)),[I,N]),w=jn({rows:A,getSearchText:nx}),V=o.useMemo(()=>{const L=new Map;for(const ee of w.filteredRows){const T=L.get(ee.queryClass)??new Set;T.add(ee.phrase),L.set(ee.queryClass,T)}return L},[w.filteredRows]),G=o.useMemo(()=>new Set(l.map(Kn)),[l]),Q=x?6:5,B=w.rows.map(L=>L.key),z=B.length>0&&B.every(L=>u.has(L)),ne=L=>{p(ee=>{const T=new Set(ee);return T.has(L)?T.delete(L):T.add(L),T})},F=h==="mentions"?"mentioned":"cited",_=h==="mentions"?"Mention History":"Citation History",Z=h==="mentions"?"mentioned":"cited";return e.jsxs("div",{className:"query-evidence",children:[e.jsx(wc,{queryClass:N,actions:i}),c,e.jsxs("div",{className:"query-evidence-view-row",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"query-evidence-tabs",role:"tablist","aria-label":"Citation tracking view",children:["mentions","citations"].map(L=>e.jsx("button",{id:`${m}-${L}`,type:"button",role:"tab","aria-controls":m,"aria-selected":h===L,tabIndex:h===L?0:-1,onClick:()=>y(L),onKeyDown:ee=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(ee.key))return;ee.preventDefault();const T=ee.key==="Home"?"mentions":ee.key==="End"||L==="mentions"?"citations":"mentions";y(T),document.getElementById(`${m}-${T}`)?.focus()},children:L==="mentions"?"Mentions":"Citations"},L))}),e.jsx(Fe,{text:"Mentions track your brand or domain in answer text. Citations track your domain in source links. Each signal is measured independently."})]}),e.jsxs("div",{className:"query-evidence-display-controls",children:[e.jsxs("label",{className:"query-evidence-preview-toggle",children:[e.jsx("input",{type:"checkbox",checked:f==="detailed",onChange:L=>b(L.target.checked?"detailed":"compact")}),"Show answer previews"]}),e.jsx(P,{type:"button",variant:"ghost",className:"min-h-11",disabled:B.length===0,onClick:()=>{p(L=>{const ee=new Set(L);for(const T of B)z?ee.delete(T):ee.add(T);return ee})},children:z?"Collapse page":"Expand page"})]})]}),t.length>0||g?e.jsxs("div",{className:"query-evidence-filters",children:[e.jsx(Zs,{value:w.query,onChange:w.setQuery,label:"Find a query",placeholder:"Find a query",className:"query-evidence-search"}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Answer engine"}),e.jsxs("select",{value:g,onChange:L=>{v(L.target.value),w.setPage(1)},children:[e.jsx("option",{value:"",children:"All engines"}),C.map(L=>e.jsx("option",{value:L,children:lt(L)},L))]})]}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Query class"}),e.jsxs("select",{value:N,onChange:L=>{k(L.target.value),w.setPage(1)},children:[e.jsx("option",{value:"all",children:"All queries"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]})]}):null,e.jsxs("div",{id:m,role:"tabpanel","aria-labelledby":`${m}-${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"}),x&&e.jsx("th",{scope:"col","aria-label":"Sentiment",children:e.jsxs("span",{className:"inline-flex items-center",children:["Sentiment",e.jsx(Fe,{text:"Branded query rows show the favorable share of judged answers. Non-brand rows show only their unfavorable and mixed answers. Expanded engine rows show each stored answer’s sentiment; factual and unmentioned answers are not judgments."})]})}),e.jsx("th",{scope:"col",children:_}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Answer"})})]})}),sx(w.rows).map(L=>e.jsxs("tbody",{children:[e.jsx("tr",{className:"query-evidence-group",children:e.jsxs("th",{scope:"rowgroup",colSpan:Q,children:[wo(L.queryClass)," (",V.get(L.queryClass)?.size??0,")"]})}),L.rows.map(({key:ee,phrase:T,queryClass:E,location:te,items:re,rawItems:ce})=>{const Ne=u.has(ee),X=B.indexOf(ee),ue=`${m}-query-${X}`,pe=G.has(Kn(T)),J=re.map(ie=>ie.citationState),me=J.includes("cited")?"cited":J.includes("emerging")?"emerging":J.includes("lost")?"lost":J.every(ie=>ie==="pending")?"pending":"not-cited",K=[...new Set(ce.map(ie=>ie.queryId).filter(ie=>!!ie))],he=ce.map(ie=>ie.sourceSnapshotId).filter(ie=>!!ie),qe=ci(re),Re=re.filter(ie=>ie.citationState===fd.cited||ie.citationState==="emerging").length;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-row",onClick:()=>ne(ee),children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("button",{type:"button",className:"query-evidence-query","aria-label":T,"aria-describedby":ue,"aria-expanded":Ne,onClick:ie=>{ie.stopPropagation(),ne(ee)},children:[e.jsx(lc,{size:16,"aria-hidden":"true",className:Ne?"rotate-90":""}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{children:T}),e.jsxs("span",{id:ue,className:"query-evidence-meta",children:[e.jsx("span",{children:wo(E)}),s&&e.jsx("span",{children:te??"No location"}),re.filter(ie=>ie.provider).map(ie=>e.jsx("span",{children:lt(ie.provider)},ie.id))]})]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ri,{state:me,label:ko(me,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":`${Re} of ${re.length} engines ${Z}`,title:`${Re} of ${re.length} engines ${Z}`,children:[Re,"/",re.length]})]})}),x&&e.jsx("td",{children:e.jsx(ql,{queryId:K.length===1?K[0]:null,sourceSnapshotIds:K.length>1?[]:he,queryClass:E,location:s?te:void 0})}),e.jsx("td",{children:e.jsx(bo,{history:qe,signal:h})}),e.jsx("td",{className:"evidence-change-cell",children:pe?e.jsx("span",{className:"query-evidence-new",children:"new query"}):e.jsx(Ro,{items:ce})}),e.jsx("td",{})]}),Ne&&re.map((ie,ge)=>e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-engine-row",children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"text-sm text-secondary",children:ie.provider?lt(ie.provider):"Awaiting engine"})}),e.jsx("td",{children:e.jsx(ri,{state:ie.citationState,className:"rounded-none border-0 bg-transparent p-0 text-sm tracking-normal",label:ko(ie.citationState,h)})}),x&&e.jsx("td",{children:e.jsx(El,{queryId:ie.queryId,sourceSnapshotIds:ie.sourceSnapshotId?[ie.sourceSnapshotId]:[],queryClass:ie.queryClass,provider:ie.provider,location:ie.location??null})}),e.jsx("td",{children:e.jsx(bo,{history:ie.runHistory,signal:h})}),e.jsx("td",{className:"evidence-change-cell",children:pe?null:e.jsx(Ro,{items:[ce[ge]??ie]})}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",className:"min-h-11",type:"button",title:`View ${ie.provider?lt(ie.provider):"saved"} answer for ${ie.query}`,onClick:we=>{we.stopPropagation(),d(ie.id)},children:"View"})})]}),f==="detailed"&&e.jsx("tr",{className:"query-evidence-preview-row",children:e.jsx("td",{colSpan:Q,children:e.jsx(cx,{item:ie,mode:h,onViewFull:()=>d(ie.id)},h)})})]},ie.id))]},ee)})]},L.queryClass??"unclassified"))]})}),w.totalRows===0&&(w.hasQuery||N!=="all"||g)?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Os,{page:w.page,pageSize:w.pageSize,visibleRows:w.rows.length,totalRows:w.totalRows,onPageChange:w.setPage,itemLabel:w.hasQuery||N!=="all"||g?"matches":"queries"})]}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",F==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function lx(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=bd(t),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function hi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function cx({item:t,mode:s,onViewFull:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1);if(s==="mentions")return e.jsx(Po,{item:t,onViewFull:n});const c=t.evidenceUrls.length>0?t.evidenceUrls.map(d=>({uri:d,title:t.groundingSources.find(m=>m.uri===d)?.title})):t.groundingSources;return e.jsxs("div",{className:"query-evidence-preview space-y-3",children:[e.jsx("p",{className:"text-[13px] font-medium text-secondary",children:t.evidenceUrls.length>0?"Cited sources":c.length>0?"Grounding sources":"Cited domains"}),c.length>0?e.jsx("ul",{className:"space-y-4",children:c.slice(0,l?void 0:6).map((d,m)=>e.jsxs("li",{className:"min-w-0",children:[e.jsx(ki,{url:d.uri,title:d.title}),hi(t,yd(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,hi(t,d)?" · competitor source":""]},d))}):e.jsx("p",{className:"text-sm text-secondary",children:"No cited sources captured for this run."}),(c.length>6||c.length===0&&t.citedDomains.length>6)&&e.jsx(P,{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(Po,{item:t,onViewFull:n,contextOnly:!0})]}):e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."})]})}function Po({item:t,onViewFull:s,contextOnly:n=!1}){const{matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}=t,c=o.useMemo(()=>lx({matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}),[a,r,l,i]);if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."});const m=t.answerSnippet.length>No;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(Ti,{headingLevel:4,highlightGroups:c,previewLength:No,children:t.answerSnippet}),(!n&&t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("dl",{className:"space-y-2 text-[13px] leading-6 text-secondary",children:[!n&&t.citedDomains.length>0&&e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Cited domains"}),e.jsxs("dd",{className:"flex flex-wrap gap-x-3 gap-y-1",children:[t.citedDomains.slice(0,6).map(u=>e.jsxs("span",{className:"[overflow-wrap:anywhere]",children:[u,hi(t,u)?" · competitor source":""]},`c-${u}`)),t.citedDomains.length>6&&e.jsxs("span",{children:["+",t.citedDomains.length-6," more"]})]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Competitors in answer"}),e.jsxs("dd",{className:"flex flex-wrap gap-x-3 gap-y-1",children:[t.mentionedCompetitorDomains.slice(0,4).map(u=>e.jsx("span",{className:"[overflow-wrap:anywhere]",children:u},`co-${u}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]})]}),m&&e.jsx(P,{type:"button",variant:"ghost",className:"min-h-11",onClick:u=>{u.stopPropagation(),s()},children:"View full answer"})]})}function Ga({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 fr({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:l=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(i=>e.jsx("button",{type:"button","aria-pressed":s===i,disabled:l,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>{i!==s&&vd("window"),n(i)},children:r?r(i):i},i))})}const Pr=ct[0],Ir=ct[1],Io=ct[2],To=ct[3],dx=["both","server","ga4"],Mo={fontSize:11,paddingTop:6},$o=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Lo=t=>typeof t=="number"?nr(Math.round(t)):String(t),as=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function Tr(t,s){if(!t||s<2)return Array(s).fill(null);const n=t.endIndex-t.startIndex;if(n<=0)return Array(s).fill(null);const a=(t.end-t.start)/n;return Array.from({length:s},(r,l)=>l<t.startIndex||l>t.endIndex?null:t.start+(l-t.startIndex)*a)}function Mr({label:t,value:s,caption:n,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx(Fe,{text:a})]}),e.jsx("p",{className:"text-xl font-semibold text-primary tabular-nums",children:s}),e.jsx("p",{className:"text-xs text-muted mt-0.5",children:n})]})}function ux(t,s){return n=>{const{cx:a,cy:r,index:l,key:i}=n,c=l??-1;return!(t[c]!=null&&t[c-1]==null&&t[c+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function mx({projectName:t,sinceMinutes:s}){const[n,a]=o.useState(!0),[r,l]=o.useState(!0),[i,c]=o.useState("both"),d=sp(t,{sinceMinutes:s,granularity:"day",limit:1}),m=np(t),p=Le({...Dl({client:Y,path:{name:t}}),enabled:!!t,staleTime:yn}).data?.connected===!0,x=Le({...Ol({client:Y,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&p,staleTime:yn}),h=o.useMemo(()=>d.data?.series?.points??[],[d.data]),y=o.useMemo(()=>{const I=x.data;return new Map((I?.days??[]).map(A=>[A.date,A.sessions]))},[x.data]),f=o.useMemo(()=>{const I=w=>w.measured!==!1;if(h.length===0||I(h[0]))return null;const A=h.findIndex(I)-1;return A<0?{from:h[0].bucket,to:h[h.length-1].bucket}:{from:h[0].bucket,to:h[A].bucket}},[h]),b=d.data?.series?.coverageStart??null,N=d.data?.series?.trends,k=o.useMemo(()=>{const I=Tr(N?.crawlerContentHits,h.length),A=Tr(N?.aiUserFetchHits,h.length),w=Tr(N?.aiReferralLandedHits,h.length);return h.map((V,G)=>({...V,crawlerContentHits:V.measured!==!1?as(V.crawlerContentHits):null,aiUserFetchHits:V.measured!==!1?as(V.aiUserFetchHits):null,aiReferralLandedHits:V.measured!==!1?as(V.aiReferralLandedHits):null,ga4Visits:y.get(V.bucket)??null,crawlTrend:I[G],fetchTrend:A[G],visitTrend:w[G]}))},[h,y,N]),$=d.data?.totals,S=$&&{crawlers:as($.crawlerContentHits),fetches:as($.aiUserFetchHits),visits:as($.aiReferralLandedHits)},g=o.useMemo(()=>h.reduce((I,A)=>({crawlers:I.crawlers+as(A.crawlerContentHits),fetches:I.fetches+as(A.aiUserFetchHits),visits:I.visits+as(A.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[h]),v=S??g,C=v.crawlers>0||v.fetches>0||v.visits>0;if(d.isLoading)return e.jsx(ve,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(d.isError)return e.jsxs(ve,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!C){const I=m.data?.sources,A=I!==void 0&&I.length===0,w=!A&&b===null;return e.jsxs(ve,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:A?"No server-side traffic source connected yet.":w?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:A?"Connect a traffic source to see how AI engines read this site over time.":w?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(ve,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Mr,{label:"AI crawlers",value:nr(v.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(Mr,{label:"AI page fetches",value:nr(v.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(Mr,{label:"AI visitors",value:nr(v.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),h.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:as(h[h.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(h[h.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(h[h.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(h[h.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(Fe,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:I=>a(I.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:I=>l(I.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(en,{width:"100%",height:206,children:e.jsxs(tn,{data:k,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(ja,{stroke:ba,vertical:!1}),e.jsx(sn,{dataKey:"bucket",tick:Ut,stroke:ds,tickFormatter:Nn,minTickGap:28}),e.jsx(nn,{tick:Ut,stroke:ds,width:48,allowDecimals:!1}),e.jsx(an,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Tt,formatter:Lo}),f&&e.jsx(ni,{x1:f.from,x2:f.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(dr,{wrapperStyle:Mo,iconType:"plainline",iconSize:14,formatter:I=>$o.has(I)?"":I}),e.jsx(Js,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Pr,fill:Pr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Js,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Ir,fill:Ir,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Ds,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Pr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Ds,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Ir,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(Fe,{text:"Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other."})]}),e.jsx(fr,{windows:dx,value:i,onChange:c,label:"Visit measurement source",formatOption:I=>I==="ga4"?"GA4":I==="both"?"Both":"Server"})]}),e.jsx(en,{width:"100%",height:176,children:e.jsxs(tn,{data:k,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(ja,{stroke:ba,vertical:!1}),e.jsx(sn,{dataKey:"bucket",tick:Ut,stroke:ds,tickFormatter:Nn,minTickGap:28}),e.jsx(nn,{tick:Ut,stroke:ds,width:48,allowDecimals:!1}),e.jsx(an,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Tt,formatter:Lo}),f&&e.jsx(ni,{x1:f.from,x2:f.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(dr,{wrapperStyle:Mo,iconType:"plainline",iconSize:14,formatter:I=>$o.has(I)?"":I}),i!=="ga4"&&e.jsx(Ds,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Io,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Ds,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:To,strokeWidth:1.8,strokeDasharray:"5 3",dot:ux(k.map(I=>I.ga4Visits),To)}),r&&i!=="ga4"&&e.jsx(Ds,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Io,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const hx=6,zn="__other__",Fn="_socialTotal";function px(t,s=hx){const n=new Map;for(const u of t)n.set(u.source,(n.get(u.source)??0)+u.sessions);const a=[...n.entries()].sort((u,p)=>p[1]!==u[1]?p[1]-u[1]:u[0].localeCompare(p[0])),r=a.slice(0,s),l=new Set(r.map(([u])=>u)),i=Math.max(0,a.length-s),c=new Map;for(const u of t){let p=c.get(u.date);p||(p={date:u.date,[Fn]:0},c.set(u.date,p));const x=l.has(u.source)?u.source:zn;p[x]=(p[x]??0)+u.sessions,p[Fn]=(p[Fn]??0)+u.sessions}const d=[...c.values()].sort((u,p)=>String(u.date).localeCompare(String(p.date))),m=r.map(([u])=>u);return i>0&&m.push(zn),{data:d,sources:m,otherCount:i}}function Gn(t){return t.replace(/\+/g," ")}function Sc(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const qo="_totalSessions",Eo="_organicSessions";function xx(t,s){const n=new Map;for(const i of s)n.set(i.date,{[qo]:i.sessions,[Eo]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[qo]:0,[Eo]:0},n.set(i.date,c));for(const d of i.bySource)c[d.source]=(c[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([i],[c])=>i.localeCompare(c)).map(([i,c])=>({date:i,...c})),r=a.map(i=>i.date),l=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:l}}const gx=["7d","30d","90d"],fx={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Ys=ct,pi=us.textDim,Cc=us.textFaint,ra=25;function yx(t){return rc(t.landingPage)}const bx=25,vx=10,$r={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Ka(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function kc(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 jx({projectName:t}){const{data:s,isLoading:n,isError:a}=ap(t);if(n)return e.jsx(ve,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(ve,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!le()&&e.jsx(Ts,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(ve,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!le()&&e.jsxs(e.Fragment,{children:[e.jsx(Ts,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(ve,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(l=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(je,{tone:rp(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?kc(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:le()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Ts,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function Nx({projectName:t}){const[s,n]=o.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(jx,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(fr,{windows:gx,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(wx,{projectName:t,window:s}),e.jsx(mx,{projectName:t,sinceMinutes:fx[s]})]})}function wx({projectName:t,window:s}){const n=hs(),a=s??"30d",[r,l]=o.useState(null),[i,c]=o.useState(null),[d,m]=o.useState(!0),[u,p]=o.useState(!1),[x,h]=o.useState(!1),[y,f]=o.useState(null),[b,N]=o.useState(null),[k,$]=o.useState("sessions"),[S,g]=o.useState("desc"),[v,C]=o.useState("sessions"),[I,A]=o.useState("desc"),[w,V]=o.useState("sessions"),[G,Q]=o.useState("desc"),[B,z]=o.useState("sessions"),[ne,F]=o.useState("desc"),[_,Z]=o.useState($r),[L,ee]=o.useState([]),[T,E]=o.useState([]),[te,re]=o.useState(!1);async function ce(se){m(!0),f(null);try{const Ve=await n.fetchQuery({...Dl({client:Y,path:{name:t}}),staleTime:yn});if(se.current)return;if(l(Ve),!Ve.connected){c(null),Z($r),ee([]),E([]),m(!1);return}const Ie=a==="all"?void 0:a,be=await n.fetchQuery({...jd({client:Y,path:{name:t},query:Ie?{window:Ie}:void 0}),staleTime:yn}),$t=be.windowStart||be.windowEnd?{...be.windowStart?{startDate:be.windowStart}:{},...be.windowEnd?{endDate:be.windowEnd}:{}}:void 0,[Yt,Jt,Ft]=await Promise.all([n.fetchQuery({...Ol({client:Y,path:{name:t},query:Ie?{window:Ie}:void 0}),staleTime:yn}).catch(()=>$r),n.fetchQuery({...Nd({client:Y,path:{name:t},query:Ie?{window:Ie}:void 0}),staleTime:yn}).catch(()=>[]),n.fetchQuery({...wd({client:Y,path:{name:t},query:$t}),staleTime:yn}).catch(()=>[])]);if(se.current)return;c(be),Z(Yt),ee(Jt),E(Ft),m(!1)}catch(Ve){if(se.current)return;f(Ve instanceof Error?Ve.message:"Failed to load GA4 data"),m(!1)}}o.useEffect(()=>{const se={current:!1};return ce(se),()=>{se.current=!0}},[t,a,n]);async function Ne(){p(!0),f(null),N(null);try{const se=await Fl(t);N(`Synced ${se.rowCount.toLocaleString()} page rows, ${se.aiReferralCount.toLocaleString()} AI and ${se.socialReferralCount.toLocaleString()} social referral rows (${se.days} days)`),await Et(n,"ga"),await ce({current:!1})}catch(se){f(se instanceof Error?se.message:"Sync failed")}finally{p(!1)}}async function X(){h(!0),f(null),N(null);try{await Sd(t),await Et(n,"ga"),l({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),N("GA4 disconnected")}catch(se){f(se instanceof Error?se.message:"Disconnect failed")}finally{h(!1)}}function ue(se){K.setPage(1),k===se?g(Ve=>Ve==="desc"?"asc":"desc"):($(se),g("desc"))}function pe(se){v===se?A(Ve=>Ve==="desc"?"asc":"desc"):(C(se),A("desc"))}function J(se){w===se?Q(Ve=>Ve==="desc"?"asc":"desc"):(V(se),Q("desc"))}const me=o.useMemo(()=>i?.topPages?[...i.topPages].sort((se,Ve)=>{const Ie=se[k],be=Ve[k];return typeof Ie=="string"&&typeof be=="string"?S==="asc"?Ie.localeCompare(be):be.localeCompare(Ie):S==="asc"?Ie-be:be-Ie}):[],[i?.topPages,k,S]),K=jn({rows:me,getSearchText:se=>rc(se.landingPage),pageSize:vx}),he=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((se,Ve)=>{const Ie=se[v],be=Ve[v];return typeof Ie=="string"&&typeof be=="string"?I==="asc"?Ie.localeCompare(be):be.localeCompare(Ie):I==="asc"?Ie-be:be-Ie}):[],[i?.aiReferrals,v,I]),qe=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((se,Ve)=>{const Ie=se[B],be=Ve[B];return typeof Ie=="string"&&typeof be=="string"?ne==="asc"?Ie.localeCompare(be):be.localeCompare(Ie):ne==="asc"?Ie-be:be-Ie}):[],[i?.aiReferralLandingPages,B,ne]),Re=jn({rows:qe,getSearchText:yx,pageSize:bx}),ie=Re.totalRows>0?`${Re.totalRows.toLocaleString()} ${Re.hasQuery?Re.totalRows===1?"match":"matches":Re.totalRows===1?"row":"rows"}`:Re.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function ge(se){Re.setPage(1),B===se?F(Ve=>Ve==="desc"?"asc":"desc"):(z(se),F("desc"))}const we=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((se,Ve)=>{const Ie=se[w],be=Ve[w];return typeof Ie=="string"&&typeof be=="string"?G==="asc"?Ie.localeCompare(be):be.localeCompare(Ie):G==="asc"?Ie-be:be-Ie}):[],[i?.socialReferrals,w,G]),{socialChartData:_e,socialChartSources:Ee,socialOtherCount:O}=o.useMemo(()=>{const se=px(T);return{socialChartData:se.data,socialChartSources:se.sources,socialOtherCount:se.otherCount}},[T]),{chartData:D,chartSources:H,dateRange:Me}=o.useMemo(()=>{const se=xx(_,L);return{chartData:se.data,chartSources:se.sources,dateRange:se.dateRange}},[_,L]);if(d&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return le()||ms()?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(Sx,{projectName:t,onConnected:()=>{(async()=>(await Et(n,"ga"),await ce({current:!1})))()}});const Qe=i?.organicSharePctDisplay??"0%",Ge=i?.channelBreakdown?.organic.sharePctDisplay??Qe,et=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,xe=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,jt=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",ze=i?.paidAiSessionsBySession??0,Je=i?.paidAiSharePctBySessionDisplay??"0%",Ot=i?new Set(i.aiReferrals.map(se=>se.source.toLowerCase())).size:0,dt=he[0]??null,st=i?.totalDirectSessions??0,ht=i?.directSharePctDisplay??"0%",kt=i?.channelBreakdown?.direct.sessions??st,Mt=i?.channelBreakdown?.direct.sharePctDisplay??ht,He=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,R=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",$e=i?.socialSessions??0,Te=i?.socialSharePctDisplay??"0%",Ue=i?.channelBreakdown?.social.sessions??$e,ut=i?.channelBreakdown?.social.sharePctDisplay??Te,Be=i?new Set(i.socialReferrals.map(se=>se.source.toLowerCase())).size:0,yt=we[0]??null;return e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:y}),b&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:b}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!le()&&!ms()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:u,onClick:Xe(Ne),children:[e.jsx(va,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Xe(X),children:[e.jsx(Bh,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"mb-4 flex items-start justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Fe,{text:`Aggregated traffic metrics from Google Analytics 4.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]})}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Lr,{value:Ka(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Lr,{value:Ka(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Qe} of total`,tone:"positive"}),e.jsx(Lr,{value:i.totalUsers===null?"—":Ka(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!le()&&!ms()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:u,onClick:Xe(Ne),children:[e.jsx(va,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Fe,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),Me&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Me.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Me.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),D.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:H.length>0?"AI vs. total sessions":"All sessions (baseline)"}),H.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),H.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:D,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(sn,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:ds},tickFormatter:Nn}),e.jsx(nn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...ts,labelFormatter:Tt,formatter:(se,Ve)=>{const Ie=typeof se=="number"?se.toLocaleString():String(se??0),be=String(Ve??"");return be==="_totalSessions"?[Ie,"Total Sessions"]:be==="_organicSessions"?[Ie,"Organic Sessions"]:[Ie,be]}}),e.jsx(dr,{wrapperStyle:{fontSize:11,color:us.text},formatter:se=>se==="_totalSessions"?"Total Sessions":se==="_organicSessions"?"Organic Sessions":se}),e.jsx(Js,{type:"monotone",dataKey:"_totalSessions",stroke:us.textFaint,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),H.map((se,Ve)=>e.jsx(Js,{type:"monotone",dataKey:se,stackId:"ai",stroke:Ys[Ve%Ys.length],fill:Ys[Ve%Ys.length],fillOpacity:.4,strokeWidth:1.5},se))]})})})]}),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(gs,{label:"Organic",value:Ge,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(gs,{label:"Social",value:ut,hint:`${Ue.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(gs,{label:"Direct",value:Mt,hint:`${kt.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(gs,{label:"Visitors from AI (at least)",value:jt,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(gs,{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."})]}),dt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-positive-800/40 bg-positive-500/6 px-4 py-3 text-sm text-positive-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:dt.source})," via ",dt.medium,", accounting for ",dt.sessions.toLocaleString()," sessions.",ze>0&&e.jsxs("span",{children:[" Paid AI: ",ze.toLocaleString()," sessions (",Je,")."]})]})]}),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?`${Ot} 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(rs,{label:"Source",sortKey:"source",current:v,dir:I,onSort:pe,align:"left"}),e.jsx(rs,{label:"Medium",sortKey:"medium",current:v,dir:I,onSort:pe,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(rs,{label:"Sessions",sortKey:"sessions",current:v,dir:I,onSort:pe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:he.map(se=>e.jsx(kx,{referral:se},`${se.source}:${se.medium}:${se.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:ie})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Zs,{value:Re.query,onChange:Re.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Re.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(rs,{label:"Landing Page",sortKey:"landingPage",current:B,dir:ne,onSort:ge,align:"left"}),e.jsx(rs,{label:"Source",sortKey:"source",current:B,dir:ne,onSort:ge,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:B,dir:ne,onSort:ge,align:"right"})]})}),e.jsx("tbody",{children:Re.rows.map(se=>e.jsx(Ax,{row:se},`${se.landingPage}:${se.source}:${se.medium}:${se.sourceDimension}`))})]})}),e.jsx(Os,{page:Re.page,pageSize:Re.pageSize,visibleRows:Re.rows.length,totalRows:Re.totalRows,onPageChange:Re.setPage,itemLabel:Re.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:()=>Re.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Fe,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(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(gs,{label:"Social Sessions",value:Ka($e),hint:`${$e.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(gs,{label:"Share of Traffic",value:Te,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(gs,{label:"Platforms",value:String(Be),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."})]}),yt&&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:`${yt.source} via ${yt.medium}`,children:Sc(Gn(yt.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:yt.medium,children:["via ",Gn(yt.medium)," · ",yt.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(gs,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(gs,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(gs,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),_e.length>0&&e.jsxs(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"})]}),O>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ee.length-1," sources · ",O," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:_e,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(sn,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:ds},tickFormatter:Nn}),e.jsx(nn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...ts,labelFormatter:Tt,formatter:(se,Ve)=>{const Ie=typeof se=="number"?se.toLocaleString():String(se??0),be=String(Ve??"");if(be===Fn)return[Ie,"Total Social"];if(be===zn){const $t=`Other (${O} source${O===1?"":"s"})`;return[Ie,$t]}return[Ie,Gn(be)]}}),e.jsx(Js,{type:"monotone",dataKey:Fn,stroke:Cc,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ee.map((se,Ve)=>{const be=se===zn?pi:Ys[Ve%Ys.length];return e.jsx(Js,{type:"monotone",dataKey:se,stackId:"social",stroke:be,fill:be,fillOpacity:.4,strokeWidth:1.5},se)})]})})}),e.jsx(Px,{sources:Ee,otherCount:O})]}),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?we.length>ra&&!te?`Top ${ra} of ${we.length}`:`${we.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(rs,{label:"Source",sortKey:"source",current:w,dir:G,onSort:J,align:"left"}),e.jsx(rs,{label:"Medium",sortKey:"medium",current:w,dir:G,onSort:J,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:w,dir:G,onSort:J,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(te?we:we.slice(0,ra)).map(se=>e.jsx(Rx,{referral:se},`${se.source}:${se.medium}:${se.channelGroup}`))})]})}),we.length>ra&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>re(se=>!se),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:te?`Show top ${ra}`:`Show all ${we.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),i&&i.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Fe,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx(Zs,{value:K.query,onChange:K.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(rs,{label:"Landing Page",sortKey:"landingPage",current:k,dir:S,onSort:ue,align:"left"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:k,dir:S,onSort:ue,align:"right"}),e.jsx(rs,{label:"Organic",sortKey:"organicSessions",current:k,dir:S,onSort:ue,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:K.rows.map(se=>e.jsx(Cx,{page:se},se.landingPage))})]})}),K.totalRows===0&&K.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Os,{page:K.page,pageSize:K.pageSize,visibleRows:K.rows.length,totalRows:K.totalRows,onPageChange:K.setPage,itemLabel:K.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 ${kc(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Sx({projectName:t,onConnected:s}){const[n,a]=o.useState(""),[r,l]=o.useState(null),[i,c]=o.useState(null),[d,m]=o.useState(!1),[u,p]=o.useState(null),x=o.useRef(null),h=o.useCallback(f=>{const b=f.target.files?.[0];if(!b)return;p(null),l(b.name);const N=new FileReader;N.onload=()=>{const k=N.result;try{const $=JSON.parse(k);if(!$.client_email||!$.private_key){p("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),c(null);return}c(k)}catch{p("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},N.onerror=()=>{p("Failed to read file."),c(null)},N.readAsText(b)},[]);async function y(){if(p(null),!n.trim()){p("Property ID is required.");return}if(!i){p("Please upload a service account key file.");return}m(!0);try{await Cd(t,{propertyId:n.trim(),keyJson:i});try{await Fl(t)}catch{}s()}catch(f){p(f instanceof Error?f.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:f=>a(f.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:x,type:"file",accept:".json,application/json",onChange:h,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>x.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(Vh,{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(P,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:Xe(y),children:d?"Connecting & syncing…":"Connect GA4"})]})}function rs({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 Ac={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Lr({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 ${Ac[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function gs({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Fe,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Ac[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Cx({page:t}){const s=Ze(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 Rc={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Pc={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 kx({referral:t}){const s=Ze(t.share),n=Rc[t.sourceDimension]??t.sourceDimension,a=Pc[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 Ax({row:t}){const s=Rc[t.sourceDimension]??t.sourceDimension,n=Pc[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(rr,{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 Rx({referral:t}){const s=Ze(t.share),n=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Gn(t.source),r=Gn(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 Px({sources:t,otherCount:s}){const n=[{key:Fn,color:Cc,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===zn)n.push({key:zn,color:pi,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Gn(r);n.push({key:r,color:Ys[a%Ys.length]??pi,label:Sc(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 Ix(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 Tx="Search Console is not connected yet. Your Canonry team can set this up.",Mx=["7d","30d","90d","all"],_a=500,Do=[{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:Hn.caution,format:t=>Ze(t)},{key:"position",label:"Avg position",color:ct[2],inverted:!0,format:t=>t.toFixed(1)}],Hs=25,$x="canonry:google-oauth-complete";function Lx(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const i=t.prior[s],c=t.trailing[s];return i!==null&&c!==null&&i<=0&&c>0?`new in the last ${a}d`:i===null||i<=0?`no prior ${a}d to compare`:c===null?`no value in the last ${a}d`:"comparison unavailable"}return r===0?`→ no change vs prior ${a}d`:`${(n?r<0:r>0)?"↑":"↓"} ${Ze(Math.abs(r))} vs prior ${a}d`}function qx(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,l=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,c=`${r.startDate} to ${r.endDate}`,d=`Tile percentages compare these ${s} ${l} (${c}) with the ${s} ${l} before them (${i}).`;return n!=="split-window"?d:`${d} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function Oo(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Fo(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 Go(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Ex({projectName:t,refreshNonce:s}){const n=hs(),{isAdmin:a}=rn(),r=ms(),[l,i]=o.useState(!1),[c,d]=o.useState([]),[m,u]=o.useState([]),[p,x]=o.useState([]),[h,y]=o.useState(null),[f,b]=o.useState([]),[N,k]=o.useState([]),[$,S]=o.useState(null),[g,v]=o.useState(""),[C,I]=o.useState(""),[A,w]=o.useState("30"),[V,G]=o.useState(!1),[Q,B]=o.useState("30d"),[z,ne]=o.useState(["clicks","impressions"]),[F,_]=o.useState(!0),[Z,L]=o.useState(null),[ee,T]=o.useState(0),[E,te]=o.useState({startDate:"",endDate:"",query:"",page:""}),[re,ce]=o.useState(0),[Ne,X]=o.useState(!1),[ue,pe]=o.useState(0),[J,me]=o.useState(!1),[K,he]=o.useState(""),[qe,Re]=o.useState(!0),[ie,ge]=o.useState(!1),[we,_e]=o.useState(!1),[Ee,O]=o.useState(!1),[D,H]=o.useState(!1),[Me,Qe]=o.useState(!1),[Ge,et]=o.useState(!1),[xe,jt]=o.useState(null),[ze,Je]=o.useState(!1),[Ot,dt]=o.useState(!1),[st,ht]=o.useState(null),[kt,Mt]=o.useState(null),[He,R]=o.useState([]),[$e,Te]=o.useState(new Set),[Ue,ut]=o.useState({}),[Be,yt]=o.useState(new Set),[se,Ve]=o.useState(""),[Ie,be]=o.useState(null),[$t,Yt]=o.useState(""),[Jt,Ft]=o.useState(!1),[mt,Zt]=o.useState(!1),[ot,fs]=o.useState(!1),[ps,Ks]=o.useState(!1),[bt,_s]=o.useState("indexed"),[Lt,ss]=o.useState(null),Vt=!!(E.query.trim()||E.page.trim()||Lt),pt=Lt!==null,$s=o.useMemo(()=>{if(!Lt)return p;const{key:j,dir:W}=Lt;return[...p].sort((de,Se)=>{const rt=j===bn.CTR?Number.isFinite(de.ctr)?de.ctr:0:de[j],tt=j===bn.CTR?Number.isFinite(Se.ctr)?Se.ctr:0:Se[j];return W==="asc"?rt-tt:tt-rt})},[p,Lt]),Rt=jn({rows:$s,pageSize:qs}),Ls=J?Rt.rows:$s,Xt=jn({rows:(st??[]).filter(j=>j.path.toLowerCase().includes(se.trim().toLowerCase())),pageSize:qs}),[Pt,Gt]=o.useState([]),[nt,xs]=o.useState(null),[ys,U]=o.useState(1),oe=o.useMemo(()=>{if(Pt.length<2)return null;const j=Pt[Pt.length-1],W=Pt[Pt.length-2];return{indexed:j.indexed-W.indexed,notIndexed:j.notIndexed-W.notIndexed}},[Pt]);o.useEffect(()=>{U(1)},[xe,bt,nt]);const ke=o.useMemo(()=>nt?(xe?.reasonGroups??[]).find(j=>j.reason===nt):void 0,[xe,nt]),ae=o.useMemo(()=>xe?bt==="indexed"?xe.indexed:bt==="deindexed"?xe.deindexed:bt==="notIndexed"?nt?ke?.urls??[]:(xe.reasonGroups??[]).length===0?xe.notIndexed:[]:[]:[],[xe,bt,nt,ke]),Pe=Math.max(1,Math.ceil(ae.length/Hs)),Ke=Math.min(Math.max(1,ys),Pe),gt=(Ke-1)*Hs,vt=o.useMemo(()=>xe?.indexed.slice(gt,gt+Hs)??[],[xe,gt]),Us=o.useMemo(()=>xe?.notIndexed.slice(gt,gt+Hs)??[],[xe,gt]),q=o.useMemo(()=>xe?.deindexed.slice(gt,gt+Hs)??[],[xe,gt]),Ae=o.useMemo(()=>(ke?.urls??[]).slice(gt,gt+Hs),[ke,gt]),[at,Nt]=o.useState(!1),[es,Oe]=o.useState(null),[St,Bs]=o.useState(null),[Wn,ns]=o.useState(null);function Yn(j,W){const de=ip(j),Se=Ix(de);Se?(Bs(Se),Oe(null)):(Bs(null),Oe(de.message||W))}const It=c.find(j=>j.connectionType==="gsc"),bs=(It?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),Jn=He.length>0?He:(st??[]).map(j=>j.path),Vs=Jn.filter(j=>st?.some(W=>W.path===j&&W.isSitemapsIndex)).length,Xn=Vs===1?"Resubmit sitemap index":Vs>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Ia=p.length>0||f.length>0||N.length>0,on=kd(),Zn=Ad();async function Sn(j,W=!1){if(r){u([]);return}if(!j){u([]),v("");return}_e(!0);try{const{sites:de}=await n.fetchQuery({..._d({client:Y,path:{name:t}}),staleTime:W?0:Ht});u(de),v(j.propertyId??de[0]?.siteUrl??""),Bs(null)}catch(de){u([]),Yn(de,"Failed to load Search Console properties")}finally{_e(!1)}}async function Cn(j){H(!0);const W=j??re;try{const de=Vt?_a:qs,Se=Vt?0:W,rt={limit:String(de)};E.startDate&&(rt.startDate=E.startDate),E.endDate&&(rt.endDate=E.endDate),E.query&&(rt.query=E.query),E.page&&(rt.page=E.page),Se>0&&(rt.offset=String(Se)),Q&&Q!=="all"&&!E.startDate&&(rt.window=Q);const tt=await n.fetchQuery({...Td({client:Y,path:{name:t},query:rt}),staleTime:Ht}),xt=tt.rows;Vt?(X(!1),x(xt),pe(xt.length),me(!0)):(X(Se+xt.length<tt.totalMatching),x(xt),pe(0),me(!1))}catch(de){x([]),X(!1),pe(0),Oe(de instanceof Error?de.message:"Failed to load GSC performance data")}finally{H(!1)}}async function Ta(){try{const j={};E.startDate&&(j.startDate=E.startDate),E.endDate&&(j.endDate=E.endDate),Q&&Q!=="all"&&!E.startDate&&(j.window=Q);const W=await n.fetchQuery({...Id({client:Y,path:{name:t},query:j}),staleTime:Ht});y(W)}catch{y(null)}}async function zs(j=!1){Qe(!0);try{const W=K.trim()||void 0,de={limit:"20"};W&&(de.url=W);const[Se,rt]=await Promise.all([n.fetchQuery({...Gd({client:Y,path:{name:t},query:de}),staleTime:j?0:Ht}),n.fetchQuery({...Kd({client:Y,path:{name:t}}),staleTime:j?0:Ht})]);b(Se),k(rt)}catch(W){b([]),k([]),Oe(W instanceof Error?W.message:"Failed to load GSC inspection history")}finally{Qe(!1)}}async function Ma(j=!1){Je(!0);try{const[W,de]=await Promise.all([n.fetchQuery({...Ld({client:Y,path:{name:t}}),staleTime:j?0:Ht}),n.fetchQuery({...qd({client:Y,path:{name:t}}),staleTime:j?0:Ht}).catch(()=>[])]);jt(W),Gt(de)}catch(W){jt(null),Gt([]),Oe(W instanceof Error?W.message:"Failed to load coverage data")}finally{Je(!1)}}async function ln(j){Nt(!0),Oe(null);try{const W=await so(t,{urls:j}),{succeeded:de,failed:Se,total:rt}=W.summary;De({title:"Indexing requested",detail:Se===0?`${de} URL${de!==1?"s":""} submitted for indexing.`:`${de}/${rt} submitted successfully, ${Se} failed.`,tone:Se===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(W){Oe(W instanceof Error?W.message:"Failed to request indexing")}finally{Nt(!1)}}async function kn(){Nt(!0),Oe(null);try{const j=await so(t,{urls:[],allUnindexed:!0}),{succeeded:W,failed:de,total:Se}=j.summary;De({title:"Indexing requested",detail:de===0?`${W} unindexed URL${W!==1?"s":""} submitted for indexing.`:`${W}/${Se} submitted successfully, ${de} failed.`,tone:de===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(j){Oe(j instanceof Error?j.message:"Failed to request indexing")}finally{Nt(!1)}}async function cn(){dt(!0),Oe(null);try{const j=await Nr(t);n.setQueryData(Ed({client:Y,path:{name:t}}),j),ht(j.sitemaps),Mt(j.summary),R(j.preferredSubmissionUrls),Te(new Set),ut({}),j.sitemaps.length===0&&ns("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(j){Oe(j instanceof Error?j.message:"Failed to list sitemaps")}finally{dt(!1)}}async function ea(j){const W=$e.has(j);if(Te(de=>{const Se=new Set(de);return W?Se.delete(j):Se.add(j),Se}),!(W||Ue[j])){yt(de=>new Set(de).add(j));try{const de=await Nr(t,j);ut(Se=>({...Se,[j]:de.sitemaps}))}catch(de){Oe(de instanceof Error?de.message:"Failed to load sitemap files")}finally{yt(de=>{const Se=new Set(de);return Se.delete(j),Se})}}}async function vs(j){if(!bs||j.length===0)return;const W=[...new Set(j)];Zt(!0),Oe(null),be({completed:0,total:W.length});let de=0,Se=0,rt=0,tt=null;try{for(let qt=0;qt<W.length;qt+=50){const it=W.slice(qt,qt+50);try{const Ce=await Dd(t,it);de+=Ce.summary.accepted,Se+=Ce.summary.failed,rt+=it.length,be({completed:rt,total:W.length})}catch(Ce){rt+=it.length;const js=it.length,dn=W.length-rt,Rn=Ce instanceof Error?Ce.message:"The batch request failed",Ns=`${de} accepted, ${Se} failed, ${js} unconfirmed, ${dn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;tt=`Sitemap submission stopped after a batch request failed. ${Ns} ${Rn}`,Oe(tt),De({title:"Sitemap resubmission partially completed",detail:Ns,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const xt=W.length;De({title:Se===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:Se===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${de}/${xt} sitemap submissions; ${Se} failed. Indexing is not guaranteed.`,tone:Se===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Yt("")}catch(xt){Oe(xt instanceof Error?xt.message:"Failed to submit sitemap to Google")}finally{Zt(!1),be(null),await cn(),tt&&Oe(tt)}}async function ta(){Zt(!0);const j=st??[];try{const W=j.filter(Se=>Se.isSitemapsIndex),de=[];for(let Se=0;Se<W.length;Se+=4)(await Promise.all(W.slice(Se,Se+4).map(async tt=>{const xt=Ue[tt.path];if(xt)return xt;const qt=await Nr(t,tt.path);return ut(it=>({...it,[tt.path]:qt.sitemaps})),qt.sitemaps}))).forEach((tt,xt)=>{de.push(...tt.length>0?tt.map(qt=>qt.path):[W[Se+xt].path])});await vs([...j.filter(Se=>!Se.isSitemapsIndex).map(Se=>Se.path),...de])}catch(W){Oe(W instanceof Error?W.message:"Failed to load sitemap files"),Zt(!1)}}async function sa(j){Ft(!0),Oe(null);try{await Od(t,"gsc",j),await Et(n,"google"),d(W=>W.map(de=>de.connectionType==="gsc"?{...de,sitemapUrl:j}:de)),De({title:"Default sitemap updated",detail:j,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(W){Oe(W instanceof Error?W.message:"Failed to set the default sitemap")}finally{Ft(!1)}}async function $a(j){try{await Zn.mutateAsync({projectName:t,projectLabel:t,opts:j?{sitemapUrl:j}:void 0})}catch{}}async function La(){Re(!0),Oe(null);try{const[j,W]=await Promise.all([r||!a?Promise.resolve(null):Gl().catch(()=>null),n.fetchQuery({...Ai({client:Y,path:{name:t}}),staleTime:Ht}).catch(()=>[])]);i(!!j?.google?.configured),d(W);const de=W.find(Se=>Se.connectionType==="gsc");await Promise.all([r?Promise.resolve():Sn(de),Cn(),Ta(),zs(),Ma(),!r&&de?.propertyId?cn():Promise.resolve()])}finally{Re(!1)}}o.useEffect(()=>{La()},[t,s,a]),o.useEffect(()=>{ce(0),L(null),te(j=>j.startDate||j.endDate?{...j,startDate:"",endDate:""}:j),T(j=>j+1),Ta()},[Q]);const yr=o.useRef(!1);o.useEffect(()=>{if(!yr.current){yr.current=!0;return}ce(0),Rt.setPage(1),Cn(0)},[ee]);function Qs(j){const W=Z===j?null:j;L(W),te(de=>({...de,startDate:W??"",endDate:W??""})),T(de=>de+1)}const na=o.useRef(!1);o.useEffect(()=>{if(!na.current){na.current=!0;return}ce(0),Cn(0)},[pt]);async function aa(){if(!l){Oe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}ge(!0),Oe(null),ns(null);try{let j=function(Ce){if(Ce.source!==Se||Ce.origin!==rt||!Ce.data||typeof Ce.data!="object")return;const js=Ce.data;js.type!==$x||js.connectionType!=="gsc"||it(!0)};const{authUrl:W,redirectUri:de}=await $d(t,"gsc");if(!W.startsWith("https://accounts.google.com/")){Oe("Unexpected OAuth redirect URL. Please try again.");return}const Se=window.open(W,"_blank","width=600,height=700");if(!Se){window.location.assign(W);return}const rt=de?new URL(de).origin:window.location.origin;let tt=!1,xt=null;const qt=()=>{xt!==null&&window.clearInterval(xt),window.removeEventListener("message",j)},it=async Ce=>{if(!tt){tt=!0,qt(),ns(Ce?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Et(n,"google"),await La()}finally{ns(null)}}};window.addEventListener("message",j),ns("Finish the Google consent flow in the popup. This page will refresh automatically."),xt=window.setInterval(()=>{Se.closed&&it(!1)},1e3)}catch(j){Oe(j instanceof Error?j.message:"Failed to start OAuth flow")}finally{ge(!1)}}async function br(){Oe(null),ns(null);try{await Md(t,"gsc"),await Et(n,"google"),d(j=>j.filter(W=>W.connectionType!=="gsc")),u([]),v("")}catch(j){Oe(j instanceof Error?j.message:"Failed to disconnect")}}async function An(){if(g){O(!0),Oe(null);try{await Ud(t,"gsc",g),await Et(n,"google"),d(j=>j.map(W=>W.connectionType==="gsc"?{...W,propertyId:g}:W)),De({title:"GSC property updated",detail:`${t} is now linked to ${g}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(j){Oe(j instanceof Error?j.message:"Failed to save GSC property")}finally{O(!1)}}}async function qa(){Oe(null),ns(null);try{await on.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(A,10)||void 0,full:V||void 0}}),await Et(n,"gsc")}catch{}}async function Ea(){if(C.trim()){et(!0),Oe(null),ns(null);try{const j=await Fd(t,C.trim());await Et(n,"gsc"),S(j),I(""),await zs()}catch(j){Oe(j instanceof Error?j.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"})]})}),St&&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:St.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:St.message}),(Pn(St.enableUrl)||Pn(St.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Pn(St.enableUrl)&&e.jsx("a",{href:Pn(St.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),Pn(St.indexingApiUrl)&&e.jsx("a",{href:Pn(St.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:()=>Bs(null),children:"×"})]})}),es&&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:[es,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Oe(null),children:"×"})]}),Wn&&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:[Wn,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>ns(null),children:"×"})]}),qe?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[It?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:It.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",xe?.lastInspectedAt?Wt(xe.lastInspectedAt):"never"]}),!r&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Xe(br),children:"Disconnect"})]}):a?e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(je,{tone:l?"caution":"negative",children:l?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:l?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[l?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ie,onClick:Xe(aa),children:ie?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ts,{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:Tx})}),(It||Ia)&&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(Fe,{text:`${qx(h?.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 ${_a.toLocaleString()} matching rows while the table shows ${qs} per page.`})]}),h?.window?.startDate&&h.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[h.window.startDate," to ",h.window.endDate,(h.window.daysSinceLatestData??0)>0&&` · latest data ${h.window.daysSinceLatestData} day${h.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fr,{windows:Mx,value:Q,onChange:j=>{B(j),ce(0),Rt.setPage(1)},label:"Search Console time period",formatOption:j=>j==="all"?"All":j}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:D,onClick:()=>{ce(0),Rt.setPage(1),Cn(0),Ta()},children:D?"Loading…":"Apply filters"})]})]}),h&&h.daily.length>0&&(()=>{const{totals:j,daily:W,trends:de,periodComparison:Se}=h,tt=Do.filter(Ce=>z.includes(Ce.key)).map(Ce=>({dataKey:Ce.key,label:Ce.label,color:Ce.color,axisId:Ce.key,inverted:Ce.inverted,formatValue:Ce.format,trend:F?de?.[Ce.key]??null:null})),xt=Ce=>j[Ce]??null,qt=new Map(W.map(Ce=>[Ce.date,Ce])),it=W.length===0?[]:Rd(W[0].date,W[W.length-1].date).map(Ce=>qt.get(Ce)??{date:Ce});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Do.map(Ce=>{const js=z.includes(Ce.key),dn=xt(Ce.key),Rn=dn===null;return e.jsxs("button",{type:"button","aria-pressed":js,disabled:Rn,className:`rounded-md border px-3 py-2 text-left transition-colors ${js?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Rn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{ne(Ns=>Ns.includes(Ce.key)?Ns.length===1?Ns:Ns.filter(vr=>vr!==Ce.key):[...Ns,Ce.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:js?Ce.color:"transparent",border:`1px solid ${Ce.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:Ce.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:dn===null?"—":Ce.format(dn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Lx(Se,Ce.key,Ce.inverted)})]},Ce.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:F,onChange:Ce=>_(Ce.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(oc,{data:it,xKey:"date",series:tt,xTickFormatter:Nn,labelFormatter:Tt,onSelectX:Qs,selectedX:Z})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:W.map(Ce=>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":Z===Ce.date,onClick:()=>Qs(Ce.date),children:[Tt(Ce.date),": ",Ce.clicks," clicks, ",Ce.impressions," impressions"]},Ce.date))}),Z&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Tt(Z)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Qs(Z),children:["Show all ",j.days," days"]})]}),j.position!==null&&(j.positionDays??j.days)<j.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",j.positionDays," of ",j.days," days. The rest have no property-level position recorded."]}),(j.position===null||j.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:E.startDate,onChange:j=>te(W=>({...W,startDate:j.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:E.endDate,onChange:j=>te(W=>({...W,endDate:j.target.value}))}),e.jsx(Zs,{value:E.query,onChange:j=>te(W=>({...W,query:j})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Zs,{value:E.page,onChange:j=>te(W=>({...W,page:j})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),p.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(bn).map(j=>e.jsx("th",{className:"text-right","aria-sort":Lt?.key===j?Lt.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{Rt.setPage(1),ss(W=>W?.key===j?W.dir==="desc"?{key:j,dir:"asc"}:null:{key:j,dir:"desc"})},children:[Pd[j],Lt?.key===j?Lt.dir==="desc"?" ↓":" ↑":""]})},j))]})}),e.jsx("tbody",{children:Ls.map((j,W)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:j.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:j.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(rr,{value:j.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:j.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.impressions.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ze(j.ctr)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.position.toFixed(1)})]},`${j.date}:${j.query}:${j.page}:${W}`))})]})}),e.jsx(Os,{page:J?Rt.page:Math.floor(re/qs)+1,pageSize:qs,visibleRows:Ls.length,totalRows:J?ue:void 0,hasNextPage:J?void 0:Ne,disabled:D,itemLabel:J?"matches":"rows",onPageChange:j=>{if(J){Rt.setPage(j);return}const W=(j-1)*qs;ce(W),Cn(W)}}),J&&ue>=_a?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",_a.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(Fe,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[xe&&xe.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:at,onClick:()=>{kn()},children:at?"Requesting…":`Request indexing (${xe.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ze,onClick:()=>{Ma(!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 j=xe.summary.indexedShare??0,W=xe.summary.notIndexedShare??0,de=54,Se=2*Math.PI*de,rt=Se*(1-j),tt=Se*W,xt=Se*j;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:us.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:Hn.positiveDeep,strokeWidth:"14",strokeDasharray:Se,strokeDashoffset:rt,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:us.textFaint,strokeWidth:"14",strokeDasharray:`${tt} ${Se-tt}`,strokeDashoffset:-xt,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:Ze(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(j=>{const W=j==="indexed"?xe.indexed.length:j==="notIndexed"?xe.notIndexed.length:xe.deindexed.length,de=j==="indexed"?"Indexed":j==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":bt===j,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${bt===j?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{_s(j),xs(null)},children:[de," (",W,")"]},j)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[bt==="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:vt.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.crawlTime?j.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:j.isMobileFriendly===!0?"Yes":j.isMobileFriendly===!1?"No":"—"})]},j.id))})]}),bt==="notIndexed"&&!nt&&(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(j=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>xs(j.reason),onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),xs(j.reason))},tabIndex:0,role:"button","aria-label":`View ${j.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:j.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.count})]},j.reason))})]}),bt==="notIndexed"&&!nt&&(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:Us.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.coverageState??"Unknown"})]},j.id))})]}),bt==="notIndexed"&&nt&&(()=>{const j=(xe.reasonGroups??[]).find(W=>W.reason===nt);return j?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>xs(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:j.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[j.count," affected page",j.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:at,onClick:()=>{ln(j.urls.map(W=>W.url))},children:at?"Requesting…":`Request indexing (${j.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Ae.map(W=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:W.url}),e.jsx("td",{className:"text-secondary",children:W.crawlTime?W.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:at,onClick:()=>{ln([W.url])},title:"Request indexing",children:"Index"})})]},W.id))})]})]}):null})(),bt==="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:q.map((j,W)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.previousState}),e.jsx("td",{className:"text-secondary",children:j.currentState}),e.jsx("td",{className:"text-secondary",children:j.transitionDate.split("T")[0]})]},`${j.url}-${W}`))})]}),(bt==="indexed"&&xe.indexed.length===0||bt==="notIndexed"&&!nt&&xe.notIndexed.length===0||bt==="deindexed"&&xe.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Os,{page:Ke,pageSize:Hs,visibleRows:Math.min(Hs,ae.length-gt),totalRows:ae.length,onPageChange:U,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":ps,onClick:()=>Ks(j=>!j),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:ps?"Hide snapshots":Pt.length>0?`View ${Pt.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.",oe&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",oe.indexed>=0?"+":"",oe.indexed.toLocaleString()," indexed, ",oe.notIndexed>=0?"+":"",oe.notIndexed.toLocaleString()," not indexed."]})]}),ps&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:Pt.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:Pt.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:j.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:j.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:j.notIndexed.toLocaleString()})]},j.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children: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(Fe,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Ot||!It?.propertyId,onClick:()=>{cn()},children:Ot?"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:$t,onChange:j=>Yt(j.target.value),onKeyDown:j=>j.key==="Enter"&&void vs([$t.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!bs||mt||!$t.trim(),onClick:()=>{vs([$t.trim()])},children:mt?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!bs||mt||Jn.length===0,onClick:()=>{vs(Jn)},children:mt?"Resubmitting…":Xn}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!bs||mt||!st?.length,onClick:()=>{ta()},children:"Resubmit all files"}),kt&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",kt.indexes," index",kt.indexes===1?"":"es",", ",kt.files," file",kt.files===1?"":"s"]}),Ie&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Ie.completed,"/",Ie.total]})]}),!bs&&It&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:Xe(aa),children:"Reconnect"})]}),st&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:st.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Zs,{value:se,onChange:j=>{Ve(j),Xt.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:Xt.rows.flatMap(j=>{const W=Oo(j),de=Fo(j),Se=Go(j),rt=Ue[j.path]??[],tt=$e.has(j.path),xt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(rr,{value:j.path})}),e.jsx("td",{className:"text-secondary",children:j.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":tt,"aria-label":`${tt?"Collapse":"Expand"} files in ${j.path}`,onClick:()=>{ea(j.path)},children:Be.has(j.path)?"Loading…":`${tt?"▾":"▸"} Index${Ue[j.path]?` (${rt.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:Se}),e.jsx("td",{className:"text-secondary",children:j.lastSubmitted?j.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:j.lastDownloaded?j.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:W.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:!bs||mt,onClick:()=>{vs([j.path])},children:j.lastSubmitted?"Resubmit to Google":"Submit to Google"}),It?.sitemapUrl===j.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Jt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{sa(j.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Zn.isPending,onClick:()=>{$a(j.path)},children:"Inspect URLs"})]})})]},j.path),qt=j.isSitemapsIndex&&tt?rt.map(it=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(rr,{value:it.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Go(it)}),e.jsx("td",{className:"text-secondary",children:it.lastSubmitted?it.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:it.lastDownloaded?it.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Oo(it).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Fo(it)||"—"}),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:!bs||mt,onClick:()=>{vs([it.path])},children:"Resubmit"}),It?.sitemapUrl===it.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:Jt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{sa(it.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Zn.isPending,onClick:()=>{$a(it.path)},children:"Inspect URLs"})]})})]},`${j.path}:${it.path}`)):[];return[xt,...qt]})})]}),e.jsx(Os,{page:Xt.page,pageSize:qs,visibleRows:Xt.rows.length,totalRows:Xt.totalRows,onPageChange:Xt.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:C,onChange:j=>I(j.target.value),onKeyDown:j=>j.key==="Enter"&&void Ea()}),e.jsx(P,{type:"button",size:"sm",disabled:Ge||!It?.propertyId||!C.trim(),onClick:Xe(Ea),children:Ge?"Inspecting…":"Inspect URL"})]}),$&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:$.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:$.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:to($.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:Wt($.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(P,{type:"button",variant:"outline",size:"sm",disabled:Me,onClick:()=>{zs(!0)},children:Me?"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:K,onChange:j=>he(j.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Me,onClick:()=>{zs(!0)},children:"Apply filter"})]}),f.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:f.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-neutral",children:j.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:j.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:to(j.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Wt(j.inspectedAt)})]},j.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(ve,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),N.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:N.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:j.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Wt(j.transitionDate)})]},`${j.url}:${j.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),It&&!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:()=>fs(j=>!j),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${ot?"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"})]})}),ot&&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(Fe,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:g,disabled:we||m.length===0,onChange:j=>v(j.target.value),children:m.length===0?e.jsx("option",{value:"",children:we?"Loading properties…":"No properties available"}):m.map(j=>e.jsxs("option",{value:j.siteUrl,children:[j.siteUrl," · ",j.permissionLevel]},j.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:we,onClick:()=>{Sn(It,!0)},children:we?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!g||Ee,onClick:Xe(An),children:Ee?"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:A,onChange:j=>w(j.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:V,onChange:j=>G(j.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:on.isPending||!It.propertyId,onClick:Xe(qa),children:on.isPending?"Queueing…":"Queue sync"}),!It.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Dx=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Ox({projectName:t,projectId:s}){const n=hs(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),m=Le(Ai({client:Y,path:{name:t}})),u=m.data?.find(X=>X.connectionType==="gbp"),p=!!u,x=a?{locationName:a}:void 0,h=Le({...Bd({client:Y,path:{name:t}}),enabled:p}),y=Le({...Vd({client:Y,path:{name:t},query:x}),enabled:p}),f=Le({...zd({client:Y,path:{name:t},query:x}),enabled:p}),b=Le({...Qd({client:Y,path:{name:t},query:x}),enabled:p}),N=Le({...Hd({client:Y,path:{name:t},query:x}),enabled:p}),k=Le({...Wd({client:Y,path:{name:t},query:x}),enabled:p}),$=Le({queryKey:["gbp-section-insights",t],queryFn:()=>Yd(t),enabled:p});function S(){Et(n,"gbp")}const g=Dt({...Jd(),onSuccess:X=>{Kl({id:X.runId,projectId:s,kind:Gs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),De({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=o.useSyncExternalStore(_l,or,or),C=Object.values(v.runs).some(X=>X.kind===Gs["gbp-sync"]&&X.projectId===s),I=g.isPending||C,A=Dt({...Xd(),onSuccess:()=>S()});if(o.useEffect(()=>{if(!a||!h.data)return;const X=h.data.locations.filter(ue=>ue.selected);(X.length<=1||!X.some(ue=>ue.locationName===a))&&r(null)},[a,h.data]),o.useEffect(()=>{if(!l||!h.data)return;(a?[a]:h.data.locations.filter(ue=>ue.selected).map(ue=>ue.locationName)).includes(l)||i(null)},[l,h.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((ue,pe)=>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:pe+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ue.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-bg-elevated/80 px-2 py-1 font-mono text-xs text-neutral",children:ue.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ue.note})]})]},ue.title))})]})})}const w=y.data,V=h.data?.locations??[],G=V.filter(X=>X.selected),Q=f.data?.keywords??[],B=b.data?.lodging??[],z=N.data?.placeActions??[],ne=k.data?.places??[],F=V.length>0?V[0].accountName:u.domain,_=a?V.find(X=>X.locationName===a)?.displayName??null:null,Z=a?V.filter(X=>X.locationName===a):G,L=new Set(Z.map(X=>X.locationName)),ee=B.filter(X=>L.has(X.locationName)),T=z.filter(X=>L.has(X.locationName)),E=ne.filter(X=>L.has(X.locationName)),te=new Set(G.map(X=>X.locationName)),re=a?Q:Q.filter(X=>te.has(X.locationName)),ce=!a&&G.length>1,Ne=($.data??[]).filter(X=>!X.dismissed&&Dx.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(Fe,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{tone:"positive",children:"Connected"}),!le()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:I,onClick:()=>g.mutate({client:Y,path:{name:t},body:{}}),children:I?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[F?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:F})," · "]}):null,h.data?`${h.data.totalSelected} of ${h.data.totalDiscovered} locations tracked`:"Loading locations…"]}),G.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"}),G.map(X=>e.jsx("option",{value:X.locationName,children:X.displayName},X.id))]})]}),G.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:[Ne.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Ne.map(X=>e.jsx("div",{className:["insight-card",Jx(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(Fe,{text:X.recommendation.reason})]})},X.id))]}),w&&e.jsx(tg,{performance:w.performance,freshness:w.freshness,timeseries:w.timeseries}),w?.profileCompleteness&&e.jsx(Fx,{summary:w.profileCompleteness}),Z.length>0&&e.jsx(Gx,{locations:Z,lodging:ee,places:E,placeActions:T,expandedLocation:l,onToggleExpanded:X=>{i(ue=>ue===X?null:X)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),f.data&&f.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[Ze(f.data.thresholdedPct,Qn.percent)," privacy-thresholded"]})]}),re.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No keyword impressions stored yet."}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Search term"}),ce&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:re.slice(0,25).map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:X.keyword}),ce&&e.jsx("td",{className:"text-muted",children:V.find(ue=>ue.locationName===X.locationName)?.displayName??X.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:X.valueCount!==null?X.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",X.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[X.periodStart,"–",X.periodEnd]})]},`${X.locationName}:${X.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>d(X=>!X),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",V.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:V.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!le()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:V.map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:X.displayName}),e.jsx("td",{className:"text-muted",children:X.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(je,{tone:X.selected?"positive":"neutral",children:X.selected?"Tracked":"Not tracked"})}),!le()&&e.jsx("td",{className:"text-right",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:A.isPending,onClick:()=>A.mutate({client:Y,path:{name:t,locationName:X.locationName},body:{selected:!X.selected}}),children:X.selected?"Untrack":"Track"})})]},X.id))})]})})]})]})})}function Fx({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:ia(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:ia(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:ia(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:ia(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:ia(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-default py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(Fe,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${Yx(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Gx({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:l}){const i=new Map(s.map(m=>[m.locationName,m])),c=new Map(n.map(m=>[m.locationName,m])),d=new Map;for(const m of a){const u=d.get(m.locationName)??[];u.push(m),d.set(m.locationName,u)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Fe,{text:le()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(m=>{const u=i.get(m.locationName)??null,p=c.get(m.locationName)??null,x=d.get(m.locationName)??[],h=r===m.locationName;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:m.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:m.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(je,{tone:m.selected?"positive":"neutral",children:m.selected?"Tracked":"Not tracked"}),m.openStatus&&m.openStatus!=="OPEN"&&e.jsx(je,{tone:m.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Ic(m.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(_x,{location:m})}),e.jsx("td",{children:e.jsx(Ux,{lodging:u})}),e.jsx("td",{children:e.jsx(Vx,{place:p,mapsUri:m.mapsUri})}),e.jsx("td",{children:e.jsx(Qx,{actions:x})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>l(m.locationName),children:h?"Hide":"Details"})})]}),h&&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(Wx,{location:m,lodging:u,place:p,placeActions:x})})})]},m.id)})})]})})]})}function Kx(t){return[{label:"Description",tone:fn(t.description)?"positive":"neutral",value:fn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:fn(t.primaryPhone)?"positive":"neutral",value:fn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:fn(t.websiteUri)?"positive":"neutral",value:fn(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function _x({location:t}){const s=Kx(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(je,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Ux({lodging:t}){return e.jsx($i,{...Bx(t)})}function Bx(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 Vx({place:t,mapsUri:s}){return e.jsx($i,{...zx(t,s)})}function zx(t,s){if(!t)return{tone:"neutral",label:"Public listing not checked",detail:s?"Maps link available.":"No Places snapshot."};const n=t.amenities.length;return{tone:n>0?"positive":"neutral",label:n>0?`${n} signal${n===1?"":"s"} detected`:"0 supported signals detected",detail:`Places tier: ${t.tier}`}}function Qx({actions:t}){return e.jsx($i,{...Hx(t)})}function Hx(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 $i({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(je,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Wx({location:t,lodging:s,place:n,placeActions:a}){const r=s?Zx(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(qr,{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:fn(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:Ic(t.openStatus)}),e.jsx(zt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(qr,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(zt,{label:"Last checked",value:Ko(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(qr,{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:Ko(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:[mr(l.placeActionType),l.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[mr(l.providerType),l.uri?` · ${Xx(l.uri)}`:""]})]},l.placeActionLinkName))})})]})]})}function qr({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 ia(t,s,n){return t===s?"positive":t===0?n:"caution"}function Yx(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Jx(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function fn(t){return typeof t=="string"&&t.trim().length>0}function Ic(t){return t?mr(t):"Not returned"}function mr(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Xx(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Ko(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Zx(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&eg(n)).map(([s])=>mr(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function eg(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function tg({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Zd.filter(y=>(a[y]??0)>0),l=eu.filter(y=>(a[y]??0)>0),i=Object.keys(a).filter(y=>(a[y]??0)>0&&tu(y)==="other").sort((y,f)=>(a[f]??0)-(a[y]??0)),c=Object.keys(a).filter(y=>(a[y]??0)===0).sort(),d=n.map(y=>{const f={date:y.date};for(const[b,N]of Object.entries(y.metrics))f[b]=N;return f}),m=n.find(y=>y.pending)?.date,u=n.length>0?n[n.length-1].date:void 0,p=d.length>0,x=s.dataThroughDate?`Data through ${Tt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,h=[...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"}),x&&e.jsx("span",{className:"text-[11px] text-muted",children:x})]}),!p||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(_o,{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:h.map(y=>e.jsxs("span",{className:"text-sm text-secondary",children:[lr(y)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[y]??0).toLocaleString()})]},y))})]})]}),p&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(_o,{data:d,metrics:l,kind:"area",firstPending:m,lastDate:u})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(y=>lr(y)).join(", ")]})]})}function _o({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ja,{stroke:ba,vertical:!1}),e.jsx(sn,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:ds},tickFormatter:Nn,minTickGap:24}),e.jsx(nn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...ts,labelFormatter:Tt,formatter:(l,i)=>[typeof l=="number"?l.toLocaleString():String(l??0),lr(String(i??""))]}),e.jsx(dr,{wrapperStyle:{fontSize:11,color:us.text},formatter:l=>lr(l)}),a&&r&&e.jsx(ni,{x1:a,x2:r,fill:us.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:us.textDim,fontSize:10}}),s.map((l,i)=>n==="line"?e.jsx(Ds,{type:"monotone",dataKey:l,stroke:ct[i%ct.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx(Js,{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 sg(t){return Gh(Bt(String(t)))}function ng(t){return Ca(Bt(String(t)))}function Er({children:t,label:s="More info",placement:n="top",className:a}){const r=o.useId(),[l,i]=o.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":l?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:e.jsx(Yh,{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 Ua=qs;function In(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Dr(t){return t.toLocaleString()}function ag(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 rg(t){const s=t.filter(n=>n.kind===Gs["backlink-extract"]&&!Ul(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function ig(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 og({projectName:t}){const s=ms(),[n,a]=o.useState(null),[r,l]=o.useState(null),[i,c]=o.useState([]),[d,m]=o.useState(null),[u,p]=o.useState(null),[x,h]=o.useState(null),[y,f]=o.useState(Date.now()),[b,N]=o.useState(0),[k,$]=o.useState(!0),[S,g]=o.useState(!1),[v,C]=o.useState(null),I=o.useCallback(async()=>{$(!0),C(null);try{const[_,Z,L,ee,T]=await Promise.all([su().catch(()=>null),nu(t,{excludeCrawlers:!0}).catch(()=>null),au(t,{limit:Ua,offset:b,excludeCrawlers:!0}).catch(te=>{if(te instanceof _n&&te.code==="NOT_FOUND")return null;throw te}),ru(t).catch(()=>[]),iu(t).catch(()=>[])]);m(_),a(Z),l(L),c(ee);const E=rg(T);p(E)}catch(_){C(_ instanceof Error?_.message:"Failed to load backlinks")}finally{$(!1)}},[t,b]);o.useEffect(()=>{I()},[I]),o.useEffect(()=>{if(!u)return;const _=u.id;let Z=!1;const L=async()=>{try{const T=await ti(_);if(Z)return;Ul(T.status)?(p(null),h(T),await I()):p(E=>E?.id===T.id?{...E,...T}:E)}catch{}},ee=window.setInterval(()=>{L()},3e3);return()=>{Z=!0,window.clearInterval(ee)}},[u,I]),o.useEffect(()=>{if(!u)return;const _=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(_)},[u]),o.useEffect(()=>{if(!x||x.status==="failed")return;const _=window.setTimeout(()=>h(null),1e4);return()=>window.clearTimeout(_)},[x]);async function A(){g(!0),C(null);try{const _=await lu(t);p(_)}catch(_){_ instanceof _n&&_.code==="MISSING_DEPENDENCY"?C("DuckDB is not installed. Visit the Backlinks admin page to install it."):C(_ instanceof Error?_.message:"Failed to trigger extract")}finally{g(!1)}}const w=o.useMemo(()=>i.slice().sort((_,Z)=>_.queriedAt.localeCompare(Z.queriedAt)).map(_=>({date:_.queriedAt,linkingDomains:_.totalLinkingDomains})),[i]),V=r?.rows??[],G=r?.total??0,Q=n?.excludedLinkingDomains??0,B=Math.floor(b/Ua)+1;return o.useEffect(()=>{b>0&&b>=G&&N(0)},[b,G]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),v&&e.jsx(ve,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:v})}),u&&e.jsx(ve,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(zh,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(je,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[ig(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."})]})]})}),x&&!u&&e.jsx(ve,{className:`surface-card p-4 mb-4 ${x.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(Qh,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${x.status==="failed"?"text-negative":"text-positive"}`,children:x.status==="failed"?"Extract failed":"Extract complete"}),x.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:ou(x.error)}):x.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),z()]});function z(){return k?e.jsx(ve,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):ne()}function ne(){const _=n!==null&&n.totalLinkingDomains>0,Z=x?.status==="failed",L=n!==null&&n.totalLinkingDomains===0&&!Z,ee=d?.status==="ready",T=d?.status==="failed",E=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return _?F(e.jsxs(e.Fragment,{children:[!le()&&!s&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:S||u!==null,onClick:Xe(A),children:[e.jsx(Wh,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":S?"Queuing…":"Re-run extract"]}),e.jsx(Er,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!le()&&!s&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"Open admin"})})]})):e.jsx(ve,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Hh,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!d&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!le()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"Set up backlinks"})})})]}),E&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",d.status,d.phaseDetail?` — ${d.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!le()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"View sync status"})})})]}),T&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:d.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!le()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"Go to Backlinks admin"})})})]}),ee&&!E&&!L&&!Z&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:d.release})," is ready. Run an extract for this project."]}),!le()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(P,{type:"button",size:"sm",disabled:S||u!==null,onClick:Xe(A),children:[e.jsx(cr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":S?"Queuing…":"Run extract"]}),e.jsx(Er,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),Z&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!le()&&!s&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"Go to Backlinks admin"})})})]}),L&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",n.targetDomain,". Try a newer release or re-run this extract."]}),!le()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:In("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:S||u!==null,onClick:Xe(A),children:[e.jsx(cr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":S?"Queuing…":"Re-run extract"]}),e.jsxs(Er,{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 F(_){if(!n)return null;const Z="Linking hosts",L="linking hosts",ee="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:Dr(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 ",L]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Dr(n.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",L," 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:Ze(Number(n.top10HostsShare))})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",L," 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"})," · ",ee," ",e.jsx("code",{className:"text-secondary",children:n.release})," · queried ",ag(n.queriedAt),Q>0&&e.jsxs(e.Fragment,{children:[" · ",Q," excluded domain",Q===1?"":"s"]})]}),w.length>=2&&e.jsxs(ve,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:w,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:ct[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:ct[0],stopOpacity:0})]})}),e.jsx(sn,{dataKey:"date",tick:Ut,stroke:ds,tickFormatter:sg}),e.jsx(nn,{tick:Ut,stroke:ds,allowDecimals:!1}),e.jsx(an,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:ng}),e.jsx(Js,{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:Z})]})}),e.jsxs("tbody",{children:[V.map(T=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:T.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Dr(T.numHosts)})]},T.linkingDomain)),V.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:Q>0&&G===0?`Every referring domain in this ${ee} was a crawler/proxy host (${Q} hidden).`:`No referring domains in this ${ee}.`})})]})]})}),e.jsx(Os,{page:B,pageSize:Ua,visibleRows:V.length,totalRows:G,onPageChange:T=>N((T-1)*Ua)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:_})]})}}const lg=["non-brand","branded","unclassified"],Uo={"non-brand":"Non-brand",branded:"Branded",unclassified:"Unclassified"};function cg(t,s){return s<=0?"neutral":t/s*100>=70?"positive":"caution"}function dg(t,s){const n=[...new Set(t.byQuery.flatMap(i=>i.providers.map(c=>c.provider)))].sort(),a=new Map,r=i=>{const c=s(i)??"unclassified";let d=a.get(c);return d||(d={key:c,queries:0,unanswered:0,engines:n.map(m=>({provider:m,answered:0,mentioned:0,cited:0})),answers:0,competitorCited:0,competitorGaps:[],citedAndNamed:0,citedNotNamed:0,namedNotCited:0,neither:0},a.set(c,d)),d},l=new Map;for(const i of t.byQuery){const c=r(i.query);if(i.providers.length===0){c.unanswered++;continue}c.queries++;for(const u of i.providers){l.set(`${i.queryId}::${u.provider}`,i.query);const p=c.engines.find(x=>x.provider===u.provider);p.answered++,u.mentioned&&p.mentioned++,u.cited&&p.cited++,c.answers++}const d=i.providers.some(u=>u.cited),m=i.providers.some(u=>u.mentioned);d&&m?c.citedAndNamed++:d?c.citedNotNamed++:m?c.namedNotCited++:c.neither++}for(const i of t.competitorGaps){const c=l.get(`${i.queryId}::${i.provider}`);if(c===void 0)continue;const d=r(c);d.competitorCited++,d.competitorGaps.push({query:c,provider:i.provider,competitors:i.citingCompetitors})}return lg.map(i=>a.get(i)).filter(i=>i!==void 0&&i.queries>0)}function ug(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 mg={engine:"engine no longer configured",query:"query no longer tracked"},Bo={"non-brand":"non-brand queries",branded:"branded queries",unclassified:"unclassified queries"},hg="Each engine's latest answer to each query, spot checks left out. Mentioned: the answer names you. Cited: its sources link to your site. Competitor cited instead of you: answers that cite a tracked competitor's site and not yours.";function Tn(t,s,n){return t===1?s:n}function pg({projectName:t,classify:s,hasCompetitors:n,providerScores:a=[]}){const r=o.useId(),[l,i]=o.useState("non-brand"),c=Le({...cu({client:Y,path:{name:t}}),staleTime:Ri}),d=c.data??null,m=d?.status==="ready"?dg(d,s):[],u=m.find(f=>f.key===l)??m.at(0);let p;c.isError?p=e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Could not load engine results: ",Ct(c.error)]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{c.refetch()},children:"Retry"})]}):d?d.status==="no-data"?p=e.jsx("p",{className:"text-sm text-secondary",children:d.reason==="no-queries"?"Add queries to start tracking AI citations.":cs()?Un:"Engine results appear after the first AI Visibility sweep."}):u||(p=e.jsx("p",{className:"text-sm text-secondary",children:"No engine answers yet."})):p=e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine results…"});const x=[];if(u&&d?.status==="ready"){const f=Tn(u.queries,"query","queries");x.push(e.jsxs(e.Fragment,{children:["Cited and named: ",e.jsxs("strong",{children:[u.citedAndNamed," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Cited but not named: ",e.jsxs("strong",{children:[u.citedNotNamed," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Named but not cited: ",e.jsxs("strong",{children:[u.namedNotCited," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Not cited or named: ",e.jsxs("strong",{children:[u.neither," of ",u.queries]})," ",f]}));for(const $ of u.engines)$.answered<u.queries&&x.push(e.jsxs(e.Fragment,{children:[lt($.provider),": answered ",e.jsxs("strong",{children:[$.answered," of ",u.queries]})," ",f]}));u.unanswered>0&&x.push(e.jsxs(e.Fragment,{children:["No answers yet: ",e.jsx("strong",{children:u.unanswered})," ",Tn(u.unanswered,"query","queries")]}));const{providersCiting:b,providersMentioning:N,providersConfigured:k}=d.summary;x.push(e.jsxs(e.Fragment,{children:["All queries: cited by ",e.jsxs("strong",{children:[b," of ",k]})," ",Tn(k,"engine","engines"),", named by ",e.jsxs("strong",{children:[N," of ",k]})]}));for(const $ of a)x.push(e.jsxs(e.Fragment,{children:[lt($.provider),$.model?` (${$.model})`:""," citation rate:"," ",e.jsx("strong",{children:Ze($.score,Qn.percent)}),", ",e.jsxs("strong",{children:[$.cited," of ",$.total]})," ",Tn($.total,"answer","answers"),", all queries"]}));for(const $ of u.competitorGaps)x.push(`"${$.query}" (${lt($.provider)}): ${$.competitors.join(", ")} cited instead of you`);for(const $ of ug(d))x.push(`"${$.query}" (${lt($.provider)}): ${$.competitors.join(", ")} cited instead of you, not counted (${mg[$.reason]})`)}const h=d?.status==="ready"?d.summary.latestRunAt:null,y=(f,b)=>u?.key==="non-brand"?fa[cg(f,b)]:"text-primary";return e.jsxs("section",{className:"overview-brief","aria-labelledby":r,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:r,className:"av-card-title",children:"By engine"}),u&&e.jsx(Fe,{text:hg})]}),h||u?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[h?e.jsxs("p",{className:"av-card-meta",children:["Latest run ",gr(h)]}):null,m.length>1?e.jsx(xa,{label:"Query type",className:"flex-wrap",options:m.map(f=>({value:f.key,label:Uo[f.key]})),value:u.key,onChange:i}):u?e.jsx("span",{className:"mention-share-class",children:Uo[u.key]}):null]}):null]}),e.jsx("div",{className:"av-card-body",children:p??(u&&e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":`By engine, ${Bo[u.key]}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsxs("th",{scope:"col",children:["Of ",u.queries," ",Tn(u.queries,"query","queries")]}),u.engines.map(f=>e.jsx("th",{scope:"col",children:lt(f.provider)},f.provider))]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Mentioned"}),u.engines.map(f=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(f.mentioned,f.answered)}`,children:f.mentioned})},f.provider))]}),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Cited"}),u.engines.map(f=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(f.cited,f.answered)}`,children:f.cited})},f.provider))]})]})]}),e.jsxs("p",{className:"av-card-line",children:[e.jsx("span",{className:"av-card-line-label",children:"Competitor cited instead of you"}),n?e.jsxs("span",{children:[e.jsx("span",{className:"av-n-sm text-primary",children:u.competitorCited})," ",e.jsxs("span",{className:"av-of",children:["of ",u.answers," ",Tn(u.answers,"answer","answers")]}),e.jsxs("span",{className:"sr-only",children:[" · ",Bo[u.key]]})]}):e.jsx("span",{className:"text-[13px] text-secondary",children:"No competitors tracked"})]})]}))}),e.jsx(ka,{items:x})]})}const xg={[Is.queued]:{word:"queued",tone:"text-secondary"},[Is.running]:{word:"running",tone:"text-info-300"},[Is.completed]:{word:"completed",tone:"text-secondary"},[Is.partial]:{word:"partial",tone:"text-caution-400"},[Is.failed]:{word:"failed",tone:"text-negative-400"},[Is.cancelled]:{word:"cancelled",tone:"text-secondary"}};function gg({runs:t,collapsed:s=!1}){const n=o.useId(),{openRun:a}=Ci(),r=new Set(t.map(c=>c.location??"")).size>1,l=t.some(c=>c.kind!==Gs["answer-visibility"]),i=t.map(c=>`${c.startedAt}: ${c.summary}.${c.statusDetail?` ${c.statusDetail}`:""}`);return e.jsx("section",{className:"overview-brief","aria-labelledby":n,children:e.jsxs("details",{className:"av-history",open:!s||void 0,children:[e.jsxs("summary",{className:"av-card-head",children:[e.jsx("h2",{id:n,className:"av-card-title",children:"Past sweeps"}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t.length>0?e.jsxs("span",{className:"av-card-meta",children:[t.length," recent"]}):null,e.jsx(Bn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"av-card-body",children:t.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No sweeps yet."}):e.jsxs("table",{className:"av-grid av-grid-dense av-grid-sweeps","aria-labelledby":n,children:[e.jsx("thead",{className:"sr-only",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Started"}),l?e.jsx("th",{scope:"col",children:"Type"}):null,e.jsx("th",{scope:"col",children:"Trigger"}),r?e.jsx("th",{scope:"col",children:"Location"}):null,e.jsx("th",{scope:"col",children:"Duration"}),e.jsx("th",{scope:"col",children:"Status"})]})}),e.jsx("tbody",{children:t.map(c=>{const d=xg[c.status],m=c.status===Is.partial||c.status===Is.failed;return e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label tabular-nums",children:e.jsx("button",{type:"button",className:"av-link",onClick:()=>a(c.id),"aria-label":`View the ${c.startedAt} sweep`,children:c.startedAt})}),l?e.jsx("td",{className:"text-[13px] text-secondary",children:c.kindLabel}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.triggerLabel}),r?e.jsx("td",{className:"text-[13px] text-secondary",children:c.location??"No location"}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.duration}),e.jsxs("td",{children:[e.jsx("span",{className:`av-status ${d.tone}`,children:d.word}),m&&c.statusDetail?e.jsx("span",{className:"ml-2 text-[13px] text-secondary",children:c.statusDetail}):null]})]},c.id)})})]})}),e.jsx(ka,{items:i})]})})}const fg=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],Vo="Measured answers",yg="Close answers",Rs={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},bg={"non-brand":"non-brand queries",branded:"branded queries",unknown:"unclassified queries"},ls={up:t=>`Up ${t} pts`,down:t=>`Down ${t} pts`,none:"No change",previousUnavailable:"No earlier value",comparedWith:t=>`vs ${t} sweep`,noPreviousRun:"No earlier sweep to compare",definitionChanged:t=>t===null?"Not compared: setup changed":`Not compared: setup changed since ${t}`,modelChanged:t=>t===null?"Not compared: engines or models changed":`Not compared: engines or models changed since ${t}`,legacyUnknown:"Not compared: older sweep lacks comparison details",partialRun:"Not compared: a sweep was incomplete",scopedRun:"Not compared: this sweep covered part of the project",explanation:"Change compares this sweep with the sweep before it when both completed and used the same setup, engines and models."},oa={simpleMention:"Mentioned counts answers naming your brand in the answer text, not in the source links.",simpleCitation:"Cited counts answers linking to your site in the sources behind the answer, not in the answer text.",advancedMention:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned. An answer that could not be tied to one property is left out of the rate, never counted as not mentioned.",advancedCitation:"An answer counts when it cites a matching URL for any assigned property. This does not mean every property was cited. An answer whose sources could not be checked is left out of the rate, as neither cited nor not cited, and counted on its own line.",propertyReach:"Selected properties named in at least one measured answer, out of the selected properties that have a name to match on. It counts properties, not answers, and shows no rate while any of those properties is unmeasured."},vg="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.",hr="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 jg(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function Tc(t){return t.reason==="identity-ambiguous"?Hl.ambiguous:t.reason==="not-applicable"?"Not applicable":"Not measured"}function wn({value:t,signal:s}){if(t.rate===null)return e.jsx("span",{className:"text-sm text-secondary",children:Tc(t)});const n=Pi(t,s);return e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:Ze(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator]}),n?e.jsx("span",{className:"text-sm tabular-nums text-secondary",children:n}):null]})}function zo({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 Or(t,s){if(!t||t.state==="unavailable")return null;const n=t[s];if(n.state==="unavailable")switch(n.reason){case wr["previous-unavailable"]:return{text:ls.previousUnavailable,tone:"text-secondary"};case wr["current-unavailable"]:case wr["not-applicable"]:return null}const{direction:a,magnitude:r}=Vl(n.delta);switch(a){case"up":return{text:ls.up(r),tone:"text-positive"};case"down":return{text:ls.down(r),tone:"text-negative"};case"none":return{text:ls.none,tone:"text-secondary"}}}function Qo(t,s){const n=Bt(t);return s!==null&&po(n)===po(Bt(s))?Uh(n):Ca(n)}function Ng(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 wg(t,s){if(!t)return null;if(t.state==="unavailable"){const n=t.previousRun?Qo(t.previousRun.createdAt,s):null;switch(t.reason){case un["no-selected-run"]:return null;case un["no-previous-run"]:return ls.noPreviousRun;case un["definition-changed"]:return ls.definitionChanged(n);case un["model-changed"]:return ls.modelChanged(n);case un["legacy-unknown"]:return ls.legacyUnknown;case un["partial-run"]:return ls.partialRun;case un["scoped-run"]:return ls.scopedRun}}return ls.comparedWith(Qo(t.previousRun.createdAt,s))}function Sg(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 Fr({label:t,help:s,value:n,signal:a,unit:r,classNoun:l,change:i}){const c=e.jsx("span",{className:"sr-only",children:` · ${l}`}),d=Pi(n,a);return e.jsxs("div",{className:"report-headline-tile",children:[e.jsxs("dt",{className:"flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:t}),e.jsx(Fe,{text:s})]}),n.rate===null?e.jsxs("dd",{className:"text-lg text-secondary",children:[Tc(n),c]}):e.jsxs(e.Fragment,{children:[e.jsxs("dd",{className:"report-headline-value",children:[e.jsx("span",{className:"text-3xl font-semibold tabular-nums text-heading",children:Ze(n.rate)}),c,i?e.jsx("span",{className:`text-sm ${i.tone}`,children:i.text}):null]}),e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:`${n.numerator} of ${n.denominator} ${r}`}),d?e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:d}):null]})]})}const Cg={otherQueries:"Other queries"},Ba={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 kg(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(" · ")||Cg.otherQueries}return a.sort((r,l)=>r.marketLabel.localeCompare(l.marketLabel)||r.query.localeCompare(l.query))}function Ho({value:t,signal:s,singleAnswer:n}){if(n&&t.denominator===1&&t.unattributed===void 0&&t.unchecked===void 0&&(t.rate===0||t.rate===1)){const a=t.rate===1;return e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm ${a?"text-positive":"text-secondary"}`,children:[a?e.jsx(Xh,{size:16,"aria-hidden":"true"}):e.jsx(Zh,{size:16,"aria-hidden":"true"}),a?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(wn,{value:t,signal:s}),t.reason==="evidence-incomplete"?e.jsx(Fe,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function Wo({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 Ag({group:t,queryClass:s,advanced:n,targetLabels:a,marketHeading:r,onViewAnswers:l}){const i=t.rows[0],c=p=>JSON.stringify([...p.targetKeys].sort()),d=t.rows.every(p=>c(p)===c(i)),m=t.rows.every(p=>p.location===i.location),u=p=>p===null?"No location requested":`Requested search location: ${p}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[r?e.jsx("tr",{children:e.jsx("th",{colSpan:4,className:"border-t border-default py-4 text-left",children:e.jsx("h3",{className:"text-base font-semibold text-heading",children:r})})}):null,e.jsx("tr",{className:"measurement-result-heading",children:e.jsxs("th",{scope:"rowgroup",colSpan:4,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"break-words text-base font-medium text-heading",children:t.query}),e.jsx("div",{className:"text-sm font-normal",children:e.jsx(ql,{showLabel:!0,queryId:i.queryId,sourceSnapshotIds:t.rows.flatMap(p=>p.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(Wo,{targetKeys:i.targetKeys,labels:a}):null,m?e.jsx("span",{children:u(i.location)}):null]})]})}),t.rows.map(p=>e.jsxs("tr",{className:"measurement-engine-result",children:[e.jsxs("td",{className:"measurement-result-engine",children:[e.jsx("span",{className:"font-medium text-heading",children:lt(p.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:p.model??"Model not recorded"}),n&&!d?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(Wo,{targetKeys:p.targetKeys,labels:a})}):null,m?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:u(p.location)}),e.jsx(El,{showLabel:!0,showSubjects:n,queryId:p.queryId,sourceSnapshotIds:p.sourceSnapshotIds??[],queryClass:s==="unknown"?null:s,provider:p.provider,model:p.model,location:p.location})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(Ho,{value:p.mentionCoverage,signal:"mentioned",singleAnswer:p.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(Ho,{value:p.citationCoverage,signal:"cited",singleAnswer:p.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(P,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${p.query} · ${p.provider}`,onClick:x=>l(p,x.currentTarget),children:[p.answerCount===1?"View answer":"View answers",e.jsx(lc,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([p.provider,p.model,p.location])))]})}const Rg="Cited counts only answers whose sources could be checked.",Yo=[{key:"mentioned",label:"Mentioned",color:ct[1],dashed:!1},{key:"cited",label:"Cited",color:Hn.positive,dashed:!0}],Jo="var(--chart-tooltip-bg)";function Pg({population:t}){const s=o.useId(),[n,a]=o.useState({mentioned:!0,cited:!0}),r=Yo.filter(x=>n[x.key]).map(x=>x.key),l=x=>a(h=>{const y={...h,[x]:!h[x]};return y.mentioned||y.cited?y:h});let i=0;const c=t.trend.map((x,h)=>(h>0&&x.continuity.state!=="comparable"&&(i+=1),{createdAt:Date.parse(x.createdAt),[`mentioned-${i}`]:x.mentionCoverage.rate,[`cited-${i}`]:x.citationCoverage.rate})),d=Array.from({length:i+1},(x,h)=>h),m=new Set(t.trend.slice(1).map(x=>x.continuity.state)),u=[...c.length===1?["First measurement. A trend appears after another comparable run."]:[],...m.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...m.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...m.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(x=>x.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[],...t.trend.some(x=>x.citationCoverage.unchecked!==void 0)?[Rg]:[]];if(c.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const p=t.trend.some(x=>x.mentionCoverage.rate!==null||x.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[p?e.jsxs(e.Fragment,{children:[e.jsxs("fieldset",{className:"flex flex-wrap gap-x-5 py-1 text-sm text-secondary",children:[e.jsx("legend",{className:"sr-only",children:"Trend legend"}),Yo.map(x=>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[x.key],disabled:n[x.key]&&r.length===1,onChange:()=>l(x.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:x.color,strokeWidth:"2",strokeDasharray:x.dashed?"6 4":void 0}),e.jsx("circle",{cx:"12",cy:"5",r:"3",fill:x.dashed?Jo:x.color,stroke:x.color,strokeWidth:"2"})]}),x.label]},x.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":`${Rs[t.queryClass]} mention and citation trend`,children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:c,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ja,{stroke:ba,vertical:!1}),e.jsx(sn,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Ut,tickLine:!1,axisLine:{stroke:ds},tickFormatter:x=>new Date(Number(x)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(nn,{domain:[0,1],tick:Ut,tickLine:!1,axisLine:!1,width:48,tickFormatter:x=>Ze(Number(x))}),e.jsx(an,{...ts,formatter:x=>typeof x=="number"?Ze(x):"Not measured",labelFormatter:x=>new Date(Number(x)).toLocaleDateString()}),d.map(x=>e.jsxs(o.Fragment,{children:[n.mentioned?e.jsx(Ds,{type:"linear",dataKey:`mentioned-${x}`,name:"Mentioned",stroke:ct[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:ct[1]}}):null,n.cited?e.jsx(Ds,{type:"linear",dataKey:`cited-${x}`,name:"Cited",stroke:Hn.positive,strokeWidth:2,strokeDasharray:"6 4",connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:Jo,strokeDasharray:"none"}}):null]},x))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:p?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${Rs[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(x=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(x.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(wn,{value:x.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(wn,{value:x.citationCoverage,signal:"cited"})}),e.jsx("td",{children:x.continuity.state.replaceAll("-"," ")})]},x.runId))})]})})]})}function xi(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function Li(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=xi(a,s)??xi(t,s),c=t.populations.find(m=>m.queryClass===i?.queryClass);if(c)return c;const d=["non-brand","branded","unknown"].map(m=>t.populations.find(u=>u.queryClass===m));return d.find(m=>m&&(m.summary.queryCount>0||m.trend.some(u=>u.queryCount>0)))??d.find(m=>m!==void 0)??t.populations[0]}const At={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"},Ig={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},Tg="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 Mg(t,s){return t&&s?At.dateRange(t.slice(0,4)===s.slice(0,4)?_h(t):Tt(t),Tt(s)):t?At.dateFrom(Tt(t)):s?At.dateThrough(Tt(s)):null}function $g(t,s){const n=[];t.provider&&n.push({key:"engine",label:At.engine(t.provider),patch:{measurementProvider:void 0}}),t.model&&n.push({key:"model",label:At.model(t.model),patch:{measurementModel:void 0}}),t.location&&n.push({key:"location",label:t.location==="none"?At.noLocation:At.location(t.location),patch:{measurementLocation:void 0}});const a=Mg(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?At.resultsFrom(Ca(Bt(r.createdAt))):At.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function Va(t,s,n){return s===""||t.some(a=>a.value===s)?t:[...t,{value:s,label:n}]}function Lg({report:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}){const[l,i]=o.useState(!1),c=o.useRef(null),d=o.useId(),m=`${d}-filters`,{filterOptions:u,selection:p}=t,x=p.measurement,h=Li(t,s.queryKey,s.answer),y=s.queryClass==="all"?h.queryClass:s.queryClass,f=$g(s,t),b=s.measurementScope==="property"?s.measurementScopeKey:void 0,N=b?r?.({id:b,label:ai(t.scopeOptions,s)?.label??b}):null,k=s.provider??"",$=s.model??"",S=s.location??"",g=s.measurementRunId??"",v=()=>c.current?.focus(),C=(A,w,V,G,Q)=>e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1",children:[e.jsx("label",{htmlFor:`${d}-${w}`,className:"text-sm font-medium text-heading",children:A}),Q?e.jsx(Fe,{text:Q}):null]}),e.jsx("select",{id:`${d}-${w}`,className:hr,value:V,onChange:B=>n({[w]:B.target.value||void 0,measurementQueryKey:void 0}),children:G.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]}),I=(A,w,V,G)=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("label",{htmlFor:`${d}-${w}`,className:"mb-1 block text-sm font-medium text-heading",children:A}),e.jsx("input",{id:`${d}-${w}`,type:"date",className:hr,value:V?.slice(0,10)??"",onChange:Q=>n({[w]:Q.target.value?`${Q.target.value}${G}`: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:At.queryType}),e.jsxs("select",{"aria-label":At.queryType,className:Tg,value:y,onChange:A=>n({queryClass:A.target.value,measurementQueryKey:void 0}),children:[e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"unknown",children:"Unclassified"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{tone:x.state==="measured"?"positive":"neutral",children:x.state==="measured"?"Complete":x.state==="partial"?"Partial":"Not measured"}),x.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:Ca(Bt(x.completedAt))}):null]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[e.jsx(P,{ref:c,type:"button",variant:"outline",className:"min-h-11","aria-expanded":l,"aria-controls":m,onClick:()=>i(A=>!A),children:At.filters(f.length)}),f.map(A=>e.jsxs(P,{type:"button",variant:"outline",className:"visibility-filter-token min-h-11 rounded-md text-sm","aria-label":At.removeFilter(A.label),onClick:()=>{n(A.patch),v()},children:[e.jsx("span",{className:"min-w-0 truncate",children:A.label}),e.jsx(Jh,{size:16,className:"shrink-0","aria-hidden":"true"})]},A.key)),N,a?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:a,children:At.manageQueries}):null]})]}),e.jsxs("div",{id:m,role:"group","aria-label":At.panel,hidden:!l,className:"border-b border-default",onKeyDown:A=>{A.key==="Escape"&&(A.target instanceof HTMLElement&&A.target.getAttribute("aria-expanded")==="true"||(i(!1),v()))},children:[e.jsxs("div",{className:"visibility-report-filters",children:[C("Answer engine","measurementProvider",k,Va([{value:"",label:"All engines"},...u.providers.map(A=>({value:A,label:A}))],k,k)),C("Requested search location","measurementLocation",S,Va([{value:"",label:"All requested locations"},...u.locations.flatMap(A=>A.kind==="exact"?[{value:A.value,label:A.value}]:A.kind==="none"?[{value:"none",label:At.noLocation}]:[])],S,S==="none"?At.noLocation:S)),C("AI model","measurementModel",$,Va([{value:"",label:"All models"},...Array.from(new Set(u.models.filter(A=>!s.provider||A.provider===s.provider).map(A=>A.model))).map(A=>({value:A,label:A}))],$,$),"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),I("Start date (UTC)","measurementFrom",s.from,"T00:00:00.000Z"),I("End date (UTC)","measurementTo",s.to,"T23:59:59.999Z"),C("Results from","measurementRunId",g,Va([{value:"",label:"Latest saved sweep"},...[...h.trend].reverse().map(A=>({value:A.runId,label:new Date(A.createdAt).toLocaleString()}))],g,"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(P,{type:"button",variant:"ghost",className:"min-h-11",disabled:f.length===0,onClick:()=>{n({...Ig}),v()},children:At.clearFilters})})]})]})}function qg({report:t,isRefreshing:s=!1,onSelectionChange:n,onPage:a,onSearch:r,search:l="",queryKey:i,answerSelection:c,evidenceReport:d,isEvidenceLoading:m=!1,evidenceError:u,onRetryEvidence:p,onEvidencePage:x}){const h=o.useRef(null),y=o.useRef(void 0),f=o.useRef(null),b=Li(t,i,c,d),N=d??t,k=N.populations.filter(w=>[...w.queries.items,...w.evidence.items].some(V=>V.queryKey===i)),$=c?[c.queryClass]:(k.length?k:m?[]:[b]).map(w=>w.queryClass),S=i?JSON.stringify([c??i,$]):void 0;o.useEffect(()=>{if(!S){s||(y.current=void 0);return}if(y.current===S)return;const w=h.current?.querySelectorAll(`[aria-label="${Vo}"]`);if(w?.length){for(const V of w){const G=V.closest("details[data-query-results]");G&&(G.open=!0)}w[0].focus({preventScroll:!0}),w[0].scrollIntoView?.({block:"start"}),y.current=S}},[S,s]);const{selection:g}=t,v=jg(g.scope),C=new Map(t.scopeOptions.filter(w=>w.kind==="property").map(w=>[w.id,w.label])),I=w=>{const V=N.populations.find(G=>G.queryClass===w.queryClass)?.evidence;return{items:V?.items.filter(G=>G.queryKey===i&&(!c||G.provider===c.provider&&G.model===c.model&&G.location===c.location&&(c.runId===null||G.runId===c.runId)))??[],nextCursor:V?.nextCursor}},A=()=>{y.current=void 0;const w=f.current;w!==null&&w.row.queryKey===i&&(!c||w.row.provider===c.provider&&w.row.model===c.model&&w.row.location===c.location)&&w?.element.isConnected?w.element.focus():h.current?.querySelector(`details[data-query-results="${b.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})};return e.jsxs("section",{ref:h,className:"visibility-report","aria-label":"AI visibility results",children:[g.provenance.kind==="legacy-simple"&&g.queryClass!=="unknown"&&g.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(P,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,[b].map(w=>{const V=kg(w.queries.items,g.scope.kind==="property"&&!g.market&&w.queryClass==="non-brand"?new Map(t.scopeOptions.filter(F=>F.kind==="market").map(F=>[F.id,F.label])):void 0),G=I(w),Q=G.items[0]?.query??w.queries.items.find(F=>F.queryKey===i)?.query,B=g.mode==="advanced"&&g.scope.kind!=="property",z=bg[w.queryClass],ne=wg(w.comparison,Ng(g,w));return e.jsxs("section",{"aria-label":Rs[w.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head flex-wrap items-center",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("h2",{children:Rs[w.queryClass]}),e.jsx(Fe,{text:w.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":w.queryClass==="branded"?"Queries that name the measured identity.":"These queries were not labeled as branded or non-brand when measured. Their saved results remain available here, separate from branded and non-brand rates."})]}),e.jsxs("div",{className:"report-headline-caption",children:[e.jsx("span",{className:"tabular-nums",children:Sg(w.summary,ne)}),e.jsx(Fe,{text:ls.explanation})]})]}),e.jsxs("dl",{className:"report-headline mt-3","data-columns":B?3:2,"aria-label":`${Rs[w.queryClass]} headline results`,children:[e.jsx(Fr,{label:B?"Answers mentioning a property":"Mentioned answers",help:g.mode==="advanced"?oa.advancedMention:oa.simpleMention,value:w.summary.mentionCoverage,signal:"mentioned",unit:"answers",classNoun:z,change:Or(w.comparison,"mentionCoverage")}),e.jsx(Fr,{label:B?"Answers citing a property":"Cited answers",help:g.mode==="advanced"?oa.advancedCitation:oa.simpleCitation,value:w.summary.citationCoverage,signal:"cited",unit:"answers",classNoun:z,change:Or(w.comparison,"citationCoverage")}),B?e.jsx(Fr,{label:"Properties mentioned",help:oa.propertyReach,value:w.summary.propertyReach,signal:"mentioned",unit:"properties",classNoun:z,change:Or(w.comparison,"propertyReach")}):null]}),e.jsx(Ll,{queryClass:g.queryClass,manage:!0}),e.jsx(Pg,{population:w}),B&&(w.breakdown.groups.length>0||w.breakdown.properties.length>0)?e.jsx(Eg,{population:w,scope:g.scope,scopeOptions:t.scopeOptions,marketKey:g.market?.id,onSelectionChange:n},`${g.scope.kind}:${g.scope.id}`):null,g.mode==="advanced"?e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Rs[w.queryClass]} property outcomes`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Property outcomes"}),e.jsxs("span",{className:"visibility-disclosure-meta",children:[w.summary.outcomes.total," ",w.summary.outcomes.total===1?"property":"properties"]})]}),e.jsxs("div",{className:"visibility-disclosure-panel flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-x-8 gap-y-3",children:[["bothSignals","mentioned and cited"],["mentionedOnly","mentioned only"],["citedOnly","cited only"],["neither","neither signal"],["notMeasured","not measured"]].map(([F,_])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:w.summary.outcomes[F]}),e.jsx("span",{className:"text-sm text-secondary",children:_})]},F))}),e.jsx(Fe,{text:vg})]})]}):null,e.jsxs("details",{className:"visibility-disclosure","data-query-results":w.queryClass,"aria-label":`${Rs[w.queryClass]} query results`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Query results"}),e.jsxs("span",{className:"visibility-disclosure-meta",children:[w.queries.total," ",w.queries.total===1?"result":"results"," · ",v]})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-3",children:[r?e.jsx("input",{type:"search","aria-label":`Search ${Rs[w.queryClass]}`,placeholder:"Search queries",className:`${hr} max-w-sm`,value:l,onChange:F=>r(F.target.value)}):null,e.jsx(Fe,{text:g.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":`${Rs[w.queryClass]} engine results`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Answer engine"}),e.jsx("th",{scope:"col",children:"Mentioned"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),V.map((F,_)=>e.jsx(Ag,{group:F,queryClass:w.queryClass,marketHeading:F.marketLabel!==V[_-1]?.marketLabel?F.marketLabel:void 0,advanced:g.mode==="advanced",targetLabels:C,onViewAnswers:(Z,L)=>{f.current={row:Z,element:L},n({measurementQueryKey:Z.queryKey,measurementAnswer:JSON.stringify({queryKey:Z.queryKey,queryClass:w.queryClass,provider:Z.provider,model:Z.model,location:Z.location,runId:g.run.id,revision:g.revision})})}},F.queryKey))]})}),w.queries.items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:"No measured queries match this selection."}):e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:[V.length," ",V.length===1?"query":"queries"," · ",w.queries.items.length," ",w.queries.items.length===1?"engine result":"engine results"," shown of ",w.queries.total," results"]}),w.queries.nextCursor&&a?e.jsx(P,{variant:"outline",onClick:()=>a(w.queries.nextCursor),children:"Next queries"}):null,i&&$.includes(w.queryClass)?e.jsxs("section",{tabIndex:-1,className:"scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-label":Vo,"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:Q??"Answers"}),e.jsx(P,{variant:"ghost",className:"min-h-11",onClick:A,children:yg})]}),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]}),p?e.jsx(P,{variant:"outline",onClick:p,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[G.items.map(F=>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:F.provider}),F.model?e.jsx("span",{className:"text-[13px] text-secondary",children:F.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:F.location===null?At.noLocation:At.location(F.location)}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(F.createdAt).toLocaleDateString()}),e.jsx(je,{tone:"neutral",children:F.mentioned===null?F.mentionUnavailableReason==="identity-ambiguous"?Hl.ambiguous:"Mention not checked":F.mentioned?"Mentioned":"Not mentioned"}),e.jsx(je,{tone:"neutral",children:F.cited===null?"Citation not checked":F.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Ti,{headingLevel:4,copyable:!!F.answerText?.trim(),children:F.answerText??"Answer text unavailable."})}),F.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:[Dh," (",F.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:F.sources.map(_=>e.jsx("li",{className:"min-w-0",children:e.jsx(ki,{url:_})},_))})]}):null]},F.answerId)),I(w).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:I(w).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,I(w).nextCursor&&x?e.jsx(P,{variant:"outline",onClick:()=>x(I(w).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Rs[w.queryClass]} competitors`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Competitors"}),e.jsx("span",{className:"visibility-disclosure-meta",children:w.competitorAvailability.state==="unavailable"?"Not available":`${w.competitors.length} measured`})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[w.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):w.competitors.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No measured competitors in this selection."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Competitor"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:w.competitors.map(F=>e.jsxs("tr",{children:[e.jsx("td",{children:F.domain}),e.jsx("td",{children:e.jsx(wn,{value:F.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(wn,{value:F.citationCoverage,signal:"cited"})})]},F.domain))})]})}),w.observedCompetitors.length>0?e.jsxs("details",{className:"mt-4 text-sm",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-heading",children:"Other names in answers"}),e.jsx("ul",{className:"divide-y divide-default",children:w.observedCompetitors.map(F=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:F.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[F.answerCount," ",F.answerCount===1?"answer":"answers"]})]},F.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},w.queryClass)})]})}function Eg({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const l=new Map(n.filter(p=>p.kind==="group").map(p=>[p.id,p])),i=[...l.values()].some(p=>p.parentGroupIds?.length),c=t.breakdown.groups.filter(p=>{const x=l.get(p.id)?.parentGroupIds??[];return s.kind==="project"?x.length===0:s.kind==="group"&&i?x.includes(s.id):!0}),[d,m]=o.useState(()=>s.kind==="project"&&c.length>0?"groups":"properties"),u=jn({rows:d==="groups"?c:t.breakdown.properties,getSearchText:p=>p.label});return e.jsxs("section",{className:"border-t border-default py-5","aria-label":"Scope breakdown",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsx("div",{className:"flex gap-2",children:["groups","properties"].map(p=>e.jsx(P,{variant:d===p?"secondary":"ghost",onClick:()=>{m(p),u.setPage(1)},children:p==="groups"?"Groups":"Properties"},p))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:u.query,onChange:p=>u.setQuery(p.target.value),className:`${hr} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:d==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:u.rows.map(p=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("button",{className:"min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>r({measurementScope:d==="groups"?"group":"property",measurementScopeKey:p.id,measurementMarketKey:a}),children:p.label})}),e.jsx("td",{children:p.queryCount}),e.jsxs("td",{children:[e.jsx(wn,{value:p.mentionCoverage,signal:"mentioned"}),e.jsx(zo,{value:p.mentionCoverage})]}),e.jsxs("td",{children:[e.jsx(wn,{value:p.citationCoverage,signal:"cited"}),e.jsx(zo,{value:p.citationCoverage})]})]},p.id))})]})}),u.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",d," match this search."]}):null,e.jsx(Os,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:d,onPageChange:u.setPage})]})}function Mc(t,s,{enabled:n}){return Le({...ar({client:Y,path:{name:t},query:si(s)}),enabled:n,staleTime:Bl,retry:!1,placeholderData:wi})}function $c(t,s){return s&&t.selection.mode==="simple"&&t.selection.measurement.state==="not-measured"}function Dg({projectName:t,selection:s,onSelectionChange:n,fallback:a,showUnmeasuredFallback:r=!1}){const[l,i]=o.useState(),[c,d]=o.useState(""),[m,u]=o.useState(),p=hs(),x=o.useMemo(()=>({scope:s.measurementScope,scopeKey:s.measurementScopeKey,marketKey:s.marketKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId}),[s.measurementScope,s.measurementScopeKey,s.marketKey,s.queryClass,s.provider,s.model,s.location,s.from,s.to,s.revision,s.measurementRunId]),h=Le({...ar({client:Y,path:{name:t},query:{...si(s),cursor:l,search:c||void 0}}),staleTime:Bl,retry:!1,placeholderData:wi}),y={...x,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??h.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??h.data?.selection.revision??s.revision,limit:50},f=JSON.stringify(y),b=Le({...ar({client:Y,path:{name:t},query:{...y,cursor:m?.selection===f?m.cursor:void 0}}),enabled:!!s.queryKey&&!!h.data&&!h.isPlaceholderData,retry:!1});if(o.useEffect(()=>{if(s.queryClass!=="all"||!h.data||h.isPlaceholderData||h.isFetching||h.isError||h.data.selection.availability.state==="unsupported"||h.data.populations.length===0||s.queryKey&&!s.answer&&!xi(h.data,s.queryKey)&&!b.data)return;const N=Li(h.data,s.queryKey,s.answer,b.data);if(!l&&!c){const{queryKey:k}=ar({client:Y,path:{name:t},query:si({...s,queryClass:N.queryClass})});p.setQueryData(k,{...h.data,selection:{...h.data.selection,queryClass:N.queryClass},populations:[N]},{updatedAt:h.dataUpdatedAt})}n({queryClass:N.queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}},{replace:!0})},[s.queryClass,s.queryKey,s.answer,h.data,h.dataUpdatedAt,h.isPlaceholderData,h.isFetching,h.isError,b.data,n,p,t,x,l,c]),h.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:a});if(h.data&&$c(h.data,r))return e.jsx(e.Fragment,{children:a});if(h.error){const N=zl(Ql(h.error)),k=N?.reason===mu["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:k?Ba.retiredMarket:N?Ba.retiredScope:ya(h.error)}),k?e.jsx(P,{variant:"outline",onClick:()=>{i(void 0),n({measurementMarketKey:void 0})},children:Ba.showAllMarkets}):N?e.jsx(P,{variant:"outline",onClick:()=>{i(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:Ba.showWholeSite}):e.jsx(P,{variant:"outline",onClick:()=>{i(void 0),h.refetch()},children:"Retry"})]})}return h.data?e.jsx("div",{"aria-busy":h.isFetching,children:e.jsx(qg,{report:h.data,isRefreshing:h.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:b.data,isEvidenceLoading:b.isFetching||!!s.queryKey&&b.isPending,evidenceError:b.error?ya(b.error):void 0,onRetryEvidence:()=>{b.refetch()},onEvidencePage:b.isFetching?void 0:N=>u({selection:f,cursor:N}),search:c,onSearch:N=>{d(N),i(void 0)},onPage:h.isFetching?void 0:i,onSelectionChange:N=>{(!("measurementQueryKey"in N)||Object.keys(N).some(k=>k!=="measurementQueryKey"&&k!=="measurementAnswer"))&&i(void 0),u(void 0),n(N)}})}):e.jsx("section",{className:"page-section-divider",role:"status","aria-label":"Loading AI visibility",children:e.jsx("div",{className:"h-64 animate-pulse rounded-md bg-surface"})})}function Og({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,fallback:l,showUnmeasuredFallback:i=!1}){const c=Mc(t,s,{enabled:!0}),d=c.error?void 0:c.data,m=!c.isPlaceholderData&&d?.selection.availability.state==="available"?d.selection.run.id:null;uu(m,null);const u=!!(d&&d.selection.availability.state==="available"&&!$c(d,i));return e.jsxs(e.Fragment,{children:[u?e.jsx(Lg,{report:d,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}):null,!u&&(d||c.error)?e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsx($l,{})}):null,e.jsx(Dg,{projectName:t,selection:s,onSelectionChange:n,fallback:l,showUnmeasuredFallback:i},`${t}:${JSON.stringify({...s,queryKey:void 0,answer:void 0})}`)]})}const Fg=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Gg=[{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."}],qi=ct[2],Kg=ct[4],_g="var(--chart-tooltip-bg)",Ug={up:"text-positive-400",down:"text-negative-400",none:"text-muted"};function Lc({direction:t,magnitude:s}){switch(t){case"up":return`up ${s} points`;case"down":return`down ${s} points`;case"none":return"no change"}}function Bg(t){return t.direction==="none"?"no change over the period":`${Lc(t)} over the period`}function Vg(t){return t===Aa||t===Ra||t===Fs}function qc(t){return t===Aa?"Cited":t===Ra?"Mentioned":t===Fs?"Mention share":lt(t)}function da(t,s){return t===Aa?Hn.positive:t===Ra?ct[1]:t===Fs?qi:Kh(wa(t),s)}function Ei(t){return t==="non-brand"?"non-brand answers":"all answers"}function gi(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function Di(t,s){return t==="mentionShare"?`Mention share in ${Ei(s)}`:gi(t)}function zg(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 Ec(t){return t==="cited"?"citationRate":"mentionRate"}function Oi(t,s){return s==="cited"?t.cited:t.mentionedCount}function Dc(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 Qg(t,s){if(s==="mentionShare"){const{projectMentionSnapshots:n,competitorMentionSnapshots:a}=t.mentionShare;return`${n} of ${n+a} tracked-brand mentions`}return`${Oi(t,s)} of ${t.total} answers`}function Hg(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Oc(t){const s=gc(t);return s===null?[]:Object.entries(s).sort(([n],[a])=>wa(n).localeCompare(wa(a))).map(([n,a])=>`${lt(n)}: ${Sa(a)}`)}function Fc(t,s){return new Date(t).toDateString()===new Date(s).toDateString()}function Xo(t){return`${t} ${t===1?"query":"queries"}`}function Fi(t){const{added:s,removed:n}=t;return[...s.length>0?[`${Xo(s.length)} added`]:[],...n.length>0?[`${s.length>0?n.length:Xo(n.length)} removed`]:[]].join(", ")}function Gc(t,s){const n=Ms(t),a=Pa(t),r=jc(t,s);if(!n||!a||!r)return null;const l=tx(r.moves),i=Fc(n.start,n.end),c=d=>gr(d,i?n.start:null);return n.sweepCount===2?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes the ",e.jsx("strong",{children:c(n.start)})," sweep and the ",e.jsx("strong",{children:c(n.end)})," sweep, with ",l," between them"]}):r.moves.added.length+r.moves.removed.length>0?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes sweeps with ",l," between them"]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point pools ",e.jsx("strong",{children:n.sweepCount})," sweeps, with ",l," between the first and last"]})}function Wg(t,s,n){const a=Gc(s,n);return a?e.jsxs(e.Fragment,{children:["Not the same queries: ",a]}):t.changes.length>0?e.jsxs(e.Fragment,{children:["Not the same queries: ",t.changes.map((r,l)=>e.jsxs(o.Fragment,{children:[l>0?", ":"",Fi(r)," ",e.jsx("strong",{children:Na(Bt(r.at))})]},r.at)),"; first and latest points cover different queries"]}):e.jsxs(e.Fragment,{children:["Not the same queries: first and latest points have answers for ",e.jsx("strong",{children:t.firstCount})," and ",e.jsx("strong",{children:t.latestCount})," queries"]})}function Zo(t){return t.replace(/ /g," ")}function pr({state:t,from:s=!1}){return e.jsx("span",{className:s?"av-model av-model-from":"av-model",children:Sa(t)})}function Yg(t,s){return t.reroute?"Same preset, answered with a different model.":ur(t.provider,t.to)?t.served?`Preset picks its own model. Answered with ${Sa(t.served.to)} (was ${Sa(t.served.from)}).`:s&&s.length>0?`Preset picks its own model. Answered with ${s.join(", ")}.`:"Preset picks its own model.":null}function Jg({buckets:t,queryChanges:s,modelRows:n,served:a,pointerNotices:r,truncated:l,incompleteHistory:i,queryName:c,sweepTimes:d}){const m=t.at(-1),u=g=>Na(g),p=new Map;for(const[g,v]of r){const C=n.find(I=>I.provider===g&&!I.reroute&&I.to.status==="known"&&v.modelIds.includes(I.to.model));C&&p.set(g,C)}const x=[];s.length>0&&x.push({key:"queries",label:"Queries",rows:s.map(g=>({key:`queries-${g.at}`,at:g.at,onOrBefore:!1,from:null,to:e.jsx("span",{className:"text-strong",children:Fi(g)}),toHelp:null}))});const h=[...new Set(n.map(g=>g.provider))].sort((g,v)=>lt(g).localeCompare(lt(v)));for(const g of h){const C=a[g]?.latestServedModelIds??null,I=n.filter(A=>A.provider===g);x.push({key:g,label:lt(g),rows:I.map((A,w)=>{const V=p.get(g)===A?r.get(g).text:null,G=[Yg(A,w===0?C:null),V].filter(Boolean).join(" ");return{key:`${g}-${A.at}-${A.reroute?"served":"set"}`,at:A.at,onOrBefore:A.onOrBefore,from:e.jsx(pr,{state:A.from,from:!0}),to:e.jsx(pr,{state:A.to}),toHelp:G||null}})})}const y=x.reduce((g,v)=>g+v.rows.length,0),f=[];for(const g of s)g.added.length>0&&f.push(e.jsxs(e.Fragment,{children:["Added ",e.jsx("strong",{children:u(g.at)}),": ",g.added.map(c).join(", ")]})),g.removed.length>0&&f.push(e.jsxs(e.Fragment,{children:["Removed ",e.jsx("strong",{children:u(g.at)}),": ",g.removed.map(c).join(", ")]}));const b=m?Pa(m):null;for(const[g,v]of Object.entries(m?gc(m)??{}:{}).sort(([C],[I])=>C.localeCompare(I)))v.status==="mixed"&&b&&f.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:b})," point mixes ",lt(g)," models: ",Dp(v)]}));const N=new Map;for(const g of n.filter(v=>v.onOrBefore)){const v=g.anchorAt?u(g.anchorAt):"";N.set(v,[...new Set([...N.get(v)??[],lt(g.provider)])])}for(const[g,v]of N)f.push(g?e.jsxs(e.Fragment,{children:["Changed before this date range, after the ",e.jsx("strong",{children:g})," sweep: ",ga(v)]}):`Changed before this date range: ${ga(v)}`);for(const g of l)f.push(`${lt(g.provider)}: most recent ${g.shown} of ${g.total} changes`);for(const g of i)f.push(`${lt(g)}: may be missing older changes`);for(const[g,v]of r)p.has(g)||f.push(e.jsxs("span",{className:"inline-flex items-center gap-1",children:[lt(g),": no model updates on record",e.jsx(Fe,{text:v.text})]}));if(y===0&&f.length===0)return null;for(const[g,v]of Object.entries(a).sort(([C],[I])=>lt(C).localeCompare(lt(I)))){const C=v.latestServedModelIds??[],I=C.length>0?C.join(", "):Sa(v.latestObservation.state);f.push(e.jsxs(e.Fragment,{children:[lt(g)," last answered with ",e.jsx("strong",{children:I})," on ",e.jsx("strong",{children:u(Bt(v.latestObservation.observedAt))})]}))}const k=x.flatMap(g=>g.rows.map(v=>v.at));let $="First sweep on the new model or query set.";if(k.length>0){const g=u(k.reduce((V,G)=>Date.parse(G)>Date.parse(V)?G:V)),v=[...new Set(k.filter(V=>u(V)===g))].sort(),C=v.map(V=>gr(V,V));$+=` ${g} = the ${ga(C)} ${C.length===1?"sweep":"sweeps"}.`;const I=n.flatMap(V=>V.anchorAt?[V.anchorAt]:[]),A=I.length>0?I.reduce((V,G)=>Date.parse(G)>Date.parse(V)?G:V):null,w=Jp(v[0],d,t,A);w&&($+=` Sweep before: ${u(w)}.`)}const S=Yp({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:S}),e.jsxs("span",{className:"av-wc-toggle",children:[e.jsxs("span",{className:"av-wc-when-closed",children:[y>0?`Show all ${y}`:"Details"," ",e.jsx("span",{"aria-hidden":"true",children:"▸"})]}),e.jsxs("span",{className:"av-wc-when-open",children:["Hide ",e.jsx("span",{"aria-hidden":"true",children:"▴"})]})]})]}),e.jsx("div",{className:"av-wc-body",children:y>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"av-change-table",children:[e.jsx("caption",{className:"sr-only",children:"Query and model changes, newest first"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Changed"})}),e.jsx("th",{scope:"col","aria-label":"Date",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:["Date",e.jsx(Fe,{text:$})]})}),e.jsx("th",{scope:"col",children:"From"}),e.jsx("th",{scope:"col",children:"To"})]})}),x.map(g=>e.jsx("tbody",{children:g.rows.map((v,C)=>e.jsxs("tr",{children:[C===0?e.jsx("th",{scope:"row",className:"av-engine",children:g.label}):e.jsx("td",{className:"av-engine",children:e.jsx("span",{className:"sr-only",children:g.label})}),e.jsx("td",{className:"av-date",children:v.onOrBefore?`on or before ${Zo(u(v.at))}`:Zo(u(v.at))}),v.from===null?null:e.jsx("td",{children:v.from}),e.jsx("td",{colSpan:v.from===null?2:void 0,children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[v.to,v.toHelp?e.jsx(Fe,{text:v.toHelp}):null]})})]},v.key))},g.key))]})}),e.jsx(ka,{items:f})]}):e.jsx("ul",{className:"av-details-list",children:f.map((g,v)=>e.jsx("li",{children:g},v))})})]})}function Xg({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:lt(s)}),e.jsxs("span",{className:"text-secondary",children:["selected ",e.jsx(pr,{state:n.configured})," · answered ",e.jsx(pr,{state:n.served})]}),e.jsx("span",{className:"av-status text-caution-400",children:"substituted"})]},s))})}function Zg({active:t,label:s,payload:n,metric:a,mode:r,buckets:l,basketChanges:i}){if(!t)return null;const c=Hg(l,s);if(!c)return null;const d=Ms(c),m=d!==null&&Fc(d.start,d.end)?d.start:null,u=bc(c,i),p=Oc(c),x=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-tooltip-label",children:Mi(c)}),u.map(f=>e.jsxs("p",{className:"trend-tooltip-detail trend-tooltip-note",children:[Fi(f)," ",gr(f.at,m)]},f.at))]}),h=p.length>0&&e.jsx("p",{className:"trend-tooltip-detail trend-tooltip-models",children:p.map((f,b)=>e.jsxs(o.Fragment,{children:[b>0?"; ":"",e.jsx("span",{className:"whitespace-nowrap",children:f})]},b))});if(a==="mentionShare"){const f=c.mentionShare.projectMentionSnapshots,b=c.mentionShare.competitorMentionSnapshots,N=f+b;return e.jsxs("div",{className:"trend-tooltip",children:[x,e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:qi},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Di("mentionShare",c.mentionShare.scope)}),e.jsx("span",{className:"trend-tooltip-value",children:Ze(c.mentionShare.rate)})]}),e.jsx("p",{className:"trend-tooltip-detail",children:N>0?`You ${f} of ${N} tracked-brand mentions. Competitors ${b}.`:"No tracked-brand mentions in this point"}),h]})}const y=r==="byProvider"?(n??[]).filter(f=>f.dataKey!==void 0):[{dataKey:a==="cited"?Aa:Ra}];return e.jsxs("div",{className:"trend-tooltip",children:[x,y.map((f,b)=>{const N=String(f.dataKey??f.name??""),k=r==="byProvider"?Dc(c,N,a):null,$=k?.count??Oi(c,a),S=k?.total??c.total,g=k?k.rate:c[Ec(a)],v=f.color??da(N,b);return e.jsx("div",{className:"trend-tooltip-block",children:e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:v},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:qc(N)}),e.jsx("span",{className:"trend-tooltip-value",children:Ze(g)}),e.jsxs("span",{className:"trend-tooltip-count",children:[$," of ",S]})]})},`${N}-${b}`)}),h]})}function ef({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:[Di(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,p=Ei(l.mentionShare.scope);i=u>0?`${Ze(l.mentionShare.rate)} mention share in ${p}, ${d} of ${u} tracked-brand mentions were you`:`mention share undefined in ${p}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(d=>{const m=Dc(l,d,s);return m?`${lt(d)} ${Ze(m.rate)} ${gi(s).toLowerCase()}, ${m.count} of ${m.total} answers`:`${lt(d)} no data`}).join("; "):i=`${Ze(l[Ec(s)])} ${gi(s).toLowerCase()}, ${Oi(l,s)} of ${l.total} answers`;const c=Oc(l);return c.length>0&&(i+=`; models: ${c.join("; ")}`),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Mi(l)}),e.jsx("td",{children:i})]},l.startDate)})})]})})}function tf({projectName:t,competitorDomains:s=[],competitorAliases:n,analyticsRevision:a="none",queryTexts:r=[],classifyQuery:l,sweepTimes:i=[]}){const[c,d]=o.useState("all"),[m,u]=o.useState("mentioned"),[p,x]=o.useState("byProvider"),h=o.useId(),y=o.useMemo(()=>Ip(s,n),[s,n]),f=Le({queryKey:["analytics-metrics",t,c,y,a],queryFn:()=>du(t,c),staleTime:Ri}),b=f.data??null,N=f.error,k=m==="mentionShare"?"overall":p,$=o.useMemo(()=>b?_p(b,m,k):null,[b,m,k]),S=b?$p(b):null,g=o.useMemo(()=>Fp(S??{}),[S]),v=o.useMemo(()=>Gp(S??{}),[S]),C=o.useMemo(()=>Object.entries(S??{}).filter(([,ge])=>ge.anchorUnavailable).map(([ge])=>ge).sort(),[S]),I=o.useMemo(()=>b?Lp(b):{},[b]),A=o.useMemo(()=>b?zp(qp(b)):[],[b]),w=o.useMemo(()=>b?yc(b):[],[b]),V=o.useMemo(()=>b?Qp(b):[],[b]),G=o.useMemo(()=>Wp(S??{},I),[S,I]),Q=o.useMemo(()=>b?Ep(b):{},[b]),B=o.useMemo(()=>no(Q,{engineName:lt}),[Q]),z=o.useMemo(()=>{const ge=new Map;for(const[we,_e]of Object.entries(Q).sort(([Ee],[O])=>Ee.localeCompare(O))){const Ee=no({[we]:_e},{engineName:lt});Ee?.kind==="no-known-change"&&ge.set(we,{text:`${Ee.text} ${Ee.detail}`,modelIds:_e.modelIds??[]})}return ge},[Q]),ne=o.useMemo(()=>{const ge=new Map(r.map(we=>[Kn(we),we]));return we=>ge.get(Kn(we))??we},[r]),F=m!=="mentionShare"&&k==="byProvider",_=b?.buckets??[],Z=_[_.length-1]?.mentionShare.scope??b?.mentionShareScope??"pooled",L=Di(m,Z),ee=F?us.textDim:m==="cited"?Hn.positive:m==="mentionShare"?qi:ct[1],T=o.useMemo(()=>{const ge=new Map(_.map(we=>[we.startDate,Pp(we)]));return we=>ge.get(String(we))??""},[_]),E=m==="mentionShare"?_.filter(ge=>typeof ge.mentionShare.rate=="number"&&Number.isFinite(ge.mentionShare.rate)):_,te=E.at(-1),ce=(b?Up(b,m):[]).at(-1)??null,Ne=b?Bp(b,m):null,X=ex(E,w),ue=jo(X,m,Z,l),pe=ce!==null&&Ne!==null?Vl(Ne.delta):null,J=pe!==null&&!ue,me=s.length,K=[];if(te&&Ne!==null&&X&&!ue&&K.push(Wg(X,te,w)),te&&E.length===1){const ge=Gc(te,w);ge&&!jo(jc(te,w),m,Z,l)&&K.push(ge)}if(pe!==null&&E[0]){const ge=Pa(E[0]);ge&&K.push(e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:ge})," point"]}))}F&&ce!==null&&K.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:Ze(ce)})," pools all answers; not an average of engines"]}));const he=[...new Set([...g.buckets.map(ge=>ge.bucketStartDate),..._.filter(ge=>bc(ge,w).length>0).map(ge=>ge.startDate)])].sort(),qe=ce!==null&&te&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:ee},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:L}),e.jsx("span",{className:"visibility-trend-current-value",children:Ze(ce)}),pe!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${J?"text-muted":Ug[pe.direction]}`,children:[Lc(pe),J?" (not the same queries)":""]}),e.jsxs("span",{className:"visibility-trend-current-detail",children:["· ",Qg(te,m)]})]}),Re=e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(xa,{options:Gg,value:m,onChange:u,label:"Metric",className:"visibility-trend-metric-control"}),m!=="mentionShare"&&e.jsx(xa,{options:Fg,value:p,onChange:x,label:"Series"}),e.jsx(xa,{options:fg,value:c,onChange:d,label:"Time window",className:"sm:ml-auto"})]});let ie;if(N)ie=e.jsx("p",{className:"text-sm text-negative-400",children:ya(N)});else if(f.isLoading&&!b)ie=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(m==="mentionShare"&&me===0)ie=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!b||!$)ie=null;else{const{rows:ge,series:we,hasData:_e}=$;if(!_e)ie=e.jsx("p",{className:"text-sm text-secondary",children:m==="mentionShare"?`No answer-text brand mentions for you or tracked competitors in ${Ei(Z)} in this window yet.`:cs()?Un:"Run a sweep to start tracking citations and mentions over time."});else if(F&&we.length===0)ie=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 Ee=`${L} rate across ${ge.length} ${ge.length===1?"sweep":"sweeps"}. Latest ${Ze(ce)}${pe!==null?`, ${Bg(pe)}${J?", not the same queries":""}`:""}.`;ie=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:Ee}),e.jsx(ef,{buckets:_,metric:m,mode:k,series:we,mentionShareScope:Z}),F&&we.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:we.map((O,D)=>{const H=Vp(b,O,m);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:da(O,D)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:qc(O)}),H!==null&&e.jsx("span",{className:"trend-legend-value",children:Ze(H)})]},O)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${L} trend chart over ${ge.length} ${ge.length===1?"point":"points"}`,children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:ge,margin:{top:8,right:20,bottom:0,left:0},children:[e.jsx(ja,{stroke:ba,vertical:!1}),e.jsx(sn,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:ds},tickFormatter:T,minTickGap:24}),e.jsx(nn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:O=>Ze(O,Qn.percent),tick:Ut,tickLine:!1,axisLine:!1,width:40}),e.jsx(an,{cursor:{stroke:ds,strokeWidth:1},content:e.jsx(Zg,{metric:m,mode:k,buckets:_,basketChanges:w})}),he.map(O=>e.jsx(op,{x:O,stroke:Kg,strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`setup-change-${O}`)),we.map((O,D)=>e.jsx(Ds,{type:"monotone",dataKey:O,name:O,stroke:da(O,D),strokeDasharray:O===Fs?"5 4":void 0,strokeWidth:Vg(O)?2.5:2,dot:O===Fs?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:da(O,D),strokeWidth:1.5}:{r:2.5,fill:da(O,D),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:_g},connectNulls:O!==Fs,isAnimationActive:!1},O))]})})}),he.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":h,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:h,className:"av-card-title",children:"AI answers over time"}),e.jsx(Fe,{text:zg(Z)})]}),te?e.jsx("p",{className:"av-card-meta",children:Mi(te)}):null]}),e.jsxs("div",{className:"visibility-trend-body",children:[B?.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:B.text}),qe,Re,ie]}),e.jsx(ka,{items:K})]}),b&&!N?e.jsxs(e.Fragment,{children:[e.jsx(Jg,{buckets:_,queryChanges:V,modelRows:G,served:I,pointerNotices:z,truncated:v,incompleteHistory:C,queryName:ne,sweepTimes:i}),e.jsx(Xg,{substitutions:A})]}):null]})}const el=new Set([pa.queued,pa.running]),_t={queryPlaceholder:"Write one research query per line",runAction:"Run queries",historyTitle:"Research history",historyMore:"Load older runs",historyLoading:"Loading older runs…",historyMoreError:"Could not load older research. Try again.",resultsTitle:"Research results",emptyHistory:"No saved research.",resultsEmpty:"Choose a saved run.",methodologySummary:"How matching works",methodology:"Brand-name matches use configured project names or domains in answer text. Project-domain citations use source links. Neither verifies property identity.",refreshPreview:"Regenerate preview",templateProvenance:"Query pattern details",brandedQuery:"Branded",discoveryQuery:"Discovery",unclassifiedQuery:"Unclassified"};function tl({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d=[],viewerResearchConfig:m=null}){const u=hs(),{account:p,canWrite:x}=rn(),h=p?.role==="viewer"&&m!==null,y=!x,f=ms(),[b,N]=o.useState(""),[k,$]=o.useState(""),[S,g]=o.useState(null),[v,C]=o.useState([]),I=o.useRef(null),A=o.useRef(!1),[w,V]=o.useState(0),G=Le({...hu({client:Y,path:{name:t}}),staleTime:6e4}),Q=Le({...pu({client:Y}),enabled:!y&&!f,staleTime:6e4}),B={client:Y,path:{name:t},query:{limit:20}},z=Ml({...xu(B),initialData:void 0,initialPageParam:B,getNextPageParam:K=>K.nextCursor?{path:B.path,query:{...B.query,cursor:K.nextCursor}}:void 0,refetchInterval:K=>K.state.data?.pages.some(he=>he.runs.some(qe=>el.has(qe.status)))?3e3:!1}),ne=z.isError&&!z.isFetchNextPageError,F=z.data?.pages.at(-1),_=ne?[]:[...new Map((z.data?.pages.flatMap(K=>K.runs)??[]).map(K=>[K.id,K])).values()],Z=F?.access?.canRun??(x||h),L=F?.access?F.access.dailyRunLimit:h?m.viewerDailyRunLimit:null;o.useEffect(()=>{!S&&_[0]&&g(_[0].id)},[_,S]);const ee=_.find(K=>K.id===S)??null,T=Le({...gu({client:Y,path:{name:t,runId:S??""}}),enabled:!ne&&!!S,refetchInterval:ee&&el.has(ee.status)?3e3:!1}),E=ne||T.isError?null:T.data??null,te=G.data?.locations??[],re=o.useMemo(()=>{if(y)return(F?.providers??[]).map(he=>({...he,catalog:he}));const K=new Map((Q.data?.providerCatalog??[]).map(he=>[he.name,he]));return(Q.data?.providers??[]).filter(he=>he.configured&&K.get(he.name)?.mode==="api").map(he=>({...he,catalog:{...K.get(he.name),defaultModel:he.model||K.get(he.name).defaultModel}}))},[y,F?.providers,Q.data]),ce=!(y?z.isPending:Q.isPending)&&re.length===0,Ne=re.find(K=>K.name===b)??null;o.useEffect(()=>{if(!b&&G.data&&!G.isError&&!Q.isError){const K=G.data.providers.find(he=>re.some(qe=>qe.name===he));N(K??re[0]?.name??"")}},[b,re,G.data,G.isError,Q.isError]);const X=Ne?.catalog.modelConfigurable??!1,ue=y?Ne?.catalog.defaultModel:(Ne?G.data?.providerModels[Ne.name]:"")||Ne?.catalog.defaultModel,pe=(X?k.trim():"")||ue,J=Ne?[...new Map([{id:Ne.catalog.defaultModel,displayName:Ne.catalog.defaultModel},...k.trim()?[{id:k.trim(),displayName:k.trim()}]:[],...Ne.catalog.knownModels].map(K=>[K.id,K])).values()]:[],me=Dt({...fu(),onSuccess:async K=>{I.current=null,V(he=>he+1),C(K.runs),g(K.runs[0]?.id??null),await mf(u),De({title:"Research batch saved",detail:`${K.runs.length} ${K.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${K.runs.map(he=>he.id).join(":")}`,dedupeMode:"replace"})},onError:K=>{De({title:"Could not start research",detail:K instanceof Error?K.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{A.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[f?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(sf,{projectName:t,canWrite:x,researchAllowed:Z&&!ne,limitedAccess:y,isEmbed:le(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d,locations:te,defaultLocation:G.data?.defaultLocation??null,providerOptions:re,provider:b,onProviderChange:K=>{N(K),$("")},resolvedModel:pe,visibilityModel:ue,configurableModel:X,model:k,onModelChange:$,modelOptions:J,settingsReady:y?!z.isPending&&!ne:!Q.isPending&&!Q.isError&&!Q.isFetching,projectReady:!G.isPending&&!G.isError&&!G.isFetching,isPending:me.isPending,errorMessage:me.isError?"The request could not be confirmed.":void 0,onSubmit:(K,he)=>{!Z||ne||le()||A.current||(I.current?.fingerprint!==he&&(I.current={fingerprint:he,key:crypto.randomUUID()}),A.current=!0,me.mutate({client:Y,path:{name:t},body:{...K,idempotencyKey:I.current.key}}))}},`${t}:${w}`),L!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",L," destination runs per project per day."]}),!y&&Q.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(P,{variant:"outline",onClick:()=>{Q.refetch()},children:"Retry providers"})]}):null,G.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(P,{variant:"outline",onClick:()=>{G.refetch()},children:"Retry locations"})]}):null,!(y?ne:Q.isError)&&ce&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:y?"No research engines are available. Ask your Canonry team to configure one.":"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."}),v.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",v.map((K,he)=>e.jsxs("span",{children:[he>0?", ":"",e.jsxs("a",{href:`#research-run-${K.id}`,className:"text-link underline",onClick:()=>g(K.id),children:[K.scope?.label??"Whole site",K.location?`, ${K.location.label}`:", No location"]})]},K.id))]})]}),e.jsxs(ve,{className:"surface-card min-w-0",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsx("div",{children:e.jsx("h3",{children:_t.historyTitle})}),z.isFetching&&e.jsx(je,{tone:"neutral",children:"Loading"})]}),ne?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(P,{variant:"outline",onClick:()=>{z.refetch()},children:"Retry history"})]}):z.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):_.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:_t.emptyHistory}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Destination"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:_.map(K=>e.jsxs("tr",{className:S===K.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:()=>g(K.id),children:cf(K.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:K.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:K.requestedModel??K.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:K.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:K.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[K.completedQueries+K.failedQueries,"/",K.totalQueries]}),e.jsx("td",{children:e.jsx(je,{tone:Kc(K.status),children:K.status})})]},K.id))})]})}),z.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:_t.historyMoreError}),z.hasNextPage&&e.jsx(P,{className:"mt-3",variant:"outline",disabled:z.isFetching,onClick:()=>{z.fetchNextPage()},children:z.isFetchingNextPage?_t.historyLoading:_t.historyMore})]})]}),!ne&&T.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(P,{variant:"outline",onClick:()=>{T.refetch()},children:"Retry results"})]}):ne?null:e.jsx(of,{detail:E,isLoading:T.isFetching,onReviewForTracking:f?void 0:s})]})}const Ps="mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50",En="__none__";function sf(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:l}=t,i=hs(),[c,d]=o.useState("once"),[m,u]=o.useState(""),[p,x]=o.useState(""),[h,y]=o.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[f,b]=o.useState(null),[N,k]=o.useState([]),[$,S]=o.useState(""),[g,v]=o.useState({}),[C,I]=o.useState(null),[A,w]=o.useState([]),[V,G]=o.useState(null),[Q,B]=o.useState(!1),[z,ne]=o.useState(!1),[F,_]=o.useState(""),[Z,L]=o.useState(""),ee=o.useRef(null),T=o.useRef(!1),E=o.useRef(null),te=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";o.useEffect(()=>{y(te),I(null)},[te]);const re=t.scopeOptions.filter(R=>R.kind==="market"||R.kind==="property"),ce=c==="markets"?"market":"property",Ne=re.filter(R=>R.kind===ce),X=R=>({kind:R.kind,key:R.id,label:R.label,planRevision:l??t.initialScope?.planRevision??0}),ue=R=>R===En?null:n.find($e=>$e.label===R),pe=f??t.defaultLocation??En,J=re.find(R=>`${R.kind}:${R.id}`===h),me=J?X(J):null,K=c==="once"?[{scope:me,location:ue(pe)}]:c==="locations"?N.map(R=>({scope:null,location:ue(R)})):N.map(R=>Ne.find($e=>`${$e.kind}:${$e.id}`===R)).map(R=>R?{scope:X(R),location:ue(g[`${R.kind}:${R.id}`]??En)}:null),he=[...new Map([...A,...t.templates].map(R=>[R.id,R])).values()],qe=C?he.find(R=>R.id===C.id):null,Re=C!==null&&qe?.version!==C.version,ie=c==="once"?m:p,ge=ie.split(/\r?\n/).filter(R=>R.trim()),we=ao(ge),_e=[...new Set([...p.matchAll(/\{([^{}]+)\}/g)].map(R=>R[1]))],Ee=/[{}]/.test(p.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),O=[];ge.length||O.push(c==="once"?"Enter at least one query.":"Enter at least one query pattern."),ge.some(R=>R.length>4e3)&&O.push("Keep each query under 4,001 characters."),c!=="once"&&Ee&&O.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),K.length||O.push(c==="locations"?"Select at least one location.":"Select at least one destination."),K.some(R=>!R||R.location===void 0)&&O.push("A selected destination or location is no longer available. Update your selection.");const D=c==="once"&&h!=="project"||c==="markets"||c==="properties";D&&(t.scopePending||t.scopeError||!l||K.some(R=>!R?.scope))&&O.push("Load the current published markets and properties before running scoped research.");const H=(c==="once"?we.length:ge.length)*K.length;if(K.length>Da&&O.push(`Select at most ${Da} destinations.`),H>Cr&&O.push(`${H} queries selected. Reduce the selection to ${Cr} or fewer.`),Re&&O.push("This saved pattern changed. Select its current version from Saved patterns."),c!=="once"&&!Ee){for(const R of K)if(!(!R||R.location===void 0))try{Sr(C??{pattern:p,variables:_e},R.scope,R.location)}catch{O.push(`Choose a location for {location}, or use only variables available for ${c==="markets"?"markets":c==="properties"?"properties":"locations"}.`);break}}const Me=JSON.stringify({mode:c,source:ie,contexts:K,provider:a,resolvedModel:r,template:C,...D?{planRevision:l}:{}}),Qe=V!==null&&V.signature!==Me,Ge=c==="once"?we.map((R,$e)=>({id:String($e),query:R,scope:me,location:K[0]?.location??null})):V?.rows??[],et=rf(Ge),xe=[];c!=="once"&&V&&(Qe&&xe.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),Ge.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."),Ge.some(R=>R.location&&!n.some($e=>JSON.stringify($e)===JSON.stringify(R.location)))&&xe.push("A preview location changed. Regenerate the preview."),et.some(R=>ao(R.queries).length!==R.queries.length)&&xe.push("Remove duplicate queries within each destination and location."),et.length>Da&&xe.push(`The preview exceeds ${Da} runs.`));const jt=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!O.length&&!xe.length&&(c==="once"||V!==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}:{}}))}),Je=()=>{if(B(!0),O.length)return;const R=K.flatMap(($e,Te)=>ge.map((Ue,ut)=>({id:`${Te}:${ut}`,scope:$e.scope,location:$e.location,...C?{template:{templateId:C.id,templateVersion:C.version,bindingLocation:$e.location}}:{},query:Sr({pattern:Ue,variables:[...new Set([...Ue.matchAll(/\{([^{}]+)\}/g)].map(Be=>Be[1]))]},$e.scope,$e.location).output})));G({signature:Me,rows:R})},Ot=R=>{d(R),k([]),I(null),S(""),B(!1)},dt=R=>{if(L(""),c==="once")try{u(Sr(R,me,ue(pe)).output)}catch{L("Select a matching market, property, or location before using this pattern.");return}else x(R.pattern);I(R)},st=R=>{const $e=E.current,Te=$e?.selectionStart??p.length,Ue=$e?.selectionEnd??Te;x(`${p.slice(0,Te)}{${R}}${p.slice(Ue)}`),I(null),requestAnimationFrame(()=>{$e?.focus(),$e?.setSelectionRange(Te+R.length+2,Te+R.length+2)})},ht=Dt({...bu(),onSuccess:async R=>{const $e={id:R.id,version:R.updatedAt,label:R.name,pattern:R.pattern,variables:R.variables};w(Te=>[...Te.filter(Ue=>Ue.id!==R.id),$e]),I($e),ne(!1),_(""),L(""),ee.current=null,await i.invalidateQueries({queryKey:yu({client:Y,path:{name:s}})}),De({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>L("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{T.current=!1}}),kt=()=>{if(!t.canWrite||t.isEmbed||T.current)return;const R=c==="once"?m:p,$e=c==="once"?[]:_e;if(!F.trim()||!R.trim()||R.length>4e3||c!=="once"&&Ee){L("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const Te={name:F.trim(),pattern:R,variables:$e},Ue=JSON.stringify(Te);ee.current?.fingerprint!==Ue&&(ee.current={fingerprint:Ue,id:crypto.randomUUID()}),T.current=!0,ht.mutate({client:Y,path:{name:s,templateId:ee.current.id},body:Te})},Mt=[...new Set([...Q||ie.trim()?O:[],...xe])],He=he.filter(R=>{const $e=c==="once"?ro(me,ue(pe)):ro(c==="markets"?{kind:"market",label:"Market"}:c==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return R.variables.every(Te=>$e[Te]!==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||ht.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:Ps,value:c,disabled:t.isPending,onChange:R=>Ot(R.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!re.some(R=>R.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!re.some(R=>R.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),c==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(re.length>0||h!=="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:Ps,value:h,onChange:R=>{y(R.target.value),I(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),h!=="project"&&!J&&e.jsx("option",{value:h,disabled:!0,children:"Selected destination unavailable"}),re.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:pe,locations:n,onChange:R=>{b(R),I(null)}})]}),c!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:c==="locations"?"Select locations":`Select ${c}`}),e.jsx("p",{className:"text-sm text-secondary",children:"Choose each destination explicitly. Each selected destination gets its own saved research run."}),e.jsx("input",{type:"search","aria-label":"Search destinations",className:Ps,placeholder:`Search ${c}`,value:$,onChange:R=>S(R.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(c==="locations"?n.map(R=>({key:R.label,label:R.label})):Ne.map(R=>({key:`${R.kind}:${R.id}`,label:R.label}))).filter(R=>R.label.toLocaleLowerCase().includes($.toLocaleLowerCase())).map(R=>{const $e=N.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:$e,onChange:()=>k(Te=>$e?Te.filter(Ue=>Ue!==R.key):[...Te,R.key])}),R.label]}),$e&&c!=="locations"&&e.jsx(fi,{label:`Answer engine location for ${R.label}`,value:g[R.key]??En,locations:n,onChange:Te=>v(Ue=>({...Ue,[R.key]:Te}))})]},R.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[N.length," selected. A market or property name changes query text, not the answer engine's location."]})]}),t.scopeError&&e.jsxs("p",{className:"text-sm text-caution",children:["Markets and properties could not load. Whole-site and location research remain available. ",e.jsx(P,{variant:"outline",onClick:t.onRetryScope,children:"Retry destinations"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block",htmlFor:"research-query-editor",children:e.jsx("span",{className:"text-sm font-medium text-heading",children:c==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:c==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${c==="markets"?"market":c==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:E,className:`${Ps} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:ie,placeholder:c==="once"?_t.queryPlaceholder:c==="markets"?"Best apartments in {market}":c==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:R=>{c==="once"?u(R.target.value):(x(R.target.value),I(null))}}),c!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(P,{size:"sm",variant:"outline",onClick:()=>st(c==="markets"?"market":c==="properties"?"property":"location"),children:["Insert ",c==="markets"?"market":c==="properties"?"property":"location"," name"]}),e.jsx("span",{className:"self-center text-sm text-secondary",children:"One pattern per line."})]}),e.jsxs("p",{id:"research-query-count",className:"mt-2 text-sm text-secondary",children:[H," / ",Cr," queries",c==="once"?"":` across ${K.length} destinations`]})]}),c!=="once"&&e.jsxs("details",{className:"border-t border-default pt-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading focus-visible:outline focus-visible:outline-2",children:["Saved patterns ",e.jsx("span",{className:"font-normal text-secondary",children:"(optional)"})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries."}),He.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:He.map(R=>e.jsx(P,{size:"sm",variant:"outline",onClick:()=>dt(R),children:R.label},R.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),C&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",C.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(P,{size:"sm",variant:"outline",onClick:()=>ne(!z),children:z?"Cancel save":"Save as a pattern"}),z&&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:Ps,value:F,maxLength:120,onChange:R=>_(R.target.value)})]}),e.jsx(P,{size:"sm",disabled:ht.isPending||!F.trim()||!ie.trim(),onClick:kt,children:ht.isPending?"Saving…":"Save pattern"})]})]}),Z&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:Z})]})]}),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:Ps,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:Ps,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:Ps,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))})]})]})]}),Mt.length>0&&e.jsx(af,{errors:Mt}),c!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:Je,children:[e.jsx(va,{size:14}),V?_t.refreshPreview:"Preview queries"]}),V&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Queries to run"}),e.jsxs("p",{className:"text-sm text-secondary",children:[Ge.length," query executions in ",et.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(nf,{rows:Ge,locations:n,onChange:(R,$e)=>G(Te=>Te&&{...Te,rows:Te.rows.map(Ue=>Ue.id===R?{...Ue,...$e}:Ue)})})]})]}),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(P,{size:"sm",disabled:!jt,onClick:()=>{if(jt){const R=ze();t.onSubmit(R,JSON.stringify({projectName:s,...R}))}},children:[e.jsx(cr,{size:14}),t.isPending?"Starting…":_t.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[c==="once"?`${we.length} queries`:`${Ge.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:Ps,value:s,onChange:r=>a(r.target.value),children:[e.jsx("option",{value:En,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function nf({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:`${Ps} 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??En,locations:s,onChange:l=>n(a.id,{location:s.find(i=>i.label===l)??null})})]},a.id))})}function af({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 rf(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 of({detail:t,isLoading:s,onReviewForTracking:n}){const[a,r]=o.useState(null);o.useEffect(()=>{r(t?.queries[0]?.id??null)},[t?.id]);const l=t?.queries.find(i=>i.id===a)??t?.queries[0]??null;return e.jsxs(ve,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":_t.resultsTitle,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Results"}),e.jsx("h3",{children:t?`Research run ${df(t.id)}`:_t.resultsEmpty})]}),t&&e.jsx(je,{tone:Kc(t.status),children:t.status})]}),t&&e.jsxs("div",{className:"mt-3 space-y-3 text-sm text-secondary",children:[e.jsxs("dl",{className:"flex flex-wrap gap-x-6 gap-y-2 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Answer engine"}),e.jsx("dd",{children:t.provider})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Requested model"}),e.jsx("dd",{className:"font-mono",children:t.requestedModel??t.resolvedModel})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Location"}),e.jsx("dd",{children:t.location?.label??"No location"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Destination"}),e.jsx("dd",{children:t.scope?.label??"Whole site"})]})]}),t.template&&e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:_t.templateProvenance}),e.jsxs("dl",{className:"mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Saved pattern"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.template})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Names used"}),e.jsx("dd",{children:Object.entries(t.template.bindings).map(([i,c])=>`${i}: ${c}`).join(" · ")||"No variables"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Original resolved text"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.output})]})]}),e.jsx("p",{className:"mt-2",children:"The queries below are the final text sent to the answer engine, including any edits."}),e.jsxs("p",{className:"mt-2 font-mono text-xs",children:[t.template.templateId," · ",t.template.templateVersion]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:_t.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:_t.methodology})]})]}),t?e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Class"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Brand-name match"}),e.jsx("th",{children:"Project domain cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:l?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>r(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(je,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?_t.brandedQuery:i.queryClass==="non-brand"?_t.discoveryQuery:_t.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(je,{tone:uf(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(je,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===vn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===vn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(je,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===vn.failed?"negative":"caution",children:i.citationState===null?i.status===vn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(lf,{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 lf({query:t,isLoading:s,scope:n,onReviewForTracking:a}){return t?e.jsxs("div",{className:"min-w-0 space-y-4 border-t border-default pt-4 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),!le()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(Ye,{type:"button",size:"sm",onClick:()=>a({researchRunQueryId:t.id,scope:n}),children:"Review for tracking"}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Only this saved query text enters tracking review. Its answer remains research evidence."})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("div",{className:"mt-1",children:e.jsx(Ti,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===vn.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r},r))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r.replace(/^www\./,"")},r))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-3",children:t.groundingSources.map((r,l)=>e.jsx("li",{className:"min-w-0",children:e.jsx(ki,{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 cf(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 df(t){return t.length>8?t.slice(0,8):t}function Kc(t){return t===pa.completed?"positive":t===pa.partial?"caution":t===pa.failed?"negative":"neutral"}function uf(t){return t===vn.completed?"positive":t===vn.failed?"negative":"neutral"}async function mf(t){await Et(t,"researchRuns")}const yi=new Set(["queued","seeding","probing"]);function hf({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:l={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d}){const{account:m}=rn(),[u,p]=o.useState("tracked"),[x,h]=o.useState("find"),[y,f]=o.useState(null),b=m?.role==="viewer"?Wl():null,N=dc(m?.role,b),$=uc(s??u,N),S=a??x,g=I=>{s===void 0&&p(I),n?.(I)},v=I=>{a===void 0&&h(I),r?.(I)},C=(I,A)=>{const w=A===void 0?{...l}:{...l,measurementScope:A?.kind??"project",measurementScopeKey:A?.key};f({...I,trackingSelection:w}),A!==void 0&&i?.({measurementScope:w.measurementScope,measurementScopeKey:w.measurementScopeKey}),g("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(xr,{active:$==="tracked",label:"Tracked",onClick:()=>g("tracked")}),N?e.jsx(xr,{active:$==="research",label:"Research",onClick:()=>g("research")}):null]}),e.jsx("div",{className:"mt-4",children:$==="tracked"?e.jsx($f,{projectName:t,selection:l,onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d,pendingTrackingSource:y,onPendingTrackingSourceHandled:()=>f(null)}):e.jsx(pf,{projectName:t,selection:l,mode:S,onModeChange:v,onReviewSavedSource:C,onSelectionChange:i,viewerResearchConfig:b})})]})}function xr({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 pf({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:l}){const{canWrite:i}=rn(),c=!i||n==="test",d=Le({...Ii({client:Y,path:{name:t}}),enabled:c,staleTime:6e4}),m=Le({...Yl({client:Y,path:{name:t}}),enabled:c,staleTime:6e4}),u=o.useMemo(()=>{const h=d.data;if(!h)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const y=new Map(h.targets.map(b=>[b.stableKey,[]]));for(const b of h.groups)for(const N of b.targetKeys)y.get(N)?.push(b.stableKey);const f=new Map(h.markets.map(b=>[b.stableKey,new Set]));for(const b of h.markets)for(const N of b.usageEdges)for(const k of y.get(N.targetKey)??[])f.get(b.stableKey)?.add(k);return[{id:"project",label:"Whole site",kind:"project",targetCount:h.targets.length},...h.groups.map(b=>({id:b.stableKey,label:b.label,kind:"group",targetCount:b.targetKeys.length,...b.parentGroupKey?{parentGroupIds:[b.parentGroupKey]}:{}})),...h.markets.map(b=>{const N=[...f.get(b.stableKey)??[]];return{id:b.stableKey,label:b.label,kind:"market",targetCount:0,...N.length?{parentGroupIds:N}:{}}}),...h.targets.map(b=>({id:b.stableKey,label:b.label,kind:"property",targetCount:1,...y.get(b.stableKey)?.length?{parentGroupIds:y.get(b.stableKey)}:{}}))]},[d.data]),p=o.useMemo(()=>(m.data?.templates??[]).map(h=>({id:h.id,version:h.updatedAt,label:h.name,pattern:h.pattern,variables:h.variables})),[m.data]),x={projectName:t,scopeOptions:u,planRevision:d.data?.active?.revision??null,selectedScope:(()=>{const h=u.find(f=>f.kind===s.measurementScope&&f.id===s.measurementScopeKey),y=d.data?.active?.revision;return h&&y&&(h.kind==="market"||h.kind==="property")?{kind:h.kind,key:h.id,label:h.label,planRevision:y,expectedPlanRevision:y}:(s.measurementScope==="market"||s.measurementScope==="property")&&s.measurementScopeKey?{kind:s.measurementScope,key:s.measurementScopeKey,label:s.measurementScopeKey,planRevision:y??0,expectedPlanRevision:y??0}:null})(),scopePending:d.isPending||d.isFetching,scopeError:d.isError,onRetryScope:()=>{d.refetch()},templates:p};return i?e.jsxs("div",{children:[e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(xr,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(xr,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(Lf,{projectName:t,onReviewDiscoveryProbe:h=>r({source:"discovery",discoveryProbeId:h})}):e.jsx(tl,{...x,onReviewForTracking:({researchRunQueryId:h,scope:y})=>r({source:"research",researchRunQueryId:h},y??null)})})]}):e.jsx(tl,{...x,viewerResearchConfig:l})}function xf({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:c,preview:d,isPreviewing:m,isCommitting:u,onPreview:p,onCommit:x}){const[h,y]=o.useState(null),[f,b]=o.useState(()=>ir(s)),[N,k]=o.useState(null),$=o.useRef(null),S=o.useRef(null),g=mc(t,s),v=o.useMemo(()=>bf(t.tracked,s,t.mode),[s,t.mode,t.tracked]),C=jn({rows:v,getSearchText:z=>`${z.queryText} ${z.provenance?.source??"legacy"} ${z.assignments.map(ne=>ne.queryClass??"unknown").join(" ")}`});o.useEffect(()=>{if(g)return;if(!a){S.current=null;return}const z=`${a}:${_r(s)}`;if(S.current===z)return;const ne=t.tracked.find(F=>F.queryId===a);ne&&(S.current=z,y({kind:"edit",row:ne,audience:t.mode==="advanced"?Gr(s):void 0,scopeLabel:Kr(s,t)}),b(sl(ne,s)),k(null))},[s,a,g,t]),o.useEffect(()=>{if(g||!l)return;const z=ir(l.trackingSelection??s);y({kind:"add"}),b(l.source==="research"?{...z,source:"research",researchRunQueryId:l.researchRunQueryId}:{...z,source:"discovery",discoveryProbeId:l.discoveryProbeId}),k(null),i()},[i,l,s,g]),o.useEffect(()=>{g&&(y(null),k(null),a!==void 0&&r?.(void 0))},[r,a,g]),o.useEffect(()=>{if(!h||h.kind==="remove")return;const z=$.current;z&&(z.scrollIntoView?.({block:"start"}),z.focus({preventScroll:!0}))},[h]);function I(z="manual"){y({kind:"add"}),b({...ir(s),source:z}),k(null),r?.(void 0)}function A(z){S.current=`${z.queryId}:${_r(s)}`,y({kind:"edit",row:z,audience:t.mode==="advanced"?Gr(s):void 0,scopeLabel:Kr(s,t)}),b(sl(z,s)),k(null),r?.(z.queryId)}function w(z){S.current=`${z.queryId}:${_r(s)}`,y({kind:"remove",row:z,audience:t.mode==="advanced"?Gr(s):void 0,scopeLabel:Kr(s,t)}),k(null),r?.(z.queryId)}function V(){y(null),k(null),r?.(void 0)}const G=h?gf(h,f,t.mode):null,Q=h!==null&&h.kind==="add"&&t.mode==="advanced"&&!Gi(f),B=G!==null&&(!Q||f.contexts.length>0)&&!m;return g?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(P,{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(vf,{selection:s,onSelectionChange:n}):null,e.jsx(Zs,{value:C.query,onChange:C.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!le()&&e.jsxs(Ye,{type:"button",size:"sm",onClick:()=>I(),children:[e.jsx(ep,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[C.totalRows.toLocaleString("en-US")," saved query ",C.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."}),C.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:C.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:C.rows.map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:z.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(Nf,{row:z,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Sf,{row:z})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:jf(z)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Cf,{row:z,outsidePlan:t.mode==="advanced"&&z.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!le()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${z.queryText}`,onClick:()=>A(z),children:[e.jsx(tp,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${z.queryText}`,onClick:()=>w(z),children:[e.jsx(cc,{"aria-hidden":"true",size:13})," Remove"]})]})})]},z.queryId))})]})}),e.jsx(Os,{page:C.page,pageSize:C.pageSize,visibleRows:C.rows.length,totalRows:C.totalRows,itemLabel:"queries",onPageChange:C.setPage})]}),h&&!le()&&e.jsx(kf,{workspace:t,templates:c,action:h,draft:f,onDraftChange:z=>{b(z),k(null)},onClose:V,canReview:B,isPreviewing:m,editorHeadingRef:$,onReview:()=>{G&&(k(G),p(G))}}),d&&N&&h&&e.jsx(If,{preview:d,workspace:t,isCommitting:u,onConfirm:()=>{x({...N,expectedWorkspaceVersion:d.workspaceVersion,previewToken:d.previewToken,reviewedAt:d.reviewedAt})}})]})}function ir(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 sl(t,s){return{...ir(s),text:t.queryText,queryClass:"keep"}}function gf(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=ff(s);if(!a||bi(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=yf(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!Gi(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function ff(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 yf(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 Gi(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function bi(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function Gr(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 Kr(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 Ki(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 bf(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=>Ki(r,s)))}function vf({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 _r(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function jf(t){switch(t.provenance?.source){case"manual":return"Manual";case"template":return"Template";case"research":return"Saved research";case"discovery":return"Discovery";default:return"Legacy"}}function _c(t,s,n){const a=new Map(s.targets.map(f=>[f.stableKey,f.label])),r=new Map(s.groups.map(f=>[f.stableKey,f.label])),l=new Map(s.markets.map(f=>[f.stableKey,f.label])),i=new Set(t.assignments.map(f=>f.targetKey));if(i.size===0)return"Whole site";const c=n?t.assignments.filter(f=>Ki(f,n)):t.assignments,d=new Set(c.map(f=>f.targetKey));if(n?.measurementScope==="group"){const f=d.size,b=Math.max(0,i.size-f);return[`${f} ${f===1?"property":"properties"} in this group`,...b?[`Shared with ${b} other ${b===1?"property":"properties"}`]:[]].join(" · ")}const m=new Set,u=new Set;for(const f of c)f.groupKeys.forEach(b=>m.add(b)),f.marketKeys.forEach(b=>u.add(b));const x=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`],h=m.size===1?r.get([...m][0])??[...m][0]:null,y=u.size===1?l.get([...u][0])??[...u][0]:null;return h&&y&&h===y?x.push(`${h} (group and market)`):(h?x.push(`Group: ${h}`):m.size>1&&x.push(`${m.size} groups`),y?x.push(`Market: ${y}`):u.size>1&&x.push(`${u.size} markets`)),x.join(" · ")}function Nf({row:t,workspace:s,selection:n}){const a=wf(t,s,n);return e.jsxs("details",{className:"group min-w-48",children:[e.jsx("summary",{className:"cursor-pointer rounded px-1 py-1 text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:_c(t,s,n)}),e.jsxs("div",{className:"mt-2 rounded border border-default bg-surface p-2 text-xs leading-5 text-secondary",children:[e.jsx("p",{className:"font-medium text-strong",children:"Assigned relationships"}),e.jsx("ul",{className:"mt-1 list-disc space-y-1 pl-4",children:a.map(r=>e.jsx("li",{children:r},r))})]})]})}function wf(t,s,n){const a=new Map(s.targets.map(d=>[d.stableKey,d.label])),r=new Map(s.groups.map(d=>[d.stableKey,d.label])),l=new Map(s.markets.map(d=>[d.stableKey,d.label])),c=t.assignments.filter(d=>Ki(d,n)).map(d=>{const m=a.get(d.targetKey)??d.targetKey??"Whole site",u=n.measurementScope==="group"&&n.measurementScopeKey?d.groupKeys.filter(x=>x===n.measurementScopeKey).map(x=>r.get(x)??x):d.groupKeys.map(x=>r.get(x)??x),p=n.measurementScope==="market"&&n.measurementScopeKey?d.marketKeys.filter(x=>x===n.measurementScopeKey).map(x=>l.get(x)??x):d.marketKeys.map(x=>l.get(x)??x);return[m,u.length?`Groups: ${u.join(", ")}`:null,p.length?`Markets: ${p.join(", ")}`:null].filter(x=>x!==null).join(" · ")});return[...new Set(c)].length?[...new Set(c)]:["Whole site"]}function Sf({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(je,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function Cf({row:t,outsidePlan:s=!1}){return s?e.jsx(je,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(je,{tone:"positive",children:"Measured"}):e.jsx(je,{tone:"caution",children:"Awaiting sweep"})}function kf({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:l,canReview:i,isPreviewing:c,editorHeadingRef:d,onReview:m}){const u=s.length>0;return n.kind==="remove"?e.jsxs(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(Ur,{canReview:i,isPreviewing:c,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(P,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("p",{className:"mt-3 text-sm leading-6 text-secondary",children:[n.audience?`Changes apply only to assignments in ${n.scopeLabel}.`:"Changes apply to every assignment of this query."," Earlier results stay unchanged."]}),e.jsxs("div",{className:"mt-4 max-w-2xl space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Query text"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.text,onChange:p=>r({...a,text:p.target.value})})]}),t.mode==="advanced"&&e.jsxs("label",{className:"block",htmlFor:"tracking-query-class",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:p=>r({...a,queryClass:p.target.value}),children:[e.jsx("option",{value:"keep",children:"Keep existing classifications"}),e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Existing locations and engines are preserved. Use Add query to create assignments in another scope."})]}),e.jsx(Ur,{canReview:i,isPreviewing:c,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(P,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-[minmax(250px,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[a.source==="manual"?e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Question"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",placeholder:"e.g. How do teams compare AEO platforms?",value:a.text,onChange:p=>r({...a,text:p.target.value})})]}):null,a.source==="template"?e.jsx(Af,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(nl,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(p=>({id:p.researchRunQueryId,label:p.queryText,detail:p.researchRunId})),onChange:p=>r({...a,researchRunQueryId:p})}):null,a.source==="discovery"?e.jsx(nl,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(p=>({id:p.discoveryProbeId,label:p.queryText,detail:p.discoverySessionId})),onChange:p=>r({...a,discoveryProbeId:p})}):null,e.jsxs("label",{className:"block",htmlFor:"tracking-query-source",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Query source"}),e.jsxs("select",{id:"tracking-query-source","aria-describedby":u?void 0:"tracking-query-source-no-templates",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.source,onChange:p=>r({...a,source:p.target.value}),children:[e.jsx("option",{value:"manual",children:"Write a question"}),u?e.jsx("option",{value:"template",children:"Saved template"}):null,e.jsxs("option",{value:"research",disabled:t.savedSources.research.length===0,children:["Saved research",t.savedSources.research.length===0?" (none available)":""]}),e.jsxs("option",{value:"discovery",disabled:t.savedSources.discovery.length===0,children:["Discovery result",t.savedSources.discovery.length===0?" (none available)":""]})]})]}),u?null:e.jsx("p",{id:"tracking-query-source-no-templates",className:"text-sm leading-6 text-secondary",children:"No saved templates are set up for this portfolio. Write a question, or use saved research or a discovery result."})]}),e.jsx(Pf,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!Gi(a)?e.jsx("div",{className:"mt-4",children:e.jsx(Rf,{workspace:t,draft:a,onDraftChange:r})}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Measurement options"}),e.jsx("div",{className:"grid gap-4 pb-3 sm:grid-cols-2",children:t.mode==="advanced"?e.jsxs("div",{className:"block",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",htmlFor:"tracking-query-class",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:p=>r({...a,queryClass:p.target.value}),children:[e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}):e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:"Automatic"})]})})]}),a.source==="research"&&e.jsx("p",{className:"mt-4 rounded-md border border-default bg-surface-subtle px-3 py-2 text-sm text-secondary",children:"Only the saved query is added."}),e.jsx(Ur,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]})}function Af({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":bi(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]}),bi(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 nl({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 _i(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function ua(t){return JSON.stringify({providers:[...t.providers].sort(),models:Object.fromEntries(Object.entries(t.models).sort(([s],[n])=>s.localeCompare(n))),location:t.location})}function Uc(t){return[...new Map(t.map(s=>[ua(s),s])).values()]}function Ui(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 Rf({workspace:t,draft:s,onDraftChange:n}){const a=o.useMemo(()=>Uc([...t.defaultContexts.map(_i),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?ua(s.contexts[0]):s.contexts.length>1?"__existing__":"";return e.jsxs("label",{className:"block",htmlFor:"tracking-query-context",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location and engines"}),e.jsxs("select",{id:"tracking-query-context","aria-label":"Location and engines",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:r,onChange:l=>{const i=a.find(d=>ua(d)===l.target.value),c=l.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:c})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(l=>e.jsx("option",{value:ua(l),children:Ui(l)},ua(l)))]}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-secondary",children:a.length===0?"No configured measurement context is available.":"Choose where this query will be measured."})]})}function Pf({workspace:t,draft:s,onDraftChange:n}){const[a,r]=o.useState(""),[l,i]=o.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),c=o.useMemo(()=>[...t.targets.map(h=>({kind:"target",key:h.stableKey,label:h.label,detail:"Property"})),...t.groups.map(h=>({kind:"group",key:h.stableKey,label:h.label,detail:"Group"})),...t.markets.map(h=>({kind:"market",key:h.stableKey,label:h.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),d=a.trim().toLocaleLowerCase(),m=d?c.filter(h=>`${h.label} ${h.detail}`.toLocaleLowerCase().includes(d)):c,u=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function p(h,y,f){const b=h==="target"?"targetKeys":h==="group"?"groupKeys":"marketKeys",N=s[b];n({...s,wholeSite:!1,[b]:f?[...N,y]:N.filter(k=>k!==y)})}function x(h,y){return(h==="target"?s.targetKeys:h==="group"?s.groupKeys:s.marketKeys).includes(y)}if(!l){const h=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: ",h?.label??s.targetKeys[0]]}),e.jsx(P,{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:h=>{n({...s,wholeSite:h.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(Zs,{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(h=>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":`${h.label}, ${h.detail}`,checked:x(h.kind,h.key),onChange:y=>p(h.kind,h.key,y.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:h.label}),e.jsx("span",{className:"text-xs text-muted",children:h.detail})]},`${h.kind}:${h.key}`))})]})}function Ur({canReview:t,isPreviewing:s,onCancel:n,onReview:a}){return e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[e.jsx(Ye,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(P,{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 If({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=o.useRef(null);o.useEffect(()=>{const c=r.current;c&&(typeof c.scrollIntoView=="function"&&c.scrollIntoView({block:"start"}),c.focus({preventScroll:!0}))},[t]);const l=!t.diff.noOp,i=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(c=>c.rows.length>0);return e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{ref:r,tabIndex:-1,children:l?"Confirm tracked query changes":"No tracking changes"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:l?"Changes apply to future sweeps. Earlier results stay unchanged.":"This request leaves tracking unchanged."})]}),e.jsx(je,{tone:l?"caution":"neutral",children:l?"Ready to confirm":"No-op"})]}),i.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:i.map(c=>e.jsx(al,{label:c.label,rows:c.rows,workspace:s,tracked:t.tracked},c.label))}):null,t.diff.unchanged.length>0?e.jsxs("details",{className:"mt-4 border-t border-default pt-2 text-sm text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3",children:[t.diff.unchanged.length," unchanged ",t.diff.unchanged.length===1?"query":"queries"]}),e.jsx(al,{label:"Unchanged",rows:t.diff.unchanged,workspace:s,tracked:t.tracked})]}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Next sweep workload"}),e.jsxs("p",{className:"leading-6",children:["Next sweep: ",t.workload.nextSweepProviderCalls," provider requests (+",t.workload.addedProviderCalls,", −",t.workload.removedProviderCalls,")."]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:e.jsx(Ye,{type:"button",size:"sm",disabled:!l||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function al({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`:Mf(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(Tf,{row:a.find(l=>l.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function Tf({row:t,workspace:s}){if(!t?.assignments.length)return null;const n=new Set(t.assignments.map(a=>a.targetKey)).size;return e.jsxs("details",{className:"mt-2 text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:["Classifications · ",n," ",n===1?"property":"properties"]}),e.jsx("ul",{className:"mt-1 max-h-40 space-y-1 overflow-y-auto",children:t.assignments.map((a,r)=>{const l=s.targets.find(d=>d.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",c=a.contexts.map(d=>Ui(_i(d))).join("; ");return e.jsx("li",{children:[l,i,c].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function Mf(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=Uc(a.assignments.flatMap(i=>i.contexts).map(_i)),l=r.length===1?Ui(r[0]):r.length>1?`${r.length} contexts`:null;return[_c(a,n),l].filter(i=>i!==null).join(" · ")}function $f({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i}){const c=hs(),[d,m]=o.useState(null),u=Le({...Ii({client:Y,path:{name:t}})}),p=Le({...Yl({client:Y,path:{name:t}}),staleTime:6e4}),x=Dt({...ju(),onSuccess:y=>m(y),onError:async y=>{m(null),await c.invalidateQueries({queryKey:vu({client:Y,path:{name:t}})}),De({title:"Could not review tracking changes",detail:y instanceof Error?y.message:"Update the draft and review it again.",tone:"negative"})}}),h=Dt({...Nu(),onSuccess:async y=>{m(null),r?.(void 0),await io(c,t),De({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 io(c,t),De({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(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{u.refetch()},children:"Try again"})]}):e.jsx(xf,{workspace:u.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:p.data?.templates??[],preview:d,isPreviewing:x.isPending,isCommitting:h.isPending,onPreview:y=>{m(null),x.mutate({client:Y,path:{name:t},body:{...y,expectedWorkspaceVersion:u.data.workspaceVersion}})},onCommit:y=>h.mutate({client:Y,path:{name:t},body:y})})}function Lf({projectName:t,onReviewDiscoveryProbe:s}){const n=hs(),[a,r]=o.useState(null),[l,i]=o.useState(""),[c,d]=o.useState("100"),m=Le({...wu({client:Y,path:{name:t},query:{limit:"10"}}),refetchInterval:k=>k.state.data?.some(S=>yi.has(S.status))?3e3:!1}),u=m.data??[];o.useEffect(()=>{!a&&u[0]&&r(u[0].id)},[a,u]);const p=u.find(k=>k.id===a)??null,x=Le({...Su({client:Y,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:p&&yi.has(p.status)?3e3:!1}),h=x.data??null,y=Dt({mutationFn:()=>{const k={},$=l.trim();$&&(k.icpDescription=$);const S=Number.parseInt(c,10);return Number.isFinite(S)&&S>0&&(k.maxProbes=S),Cu(t,k)},onSuccess:async k=>{r(k.sessionId),i(""),await Of(n,t,k.sessionId),De({title:"Discovery started",detail:`Run ${Br(k.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${k.sessionId}`,dedupeMode:"replace"})},onError:k=>{De({title:"Discovery failed to start",detail:k instanceof Error?k.message:"Could not start discovery.",tone:"negative"})}}),f=h??p,b=o.useMemo(()=>(h?.probes??[]).slice(0,30),[h?.probes]);async function N(){try{const k=await m.refetch();if(k.error)throw k.error;const $=k.data?.length??0;De({title:"Discovery sessions refreshed",detail:`${$} recent session${$===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(k){De({title:"Discovery refresh failed",detail:k instanceof Error?k.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:le()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{N()},children:[e.jsx(va,{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(je,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:l,onChange:k=>i(k.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:c,onChange:k=>d(k.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!le()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:y.isPending,onClick:()=>y.mutate(),children:[e.jsx(cr,{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(je,{tone:"neutral",children:"Loading"})]}),u.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:u.map(k=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===k.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(k.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:Br(k.id)}),e.jsx(je,{tone:rl(k.status),children:k.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",k.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",k.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",k.wastedCount??0]})]})]},k.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:f?Br(f.id):"No run selected"})]}),f&&e.jsx(je,{tone:rl(f.status),children:f.status})]}),f?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(za,{label:"Questions tested",value:f.probeCount??0}),e.jsx(za,{label:"Cited queries",value:f.citedCount??0,tone:"positive"}),e.jsx(za,{label:"Worth tracking",value:f.aspirationalCount??0,tone:"caution"}),e.jsx(za,{label:"Skip",value:f.wastedCount??0,tone:"negative"})]}),f.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:f.error}),f.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:f.warning}),f.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:f.icpDescription})]}),f.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:f.competitorMap.slice(0,8).map(k=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[k.domain," ",e.jsx("span",{className:"text-muted",children:k.hits})]},k.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),f?.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"})]}),x.isFetching&&e.jsx(je,{tone:"neutral",children:"Loading"})]}),b.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Tracking review"})})]})}),e.jsx("tbody",{children:b.map(k=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:k.query}),e.jsx("td",{children:e.jsx(je,{tone:qf(k.bucket),children:Df(k.bucket)})}),e.jsx("td",{className:"text-secondary",children:k.citedDomains.length>0?k.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!le()&&s&&(k.bucket==="cited"||k.bucket==="aspirational")&&e.jsx(Ye,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(k.id),children:"Review for tracking"})})]},k.id))})]})})]})]})]})]})}function za({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 rl(t){return t==="completed"?"positive":t==="failed"?"negative":yi.has(t)?"caution":"neutral"}function qf(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Ef={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Df(t){return t?Ef[t]:"Not classified"}function Br(t){return t.length>8?t.slice(0,8):t}async function Of(t,s,n){await Promise.all([Et(t,"discovery"),t.invalidateQueries({queryKey:ku({client:Y})})])}function Ff({projectName:t}){const[s,n]=o.useState("changes"),[a,r]=o.useState(null),[l,i]=o.useState(null),c=Le({...Au({client:Y,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=Le({...Ru({client:Y,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),m=(d.data??[]).filter(b=>(b.status==="completed"||b.status==="partial")&&b.trigger!=="probe").reverse(),u=l??m[0]?.id??"",p=a??m.find(b=>b.id!==u)?.id??"",x=!!(p&&u&&p!==u),h=Le({...Pu({client:Y,path:{name:t},query:{run1:p,run2:u}}),enabled:s==="compare"&&x}),y=c.data??[],f=h.data?.diff.filter(b=>b.changed||b.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([b,N])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===b,className:`filter-chip ${s===b?"filter-chip-active":""}`,onClick:()=>n(b),children:N},b))}),s==="changes"?e.jsx(lp,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),c.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!c.isLoading&&y.length===0?e.jsxs(ve,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:cs()?Un:"Complete an answer visibility sweep to create the first snapshot."})]}):null,y.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:y.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(b.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.mentionedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Ze(b.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.citedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Ze(b.overallCitedRate)})]},b.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:p,onChange:b=>r(b.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:m.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:u,onChange:b=>i(b.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:m.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]})]}),d.isLoading||h.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:cs()?Un:"Run another answer visibility sweep before comparing historical evidence."})]}):null,h.data&&f.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,f.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:f.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:b.query??"Archived query"}),e.jsx("td",{children:e.jsxs(je,{tone:b.changed?"caution":"neutral",children:[b.run1State??"none"," → ",b.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(je,{tone:b.visibilityChanged?"caution":"neutral",children:[b.run1MentionState??"none"," → ",b.run2MentionState??"none"]})})]},b.queryId??b.query??"unknown"))})]})}):null]}):null]})}const il={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},Gf={contract:null,assessment:null,googleAds:il,gtm:il,snapshots:[]};function Kf(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Vf(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function _f(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 Uf(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 Bf(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 Bc(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"&&zf(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 Vf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function zf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Vc(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 Qf(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 Hf(t,s){return t==="configured"?s==="not-configured"?"Not declared":s==="contract-selection-required"?"Choose conversion":"Declared":t==="static"?s==="assessment-unavailable"?"Unavailable":s==="assessment-loading"?"Checking":s==="static-mismatch"?"Mismatch":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"Consistent":s==="configured"?"Needs review":"Not checked":s==="observed"?"Observed":s==="runtime-unverified"?"Not observed":"Not checked"}function hn(t){return t.length<=12?t:`…${t.slice(-10)}`}function Wf(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 Yf(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 Vr={"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 ol(t){return t.outcome==="pass"?{label:Vr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Vr[t.code],tone:"negative",outcome:"Fail"}:{label:Vr[t.code],tone:"caution",outcome:"Unknown"}}function Jf(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Xf(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 Zf(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function ll({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const l=Vc(s.state),i=s.snapshotState==="loading"?"Loading stored snapshots":s.snapshotState==="unavailable"?"Stored snapshots unavailable":s.snapshotCount===0?"No stored snapshots":null;return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:t}),e.jsx("td",{children:e.jsx(je,{tone:l.tone,children:l.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),i?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:i}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Wt(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const ey="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.",ty="Available once Google Ads and Tag Manager are connected.",sy="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 ny({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:l}){const i=t.googleAds.state==="connected",c=t.gtm.state==="connected",d=t.googleAds.state==="unavailable",m=t.gtm.state==="unavailable",u=d||m||t.gtm.state==="unavailable",p={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},x=!i&&!c,h=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:d?p:Uf(t)},{title:"Tag Manager",state:t.gtm.state,ready:c,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:m?p:Bf(t)}],y=i&&c&&!u?Bc(t):null;return e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("h2",{id:"conversion-integrity-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx(Fe,{text:"Canonry reads your Google configuration and never changes or publishes it. Connect Google Ads and Tag Manager, then choose one website conversion to check across both."})]}),x?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:sy}):null]})}),e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-y border-default py-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Conversion to check"}),e.jsx(Fe,{text:ey})]}),y&&s?e.jsx(Ye,{type:"button",disabled:r,onClick:()=>s(y.id),children:r?"Working…":y.label}):e.jsx("p",{className:"text-sm text-secondary",children:ty})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:h.map(f=>{const b=f.ready?{label:"Ready",tone:"positive"}:Vc(f.state),N=f.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:f.title}),e.jsx(je,{tone:b.tone,children:b.label}),f.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:f.summary}):null,N&&s?N.id==="retry-connection-status"?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(N.id),children:r?"Working…":N.label}):e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(N.id),children:r?"Working…":N.label}):null,f.summary&&f.onChange?e.jsx(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":f.changeLabel,disabled:r,onClick:f.onChange,children:"Change"}):null]},f.title)})}),l?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:l}):null]})]})}function ay({workspace:t=Gf,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:l=null,onSelectContract:i,contractError:c=null,onRetryContracts:d,onRetryEvidence:m,onChangeGoogleAdsSelection:u,onChangeGtmSelection:p,onAddContract:x}){const h=Kf(t),y=_f(h),f=Bc(t),b=t.assessment?.findings??[],N=b.filter(g=>g.outcome!=="pass"),k=b.filter(g=>g.outcome==="pass"),$=N.some(g=>g.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&c===null?e.jsx(ny,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:u,onChangeGtmSelection:p,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(je,{tone:y.tone,children:y.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Wt(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(g=>e.jsxs("li",{className:"break-words",children:[Zf(g)," ",g.kind,", captured ",Wt(g.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",g.id,")"]})]},g.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?f.id==="review-findings"||f.id==="review-runtime-verification"||f.id==="retry-connection-status"||f.id==="select-contract"||f.id==="retry-integrity"||f.id==="waiting-for-integrity"?e.jsx(P,{type:"button",disabled:n||f.id==="waiting-for-integrity",onClick:()=>s(f.id),children:n?"Working…":f.label}):e.jsx(Ye,{type:"button",disabled:n,onClick:()=>s(f.id),children:n?"Working…":f.label}):f.id==="review-findings"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):h==="runtime-unverified"?e.jsx(P,{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:f.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&&x?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:x,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:g=>i?.(g.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(g=>e.jsx("option",{value:g.id,children:g.name},g.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:Wf(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:Yf(t.contract)})]})]}),e.jsxs("details",{className:"inline-disclosure mt-5",children:[e.jsx("summary",{children:"Show declared identifiers"}),e.jsxs("dl",{className:"mt-3 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads customer"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:hn(t.contract.googleAds.customerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads conversion action"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:hn(t.contract.googleAds.conversionActionId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager container"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:hn(t.contract.gtm.containerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager tag"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:hn(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),c?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:c}),d?e.jsx(P,{type:"button",variant:"outline",onClick:d,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),N.length>0?e.jsxs("section",{id:"conversion-integrity-findings",tabIndex:-1,className:"page-section-divider","aria-labelledby":"conversion-integrity-findings-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Assessment findings"}),e.jsx("h3",{id:"conversion-integrity-findings-title",className:"text-base font-semibold text-heading",children:"Checks to review"})]}),e.jsxs(je,{tone:$,children:[N.length," ",N.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:N.map(g=>{const v=ol(g);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:v.label}),e.jsx(je,{tone:v.tone,children:v.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",g.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",g.code]}),g.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",g.evidenceIds.join(", ")]}):null]},`${g.code}:${g.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(Fe,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(g=>{const v=Qf(g.key,h);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${v==="positive"?"bg-positive-fill":v==="caution"?"bg-caution-fill":v==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:g.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:g.detail}),e.jsx(je,{tone:v,children:Hf(g.key,h)})]},g.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:[ll({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:u}:{},actionPending:n}),ll({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:p}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&m?e.jsx(P,{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(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:g.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:g.kind}),e.jsx("td",{className:"text-secondary",children:Wt(g.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:hn(g.id)})]},g.id))})]})})]}):null,k.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[k.length," ",k.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:k.map(g=>{const v=ol(g);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:v.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",g.code]}),g.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",g.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(je,{tone:v.tone,children:v.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:g.subject})]},`${g.code}:${g.subject}`)})})]})})]}):null,h==="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 ",Jf(t.contract)," and complete the conversion that emits ",e.jsx("span",{className:"font-mono text-heading",children:t.contract.eventName}),"."]}),e.jsxs("li",{children:["In Tag Manager preview or debugging, confirm tag ",e.jsx("span",{className:"font-mono text-heading",children:hn(t.contract.gtm.tagId)})," fires with ",Xf(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:hn(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const pn=3e4,cl={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Kt="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",os="text-sm font-medium text-secondary";function dl(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:Ct(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function Qa(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function ry(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 iy(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function oy(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:iy(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 ly(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:Qa(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:Qa(t.triggerIds),variableIds:Qa(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:Qa(t.productionHosts)}}}function ul(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 Ha(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 Wa(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Ya({id:t,label:s,value:n,onChange:a,children:r,disabled:l=!1}){return e.jsxs("label",{htmlFor:t,className:os,children:[s,e.jsx("select",{id:t,className:Kt,value:n,onChange:i=>a(i.target.value),disabled:l,children:r})]})}function Mn({id:t,checked:s,onChange:n,children:a}){return e.jsxs("label",{htmlFor:t,className:"flex items-start gap-2 text-sm text-secondary",children:[e.jsx("input",{id:t,type:"checkbox",checked:s,onChange:r=>n(r.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function ml({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1),[c,d]=o.useState(null),m=o.useRef(null),u=o.useRef(null),p=o.useRef(!1);o.useEffect(()=>{const f=p.current;p.current=a,a?u.current?.focus():f&&m.current?.querySelector("button")?.focus()},[a]);function x(){d(null),r(!0)}function h(){d(null),r(!1)}async function y(){i(!0),d(null);try{await n()}catch(f){d(Ct(f)),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(P,{ref:u,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:l,onClick:h,children:"Keep connected"}),e.jsx(Ye,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||l,onClick:()=>{y()},children:l?"Disconnecting…":`Disconnect ${t}`})]}),c?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:c}):null]}):e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:x,children:["Disconnect ",t]})})}function hl({id:t,label:s,options:n,synced:a,loading:r,failed:l,onRetry:i,emptyHint:c,value:d,onChange:m}){const u=n.some(f=>f.id===d),[p,x]=o.useState(!1),h=p||d!==""&&!u&&n.length>0,y=e.jsx("label",{htmlFor:t,className:os,children:s});return r?e.jsxs("div",{children:[y,e.jsx("select",{id:t,className:Kt,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):l?e.jsxs("div",{children:[y,e.jsx("input",{id:t,required:!0,className:Kt,value:d,onChange:f=>m(f.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:Kt,value:d,onChange:f=>m(f.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":c})]}):e.jsxs("div",{children:[y,h?e.jsx("input",{id:t,required:!0,className:Kt,value:d,onChange:f=>m(f.target.value)}):e.jsxs("select",{id:t,required:!0,className:Kt,value:d,onChange:f=>m(f.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(f=>e.jsxs("option",{value:f.id,children:[f.name,f.detail?` (${f.detail})`:"",f.active?"":" — inactive"]},f.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{x(!h),m("")},children:h?"Choose from synced list":"Enter an ID manually"})]})}function cy({projectId:t,projectName:s}){const n=rn(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),[m,u]=o.useState(""),[p,x]=o.useState(null),[h,y]=o.useState(!1),[f,b]=o.useState(!1),[N,k]=o.useState(""),[$,S]=o.useState(""),[g,v]=o.useState(""),[C,I]=o.useState(""),[A,w]=o.useState(""),[V,G]=o.useState(!1),[Q,B]=o.useState(cl),[z,ne]=o.useState(null),F=o.useRef(null),_=Le({...Iu({client:Y,path:{name:s}}),staleTime:pn}),Z=Le({...Tu({client:Y,path:{name:s}}),staleTime:pn}),L=Le({...Mu({client:Y,path:{name:s}}),staleTime:pn}),ee=Le({...$u({client:Y,path:{name:s}}),staleTime:pn}),T=ee.data,E=Le({...Lu({client:Y,path:{name:s},query:{limit:5}}),staleTime:pn}),te=Le({...qu({client:Y,path:{name:s},query:{limit:5}}),staleTime:pn}),re=L.data??[],Ne=(z?re.find(q=>q.id===z)??null:null)??(re.length===1?re[0]??null:null),X=re.length>1&&!Ne,ue=Le({...Eu({client:Y,path:{name:s,contractId:Ne?.id??""}}),enabled:!!Ne,staleTime:pn}),pe=Le({...Du({client:Y,path:{name:s}}),enabled:p==="google-ads"&&_.data?.connected===!0,staleTime:0}),J=Le({...Ou({client:Y,path:{name:s}}),enabled:p==="gtm"&&Z.data?.connected===!0,staleTime:0}),me=Le({...Fu({client:Y,path:{name:s,accountId:g}}),enabled:p==="gtm"&&!!g,staleTime:0}),K=Le({...Gu({client:Y,path:{name:s,accountId:g,containerId:C}}),enabled:p==="gtm"&&!!g&&!!C,staleTime:0}),he=Dt(Ku({client:Y})),qe=Dt(_u({client:Y})),Re=Dt(Uu({client:Y})),ie=Dt(Bu({client:Y})),ge=Dt(Vu({client:Y})),we=Dt(zu({client:Y})),_e=Dt(Qu({client:Y})),Ee=Dt(Hu({client:Y})),O=Dt(Wu({client:Y}));o.useEffect(()=>{if(p!=="google-ads"||h||!_.isSuccess)return;const q=_.data.connection?.selection;k(q?.customerId??""),S(q?.loginCustomerId??""),y(!0)},[h,_.data,_.isSuccess,p]),o.useEffect(()=>{if(p!=="gtm"||f||!Z.isSuccess)return;const q=Z.data.selection;v(q?.accountId??""),I(q?.containerId??""),w(q?.workspaceId??""),b(!0)},[f,Z.data,Z.isSuccess,p]),o.useEffect(()=>{!z||!L.data||L.data.some(q=>q.id===z)||ne(null)},[L.data,z]);const D=o.useMemo(()=>{const q=E.data?.snapshots??[],Ae=te.data?.snapshots??[],at=[...q.map(St=>({id:St.id,provider:"google-ads",kind:St.kind,capturedAt:St.capturedAt})),...Ae.map(St=>({id:St.id,provider:"gtm",kind:St.kind,capturedAt:St.capturedAt}))].sort((St,Bs)=>Bs.capturedAt.localeCompare(St.capturedAt)).slice(0,5),Nt=[],es=ue.data?.googleAdsSnapshot,Oe=ue.data?.gtmSnapshot;return es&&Nt.push({id:es.id,provider:"google-ads",kind:es.kind,capturedAt:es.capturedAt}),Oe&&Nt.push({id:Oe.id,provider:"gtm",kind:Oe.kind,capturedAt:Oe.capturedAt}),{contract:ue.data?.assessment.contract??Ne,assessment:ue.data?.assessment??null,contractSelectionRequired:X,assessmentState:Ne?ue.isError?"unavailable":ue.isLoading?"loading":void 0:void 0,assessmentError:ue.isError?Ct(ue.error):null,googleAds:ry(_.data,dl(E.data?.total??0,E.isLoading,E.isError,E.error),_.isError),gtm:oy(Z.data,dl(te.data?.total??0,te.isLoading,te.isError,te.error),Z.isError),snapshots:at,assessmentEvidenceSnapshots:Nt}},[Ne,X,E.data,E.error,E.isError,E.isLoading,_.data,_.isError,te.data,te.error,te.isError,te.isLoading,Z.data,Z.isError,ue.data,ue.error,ue.isError,ue.isLoading]),H=o.useSyncExternalStore(_l,or,or),Me=Object.values(H.runs).some(q=>q.projectId===t&&(q.kind===Gs["google-ads-sync"]||q.kind===Gs["gtm-sync"])),Qe=he.isPending||qe.isPending||Re.isPending||ie.isPending||ge.isPending||we.isPending||_e.isPending||Ee.isPending||O.isPending||Me;async function Ge(){await Promise.all([_.refetch(),Z.refetch(),L.refetch(),E.refetch(),te.refetch(),ee.refetch(),Ne?ue.refetch():Promise.resolve()])}async function et(q){await Ge();for(let Ae=0;Ae<10&&!q();Ae+=1)await new Promise(at=>setTimeout(at,1500)),await Ge()}function xe(){const q=document.activeElement;F.current=q instanceof HTMLElement?q:null}function jt(q){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(q);return}globalThis.setTimeout(q,0)}function ze(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Je(q){if(!q)return;!q.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!q.hasAttribute("tabindex")&&(q.tabIndex=-1),q.focus({preventScroll:!0})}function Ot(q,Ae=q){const at=document.getElementById(q);at instanceof HTMLDetailsElement&&(at.open=!0);const Nt=at?.scrollIntoView;typeof Nt=="function"&&Nt.call(at,{behavior:ze()?"auto":"smooth",block:"start"}),Je(document.getElementById(Ae)??at)}function dt(q,Ae){xe(),jt(()=>Ot(q,Ae))}function st(){const q=F.current;F.current=null,q&&jt(()=>{q.isConnected&&q.focus({preventScroll:!0})})}function ht(){r(null),d(!1),st()}function kt(){r(null),x(null),st()}function Mt(){r(null),G(!1),st()}function He(){r(null),x(null),d(!0),dt("google-ads-connect-panel","google-ads-connect-title")}function R(){r(null),k(""),S(""),y(!1),x("google-ads"),d(!1),dt("google-ads-selection-panel","google-ads-selection-title")}function $e(){r(null),v(""),I(""),w(""),b(!1),x("gtm"),d(!1),dt("gtm-selection-panel","gtm-selection-title")}function Te(){r(null),G(!0),dt("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Ue(q,Ae){Kl({id:q.id,projectId:q.projectId,kind:q.kind,projectLabel:s,sourceAction:Ae}),De({title:Ae==="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:${q.id}`,dedupeMode:"replace"})}async function ut(){Ss(n),r(null);try{const q=await he.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."),ul(q.authorizationUrl,()=>{Ge(),i(null),st()})}catch(q){r(Ct(q))}}async function Be(){Ss(n),r(null);try{const q=await qe.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."),ul(q.authorizationUrl,()=>{Ge(),i(null),st()})}catch(q){r(Ct(q))}}async function yt(){if(Ss(n),!N){r("Select a Google Ads customer before saving.");return}r(null);try{await Re.mutateAsync({path:{name:s},body:{customerId:N,...$.trim()?{loginCustomerId:$.trim()}:{}}}),x(null),st(),await et(()=>_.data?.selectedCustomer!=null)}catch(q){r(Ct(q))}}async function se(){if(Ss(n),!g||!C){r("Select a Tag Manager account and container before saving.");return}r(null);try{await ie.mutateAsync({path:{name:s},body:{accountId:g,containerId:C,...A?{workspaceId:A}:{}}}),x(null),st(),await et(()=>Z.data?.status==="connected")}catch(q){r(Ct(q))}}async function Ve(){Ss(n),r(null),await _e.mutateAsync({path:{name:s}}),x(null),d(!1),k(""),S(""),y(!1),i(null),await Ge(),De({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),F.current=null,jt(()=>Je(document.getElementById("conversion-integrity-title")))}async function Ie(){Ss(n),r(null),await Ee.mutateAsync({path:{name:s}}),x(null),v(""),I(""),w(""),b(!1),i(null),await Ge(),De({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),F.current=null,jt(()=>Je(document.getElementById("conversion-integrity-title")))}async function be(){Ss(n),r(null);try{const q=await ge.mutateAsync({path:{name:s}});Ue(q,"google-ads-sync")}catch(q){r(Ct(q))}}async function $t(){Ss(n),r(null);try{const q=await we.mutateAsync({path:{name:s}});Ue(q,"gtm-sync")}catch(q){r(Ct(q))}}async function Yt(){Ss(n),r(null);try{const q=await Promise.allSettled([ge.mutateAsync({path:{name:s}}),we.mutateAsync({path:{name:s}})]),[Ae,at]=q;Ae.status==="fulfilled"&&Ue(Ae.value,"google-ads-sync"),at.status==="fulfilled"&&Ue(at.value,"gtm-sync");const Nt=q.find(es=>es.status==="rejected");if(Nt?.status==="rejected")throw Nt.reason}catch(q){r(Ct(q))}}async function Jt(){Ss(n);const q=_.data?.connection?.selection.customerId,Ae=Z.data?.selection;if(!q||!Ae?.accountId||!Ae.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const at=await O.mutateAsync({path:{name:s},body:ly(Q,q,{accountId:Ae.accountId,containerId:Ae.containerId})});B(cl),G(!1),st(),(await L.refetch()).data?.some(es=>es.id===at.id)&&ne(at.id)}catch(at){r(Ct(at))}}function Ft(q){switch(q){case"connect-google-ads":He();return;case"connect-gtm":xe(),Be();return;case"select-google-ads":R();return;case"select-gtm":$e();return;case"sync-google-ads":be();return;case"sync-gtm":$t();return;case"sync-static-evidence":Yt();return;case"declare-contract":Te();return;case"review-findings":dt("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":dt("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Ge();return;case"select-contract":dt("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ue.refetch();return;case"waiting-for-integrity":return}}const mt=pe.data?.customers??[],Zt=J.data?.accounts??[],ot=me.data?.containers??[],fs=K.data?.workspaces??[],ps=!!N&&!mt.some(q=>q.customerId===N),Ks=!!g&&!Zt.some(q=>q.id===g),bt=!!C&&!ot.some(q=>q.id===C),_s=!!A&&!fs.some(q=>q.id===A),Lt=ps&&pe.isSuccess&&pe.data.truncated===!1,ss=Ks&&J.isSuccess&&J.data.truncated===!1,Vt=bt&&me.isSuccess&&me.data.truncated===!1,pt=_s&&K.isSuccess&&K.data.truncated===!1,$s=ss||Vt||pt,Rt=ss?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Vt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":pt?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,Ls=Wa(Lt,pe.data,pe.isError),Xt=Wa(ss,J.data,J.isError),Pt=Wa(Vt,me.data,me.isError),Gt=Wa(pt,K.data,K.isError),nt=pe.isError?Ct(pe.error):null,xs=J.isError?Ct(J.error):me.isError?Ct(me.error):K.isError?Ct(K.error):null,ys=p==="google-ads"?nt:p==="gtm"?xs:null,U=Ha("customer",pe.data,mt.length),oe=Ha("account",J.data,Zt.length),ke=Ha("container",me.data,ot.length),ae=Ha("draft workspace",K.data,fs.length),Pe=J.isError||me.isError||K.isError&&!!A,Ke=c||p!==null||V;function gt(){pe.refetch()}function vt(){if(J.isError){J.refetch();return}if(me.isError){me.refetch();return}K.isError&&K.refetch()}return _.isLoading||Z.isLoading||L.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(q=>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"})]},q))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):L.isError&&!L.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",Ct(L.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{L.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ay,{workspace:D,onPrimaryAction:Ft,actionPending:Qe,actionError:Ke?null:a,contracts:re,selectedContractId:Ne?.id??null,onSelectContract:q=>ne(q||null),contractError:L.isError?Ct(L.error):null,onRetryContracts:()=>{L.refetch()},onRetryEvidence:()=>{Promise.all([E.refetch(),te.refetch()])},onChangeGoogleAdsSelection:R,onChangeGtmSelection:$e,onAddContract:()=>Ft("declare-contract")}),l?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:l}):null,c?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:Xe(async q=>{q.preventDefault(),await ut()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:os,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:m,onChange:q=>u(q.target.value),className:Kt,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:he.isPending,children:he.isPending?"Starting…":"Continue to Google"}),e.jsx(P,{type:"button",variant:"outline",onClick:ht,children:"Cancel"})]})]})]}):null,p==="google-ads"?e.jsxs("section",{id:"google-ads-selection-panel",className:"page-section-divider","aria-labelledby":"google-ads-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select customer context"})]})}),ys?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ys}),e.jsx(P,{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,Lt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:"The saved customer is no longer accessible. Choose another customer before saving."}):null,e.jsxs("div",{className:"grid max-w-2xl gap-4 sm:grid-cols-2",children:[e.jsxs(Ya,{id:"google-ads-customer",label:"Customer account",value:N,onChange:q=>{y(!0),k(q);const Ae=mt.find(at=>at.customerId===q);S(Ae?.parentCustomerId??"")},disabled:pe.isLoading,children:[e.jsx("option",{value:"",children:pe.isLoading?"Loading accessible customers…":"Select a customer"}),ps?e.jsxs("option",{value:N,disabled:Lt,children:["Saved customer ",N," (",Ls,")"]}):null,mt.map(q=>e.jsx("option",{value:q.customerId,children:q.descriptiveName??`Customer ${q.customerId}`},q.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:os,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Kt,value:$,onChange:q=>{y(!0),S(q.target.value)},placeholder:"Use only when a manager context is required"})]})]}),U?e.jsx("p",{role:"status",className:`mt-3 text-sm ${pe.data?.truncated?"text-caution":"text-secondary"}`,children:U}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:Re.isPending||pe.isLoading||pe.isError||Lt||!N,onClick:Xe(yt),children:Re.isPending?"Saving…":"Save customer selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:kt,children:"Cancel"})]}),_.data?.connected?e.jsx(ml,{providerLabel:"Google Ads",disabled:Qe,onDisconnect:Ve}):null]}):null,p==="gtm"?e.jsxs("section",{id:"gtm-selection-panel",className:"page-section-divider","aria-labelledby":"gtm-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Tag Manager"}),e.jsx("h3",{id:"gtm-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select container context"})]})}),ys?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ys}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:vt,children:J.isError?"Retry account list":me.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(Ya,{id:"gtm-account",label:"Account",value:g,onChange:q=>{b(!0),q!==g&&(I(""),w("")),v(q)},disabled:J.isLoading,children:[e.jsx("option",{value:"",children:J.isLoading?"Loading accounts…":"Select an account"}),Ks?e.jsxs("option",{value:g,disabled:ss,children:["Saved account ",g," (",Xt,")"]}):null,Zt.map(q=>e.jsx("option",{value:q.id,children:q.name},q.id))]}),e.jsxs(Ya,{id:"gtm-container",label:"Container",value:C,onChange:q=>{b(!0),q!==C&&w(""),I(q)},disabled:!g||me.isLoading,children:[e.jsx("option",{value:"",children:me.isLoading?"Loading containers…":"Select a container"}),bt?e.jsxs("option",{value:C,disabled:Vt,children:["Saved container ",C," (",Pt,")"]}):null,ot.map(q=>e.jsx("option",{value:q.id,children:q.name},q.id))]}),e.jsxs(Ya,{id:"gtm-workspace",label:"Draft workspace (optional)",value:A,onChange:q=>{b(!0),w(q)},disabled:!C||K.isLoading,children:[e.jsx("option",{value:"",children:K.isLoading?"Loading workspaces…":"No draft workspace"}),_s?e.jsxs("option",{value:A,disabled:pt,children:["Saved draft workspace ",A," (",Gt,")"]}):null,fs.map(q=>e.jsx("option",{value:q.id,children:q.name},q.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[oe?e.jsx("p",{role:"status",className:J.data?.truncated?"text-caution":"text-secondary",children:oe}):null,ke?e.jsx("p",{role:"status",className:me.data?.truncated?"text-caution":"text-secondary",children:ke}):null,ae?e.jsx("p",{role:"status",className:K.data?.truncated?"text-caution":"text-secondary",children:ae}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:ie.isPending||J.isLoading||me.isLoading||K.isLoading&&!!A||Pe||$s||!g||!C,onClick:Xe(se),children:ie.isPending?"Saving…":"Save container selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:kt,children:"Cancel"})]}),Z.data?.connected?e.jsx(ml,{providerLabel:"Tag Manager",disabled:Qe,onDisconnect:Ie}):null]}):null,V?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:Xe(async q=>{q.preventDefault(),await Jt()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:os,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Kt,value:Q.name,onChange:q=>B(Ae=>({...Ae,name:q.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:os,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Kt,value:Q.eventName,onChange:q=>B(Ae=>({...Ae,eventName:q.target.value})),placeholder:"booking_complete"})]}),e.jsx(hl,{id:"contract-conversion-action",label:"Google Ads conversion action",options:T?.googleAds.conversionActions??[],synced:T?.googleAds.syncedAt!=null,loading:ee.isLoading,failed:ee.isError,onRetry:()=>{ee.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:Q.conversionActionId,onChange:q=>B(Ae=>({...Ae,conversionActionId:q}))}),e.jsx(hl,{id:"contract-gtm-tag",label:"Tag Manager tag",options:T?.gtm.tags??[],synced:T?.gtm.syncedAt!=null,loading:ee.isLoading,failed:ee.isError,onRetry:()=>{ee.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:Q.tagId,onChange:q=>B(Ae=>({...Ae,tagId:q}))})]}),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:os,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Kt,value:Q.conversionId,onChange:q=>B(Ae=>({...Ae,conversionId:q.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:os,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Kt,value:Q.conversionLabel,onChange:q=>B(Ae=>({...Ae,conversionLabel:q.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:os,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Kt,value:Q.triggerIds,onChange:q=>B(Ae=>({...Ae,triggerIds:q.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:os,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Kt,value:Q.variableIds,onChange:q=>B(Ae=>({...Ae,variableIds:q.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:os,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Kt,value:Q.campaignIds,onChange:q=>B(Ae=>({...Ae,campaignIds:q.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:os,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Kt,value:Q.productionHosts,onChange:q=>B(Ae=>({...Ae,productionHosts:q.target.value})),placeholder:"example.com"})]})]}),e.jsxs("fieldset",{className:"mt-5 border-t border-subtle pt-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Required evidence"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsx(Mn,{id:"contract-primary-action",checked:Q.requirePrimaryAction,onChange:q=>B(Ae=>({...Ae,requirePrimaryAction:q})),children:"Google Ads action is primary"}),e.jsx(Mn,{id:"contract-biddable-goal",checked:Q.requireBiddableGoal,onChange:q=>B(Ae=>({...Ae,requireBiddableGoal:q})),children:"Google Ads goal is biddable"}),e.jsx(Mn,{id:"contract-runtime-verification",checked:Q.verificationRequired,onChange:q=>B(Ae=>({...Ae,verificationRequired:q})),children:"Runtime proof is required"}),e.jsx(Mn,{id:"contract-transaction-id",checked:Q.requireTransactionId,onChange:q=>B(Ae=>({...Ae,requireTransactionId:q})),children:"Transaction ID is required"}),e.jsx(Mn,{id:"contract-value",checked:Q.requireValue,onChange:q=>B(Ae=>({...Ae,requireValue:q})),children:"Conversion value is required"}),e.jsx(Mn,{id:"contract-currency",checked:Q.requireCurrency,onChange:q=>B(Ae=>({...Ae,requireCurrency:q})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:O.isPending,children:O.isPending?"Saving…":"Save conversion contract"}),e.jsx(P,{type:"button",variant:"outline",onClick:Mt,children:"Cancel"})]})]})]}):null]})}const dy=6e4,uy=["7d","14d","30d"],Bi="not available",my='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%.',hy="No Google Ads snapshot stored yet",py="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.",xy="No closed days yet",gy="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.",fy={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},Ws=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),zr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),yy=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function $n(t,s){return t===null||!Number.isFinite(t)?Bi:s===null?yy.format(t/1e6):dp(t,s)}function Qr(t){return t===null||!Number.isFinite(t)?Bi:Ze(t)}function by(t,s){return t===null||!Number.isFinite(t)?`${Bi} vs prior ${s}d`:t===0?`no change vs prior ${s}d`:`${t>0?"↑":"↓"} ${Ze(Math.abs(t))} vs prior ${s}d`}function vy(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function jy(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function Ny(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 wy({projectName:t}){const[s,n]=o.useState("14d"),[a,r]=o.useState(()=>new Set(["costMicros","conversions"])),l=Le({...Yu({client:Y,path:{name:t},query:{window:s}}),staleTime:dy}),i=l.data,c=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Fe,{text:my})]}),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(fr,{windows:uy,value:s,onChange:n,label:"Google Ads time period"})]});if(l.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[c,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(g=>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"})]},g))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(l.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",Ct(l.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{l.refetch()},children:"Retry performance"})]});const{totals:d,daily:m,campaigns:u,comparison:p,comparisonUnavailableReason:x,source:h}=i;if(!h){const g=x==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:g?xy:hy}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:g?gy:py})]})]})}const y=h.currencyCode,f=h.campaignsInInventory>0&&h.campaignsQueried<h.campaignsInInventory?{queried:h.campaignsQueried,inInventory:h.campaignsInInventory}:null,b=d.costMicros>0&&d.conversions===0,N=[{key:"spend",comparable:!0,label:"Spend",value:$n(d.costMicros,y),change:p?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:zr.format(d.conversions),change:p?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:b?"no conversions":$n(d.costPerConversionMicros,y),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Qr(d.conversionRate),change:p?.change.conversionRate??null,direction:"up-good",seriesKey:null}],k=[{key:"clicks",label:"Clicks",value:Ws.format(d.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:Ws.format(d.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Qr(d.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:$n(d.cpcMicros,y),seriesKey:null}],$={costMicros:{label:"Spend",color:ct[1],axisId:"spend",formatValue:g=>$n(g,y)},conversions:{label:"Conversions",color:ct[0],axisId:"conversions",formatValue:g=>zr.format(g)},clicks:{label:"Clicks",color:ct[2],axisId:"clicks",formatValue:g=>Ws.format(g)},impressions:{label:"Impressions",color:ct[3],axisId:"impressions",formatValue:g=>Ws.format(g)}},S=[...a].map(g=>({dataKey:g,...$[g]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,f!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",Ws.format(f.queried)," of"," ",Ws.format(f.inInventory)," campaigns, so they are a subset of the account."]}):null,h.truncated?e.jsx("p",{role:"status",className:"mt-3 text-sm text-caution",children:"The provider returned a bounded result, so some rows are missing from the figures below."}):null,!p&&x==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:fy["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:N.map(g=>{const v=g.seriesKey!==null&&a.has(g.seriesKey),C=v&&a.size===1,I=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[g.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?$[g.seriesKey].color:"var(--color-mono-600)"}}):null,g.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:g.value}),p&&g.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${Ny(g.change,g.direction)}`,children:by(g.change,p.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:g.comparable?`no prior ${s} period stored`:" "})]});return g.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:I},g.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:C,onClick:()=>r(A=>{const w=new Set(A);return w.has(g.seriesKey)?w.delete(g.seriesKey):w.add(g.seriesKey),w.size===0?A:w}),className:`rounded-md border px-3 py-2 text-left transition-colors ${v?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${C?"cursor-default":""}`,children:I},g.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:k.map(g=>{const v=g.seriesKey!==null&&a.has(g.seriesKey),C=v&&a.size===1,I=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[g.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?$[g.seriesKey].color:"var(--color-mono-600)"}}):null,g.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:g.value})]});return g.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:I},g.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:C,onClick:()=>r(A=>{const w=new Set(A);return w.has(g.seriesKey)?w.delete(g.seriesKey):w.add(g.seriesKey),w.size===0?A:w}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${C?"cursor-default":"hover:bg-surface-hover"}`,children:I},g.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(oc,{data:m,xKey:"date",series:S,xTickFormatter:Nn,labelFormatter:Tt}),e.jsx("ul",{className:"sr-only",children:m.map(g=>e.jsxs("li",{children:[Tt(g.date),":"," ",S.map(v=>`${v.label} ${$[v.dataKey].formatValue(g[v.dataKey])}`).join(", "),g.origin==="filled"?", no delivery reported":""]},g.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(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:g.name??g.campaignId,children:g.name??e.jsx("span",{className:"font-mono text-secondary",children:g.campaignId})}),e.jsx("td",{children:e.jsx(je,{tone:vy(g.status),children:jy(g.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ws.format(g.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ws.format(g.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:$n(g.totals.costMicros,y)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:zr.format(g.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Qr(g.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:g.totals.costMicros>0&&g.totals.conversions===0?e.jsx(je,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:$n(g.totals.costPerConversionMicros,y)})})]},g.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Ca(Bt(h.capturedAt))," · ","customer ",h.customerId," · ","latest closed day ",Tt(h.asOfDate),h.openDate?e.jsxs(e.Fragment,{children:[" · ",Tt(h.openDate)," still open, excluded"]}):null,h.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",h.timeZone]}):null]})]})]})}const Hr=20,Es=50,Sy=50,Cy=50;function Vi(t){return t==="viewer"}function zi(t){return t?.status==="unavailable"}function zc(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Qc(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 Ja(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 ky(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 Wr(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 pl(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function xl(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 Xa(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 vi(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Yr(t){return vi(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ji({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[l,i]=o.useState(""),[c,d]=o.useState(!1),m=l.trim().toLocaleLowerCase(),u=m?t.filter(y=>y.label.toLocaleLowerCase().includes(m)):t,p=c?u:u.slice(0,Sy),x=p.length<u.length;function h(){const y=new Set([...s,...p.map(f=>f.id)]);n(t.filter(f=>y.has(f.id)).map(f=>f.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(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p.length===0,onClick:h,children:"Select all shown"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),u.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",p.length," of ",u.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:p.map(y=>{const f=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:f,type:"checkbox",onChange:b=>n(zc(s,y.id,b.currentTarget.checked))}),e.jsx("span",{children:y.label})]}),y.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[y.urlCount," URLs"]})]},y.id)})}),x?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function Qi(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(je,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Hi({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function Ay({value:t}){const[s,n]=o.useState(0),[a,r]=o.useState(0),[l,i]=o.useState(null),c=t.preview,d=c?.counts.needsAttention??0,m=c?.rows.filter(C=>C.status==="matched")??[],u=c?.rows??[],p=u.filter(C=>C.status!=="matched"),x=Math.max(1,Math.ceil(u.length/Es)),h=Math.min(s,x-1),y=u.slice(h*Es,(h+1)*Es),f=Math.max(1,Math.ceil(p.length/Es)),b=Math.min(a,f-1),N=p.slice(b*Es,(b+1)*Es),k=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,$=m.length>0&&!t.isApplying,S=c!==null&&l===c.previewChecksum,g=p.length>0&&b===f-1;o.useEffect(()=>{n(0),r(0),i(null)},[c?.previewChecksum]);async function v(C){if(C)try{t.onCsvChange(await C.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:C=>{v(C.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:C=>t.onCsvChange(C.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(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!k,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),c?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[c.counts.matchedRows," matched · ",c.counts.groupsReady," group",c.counts.groupsReady===1?"":"s"," ready",d>0?` · ${d} need${d===1?"s":""} attention`:""]}),c.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:c.groupChanges.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:C.label}),e.jsx("td",{className:"text-secondary",children:C.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:C.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[C.addedTargetKeys.length,C.unchangedTargetKeys.length>0?` · ${C.unchangedTargetKeys.length} already members`:""]})]},C.groupKey))})]})}):null,c.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",c.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:y.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(je,{tone:pl(C.status),children:xl(C.status)}),Xa(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Xa(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",h+1," of ",x," · ",c.rows.length," rows"]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h===0,onClick:()=>n(C=>Math.max(0,C-1)),children:"Previous 50 rows"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h===x-1,onClick:()=>n(C=>Math.min(x-1,C+1)),children:"Next 50 rows"})]})]}):null,d>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",d," row",d===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:N.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(je,{tone:pl(C.status),children:xl(C.status)}),Xa(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Xa(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",b+1," of ",f]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===0,onClick:()=>r(C=>Math.max(0,C-1)),children:"Previous 50 exceptions"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===f-1,onClick:()=>r(C=>Math.min(f-1,C+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:S,disabled:t.isApplying||!g,onChange:C=>i(C.currentTarget.checked?c.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",d," row",d===1?"":"s"," will be skipped."]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!$||!S,onClick:()=>{t.onApply(m.map(C=>C.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${m.length} matched row${m.length===1?"":"s"}`})]}):e.jsx(P,{type:"button",className:"mt-3 min-h-11",disabled:!$,onClick:()=>{t.onApply(m.map(C=>C.dataRow))},children:t.isApplying?"Creating groups…":`Create ${c.counts.groupsReady} group${c.counts.groupsReady===1?"":"s"} with ${m.length} membership${m.length===1?"":"s"}`})]}):null]})}const Ry="—";function Py({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:l=!1,isBusy:i=!1,canContinue:c=!0,onSelectedQueryIdsChange:d,onApplySelectedQueries:m,onClearQueryAssignments:u,onRemoveQuery:p,onCreateQueries:x,onCreateAndPairQuestions:h,isCreatingQueries:y=!1,createQueriesError:f=null,onManageProjectQueries:b,groups:N,audience:k,onAudienceChange:$,assignmentImpact:S=null,isPreviewingAssignmentImpact:g=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:C,assignmentNotice:I=null,onReplaceAssignments:A,isReplacingAssignments:w=!1,onBack:V,onContinue:G}){const[Q,B]=o.useState(""),[z,ne]=o.useState(!1),[F,_]=o.useState(!1),[Z,L]=o.useState(""),[ee,T]=o.useState(""),[E,te]=o.useState(null);if(zi(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Hi,{message:s.message})});const re=Vi(t),ce=k,Ne=$,X=Ja(ce,n,N),ue=X.length,pe=ue>0&&r.length>0&&!l&&!i&&!g&&S!==null&&v===null,J=u??p,me=Q.trim().toLocaleLowerCase(),K=me?a.filter(H=>Yr(H).toLocaleLowerCase().includes(me)):a,he=K.filter(H=>(H.propertyIds?.length??0)===0),qe=F?he:K,Re=z?qe:qe.slice(0,Cy),ie=Re.filter(H=>!vi(H)),ge=[...new Set(Z.split(`
4
+ `).map(H=>H.trim()).filter(Boolean))],we=[...ee.matchAll(/\{([a-z][\w-]*)\}/gi)].map(H=>H[1]),_e=n.filter(H=>X.includes(H.id)),Ee=we.length===0||ee.trim()===""?[]:_e.map(H=>({propertyId:H.id,text:we.reduce((Me,Qe)=>Me.replaceAll(`{${Qe}}`,H.label),ee.trim())})),O=[...new Set(Ee.map(H=>H.text))];function D(){const H=new Set([...r,...ie.map(Me=>Me.id)]);d(a.filter(Me=>H.has(Me.id)).map(Me=>Me.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."})]})}),re?e.jsx(Qi,{}):null,re?null:e.jsxs("fieldset",{className:"border-y border-default py-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Apply to"}),e.jsx("div",{className:"mt-3 max-w-xl",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"sr-only",children:"Apply to"}),e.jsxs("select",{"aria-label":"Apply to",value:ce.kind==="all"?"all":ce.kind==="specific"?"specific":`group:${ce.groupIds[0]??""}`,onChange:H=>{const Me=H.currentTarget.value;Me==="all"?Ne({kind:"all"}):Me==="specific"?Ne({kind:"specific",propertyIds:[]}):Me.startsWith("group:")&&Ne({kind:"groups",groupIds:[Me.slice(6)]})},className:"block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsxs("option",{value:"all",children:["All Properties · ",n.length]}),N.length>0?e.jsx("optgroup",{label:"Groups",children:N.map(H=>{const Me=Ja({kind:"groups",groupIds:[H.id]},n,N).length;return e.jsx("option",{value:`group:${H.id}`,disabled:Me===0,children:Wr(H,n)},H.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),ce.kind==="groups"?e.jsxs("div",{className:"mt-3 max-w-2xl space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:ce.groupIds.map(H=>{const Me=N.find(Qe=>Qe.id===H);return Me?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:[Wr(Me,n),e.jsx("button",{type:"button","aria-label":`Remove ${Me.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 Qe=ce.groupIds.filter(Ge=>Ge!==Me.id);Ne(Qe.length>0?{kind:"groups",groupIds:Qe}:{kind:"all"})},children:"×"})]},Me.id):null})}),N.some(H=>!ce.groupIds.includes(H.id)&&Ja({kind:"groups",groupIds:[H.id]},n,N).length>0)?e.jsxs("label",{className:"block max-w-sm",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Add another group"}),e.jsxs("select",{"aria-label":"Add another group",value:"",onChange:H=>{H.currentTarget.value&&Ne({kind:"groups",groupIds:[...ce.groupIds,H.currentTarget.value]})},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",children:"Choose a group"}),N.filter(H=>!ce.groupIds.includes(H.id)).map(H=>{const Me=Ja({kind:"groups",groupIds:[H.id]},n,N).length;return e.jsx("option",{value:H.id,disabled:Me===0,children:Wr(H,n)},H.id)})]})]}):null,ue===0?e.jsx("p",{role:"alert",className:"text-sm text-caution",children:"This group has no included Properties. Add Properties to the group, then try again."}):null]}):null,ce.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(ji,{legend:"Specific Properties",properties:n,selectedPropertyIds:ce.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:H=>{Ne({kind:"specific",propertyIds:H})}})}):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."})]}),re||!x?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:Z,onChange:H=>L(H.currentTarget.value),placeholder:`best apartments in dallas
5
5
  luxury apartments atlanta
6
- pet friendly apartments austin`}),f?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:f}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:fe.length===0||y||i,onClick:()=>{Promise.resolve(x(fe)).then(()=>$(""),()=>{})},children:y?"Adding…":`Add ${fe.length||""} ${fe.length===1?"query":"queries"}`.replace(" "," ")}),b?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:b,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:ee,onChange:H=>T(H.target.value),placeholder:"apartments near {property}"}),ee.trim()===""?null:Ce.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."]}):Ge.length===0?e.jsx("p",{className:"mt-2 text-sm text-caution",children:"Select at least one Property to write queries for."}):e.jsxs("div",{className:"mt-2 rounded-md border border-base bg-bg-elevated p-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:[O.length," ",O.length===1?"query":"queries",", one per selected Property:"]}),e.jsx("ul",{className:"mt-1 mb-0 list-none space-y-0.5 p-0",children:O.slice(0,3).map(H=>e.jsx("li",{className:"text-sm text-strong",children:H},H))}),O.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",O.length-3," more"]}):null]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Ee.length===0||y||i||!h,onClick:()=>{h&&Promise.resolve(h(Ee)).then(()=>T(""),()=>{})},children:y?"Adding…":`Add ${Ee.length||""} ${Ee.length===1?"query":"queries"}`.replace(" "," ")}),Ee.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"," ",Ee.length," assignment",Ee.length===1?"":"s","."]}):null]})]})]}),re?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(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:ie.length===0,onClick:D,children:"Select all shown queries"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>d([]),children:"Clear query selection"}),e.jsx(P,{type:"button",size:"sm",className:"min-h-11",disabled:!xe,onClick:()=>{m({queryIds:r,propertyIds:X,...le.kind==="groups"?{groupIds:le.groupIds}:{}})},children:l?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${Cy(le,N,ue)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[g?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,S?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",S.assignmentCount," Property assignment",S.assignmentCount===1?"":"s"," · ",S.addedAssignments," new, ",S.alreadyPresentAssignments," already assigned"," · ",S.fullRunProviderCalls," provider request",S.fullRunProviderCalls===1?"":"s"," per full run"," · ",S.addedProviderCalls," new",le.kind==="groups"?` · ${S.resolvedPropertyCount} unique ${S.resolvedPropertyCount===1?"Property":"Properties"}${S.overlapCount>0?`, ${S.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):v?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:v}),C?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:C,children:"Retry impact"}):null,V?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:V,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",ue," Properties = ",r.length*ue," assignments"]})]}),I?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:I}):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:Q,onChange:H=>{B(H.currentTarget.value),ne(!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 ",Ae.length," of ",qe.length," queries,"," ",K.length-pe.length," of ",K.length," applied"]}),re||pe.length===0?null:e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{_(H=>!H),ne(!1)},children:F?"Show all queries":`Show the ${pe.length} not applied`})]})]}):null,Ae.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:[re?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),re?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:Ae.map(H=>{const Me=vi(H),Qe=Yr(H),Fe=r.includes(H.id),tt=(H.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[re?null:Me?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 ${Qe}`,checked:Fe,type:"checkbox",onChange:ge=>d(zc(r,H.id,ge.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:Qe})}),e.jsx("td",{className:"text-secondary",children:Qc(H.propertyIds??[],n)}),re?null:e.jsx("td",{className:"text-right",children:tt?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[A?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||w,onClick:()=>te({queryId:H.id,propertyIds:[...H.propertyIds??[]]}),"aria-label":`Replace query assignments for ${Qe}`,children:"Replace assignments"}):null,e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{J(H.id)},"aria-label":`Clear query assignments for ${Qe}`,children:"Clear assignments"})]}):null})]},H.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,re||!E?null:(()=>{const H=a.find(Fe=>Fe.id===E.queryId),Me=H?Yr(H):"this query",Qe=E.propertyIds.filter(Fe=>n.some(tt=>tt.id===Fe));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 “",Me,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(ji,{legend:"Properties for this query",properties:n,selectedPropertyIds:Qe,onSelectedPropertyIdsChange:Fe=>te(tt=>tt&&{...tt,propertyIds:[...Fe]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:w||i,onClick:()=>te(null),children:"Keep current assignments"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Qe.length===0||w||i||!A,onClick:()=>{A&&Promise.resolve(A({queryId:E.queryId,propertyIds:Qe}))},children:w?"Replacing assignments…":`Replace with ${Qe.length} ${Qe.length===1?"Property":"Properties"}`})]})]})})(),Ae.length<qe.length?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>ne(!0),children:"Show all queries"}):null,re?null:e.jsxs(e.Fragment,{children:[c?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${V?"justify-between":"justify-end"}`,children:[V?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:V,children:"Back"}):null,e.jsx(P,{type:"button",variant:xe?"outline":"default",className:"min-h-11",disabled:!c||i,onClick:G,children:"Continue"})]})]})]})}function Py({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:l=!1,onGroupDraftChange:i,onSaveGroup:c,onEditGroup:d,onRemoveGroup:m,onClearGroupDraft:u,membershipImport:p,onBack:x,onContinue:h}){if(zi(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(Hi,{message:s.message})});const y=Vi(t),f=r.name.trim().length>0&&r.propertyIds.length>0&&!l,b=n.filter(S=>r.propertyIds.includes(S.id)).length,N=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,k=!y&&(d!==void 0||m!==void 0);function L(){if(u){u();return}i({name:"",propertyIds:[],competitorDomains:""})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-groups-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-groups-title",children:"Groups"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Use groups to assign queries by market and compare competitors."})]})}),y?e.jsx(Qi,{}):null,y||!p?null:e.jsx(ky,{value:p}),y?null:e.jsxs("div",{className:"space-y-4 border-y border-default py-4",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Group name"}),e.jsx("input",{"aria-label":"Group name",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.name,onChange:S=>i({...r,name:S.currentTarget.value}),placeholder:"Waterfront venues"})]}),e.jsxs("details",{children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:[b," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(ji,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:S=>i({...r,propertyIds:S})})})]}),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:S=>i({...r,competitorDomains:S.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!f,onClick:()=>{c(r)},children:l?"Saving group…":"Save group"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!N,onClick:L,children:"Clear form"}),e.jsx("p",{className:"text-sm text-secondary",children:"Competitor domains are used only in this group's competitor report. Membership changes affect future assignments only."})]}),N?e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Save this group or clear the form before continuing."}):null]}),e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Competitors"}),k?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.name}),e.jsx("td",{className:"text-secondary",children:Qc(S.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:S.competitors.length>0?S.competitors.join(", "):"None"}),k?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[d?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${S.name}`,onClick:()=>d(S),children:"Edit"}):null,m?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${S.name}`,onClick:()=>{m(S.id)},children:"Remove"}):null]})}):null]},S.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 ${x?"justify-between":"justify-end"}`,children:[x?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:x,children:"Back"}):null,e.jsx(P,{type:"button",className:"min-h-11",disabled:N,onClick:h,children:a.length===0&&!N?"Continue without groups":"Continue"})]})]})}function Iy({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:l,onReviewChanges:i,isReviewing:c=!1,canReviewChanges:d=!0,reviewedChanges:m,reviewChangesError:u,canPublish:p,isPublishing:x=!1,onPublish:h}){const[y,f]=o.useState(Hr),[b,N]=o.useState(Hr),[k,L]=o.useState(Hr);if(zi(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(Hi,{message:s.message})});const S=Vi(t),g=r?.items??[],v=r?.coverageItems??[],C=g.slice(0,y),I=v.slice(0,b),A=a.slice(0,k),w=i!==void 0,V=m!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),S?e.jsx(Qi,{}):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,")"]}),g.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:C.map(G=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:G.url}),e.jsx("p",{className:"mt-1 text-secondary",children:G.reason})]},`${G.url}-${G.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 ",C.length," of ",g.length]}),C.length<g.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>f(G=>G+Fs),children:"Show next 50 URLs"}):null]})]}):null,S?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,")"]}),I.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[I.map(G=>e.jsxs("section",{"aria-label":`${G.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:G.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:G.savedUrls.map(Q=>e.jsx("li",{className:"break-all text-secondary",children:Q},Q))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),G.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:G.currentSitemapUrls.map(Q=>e.jsx("li",{className:"break-all text-secondary",children:Q},Q))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},G.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",I.length," of ",v.length]}),I.length<v.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>N(G=>G+Fs),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(P,{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??Ay})]})})]})}),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((G,Q)=>e.jsx("li",{children:G},`${G}-${Q}`))}):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:A.map(G=>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:G.title}),G.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:G.detail}):null]}),e.jsx(Ne,{tone:G.tone??"caution",children:"Needs attention"})]},G.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",A.length," of ",a.length]}),A.length<a.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>L(G=>G+Fs),children:"Show next 50 exceptions"}):null]})]})]}),S?null:e.jsxs(e.Fragment,{children:[w&&u?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:u}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${l?"justify-between":"justify-end"}`,children:[l?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:l,children:"Back"}):null,i!==void 0&&!V?e.jsx(P,{type:"button",className:"min-h-11",disabled:c||!d,onClick:()=>{i()},children:c?"Reviewing changes…":"Review changes"}):e.jsx(P,{type:"button",className:"min-h-11",disabled:!p||x,onClick:()=>{h()},children:x?"Publishing setup…":"Publish setup"})]})]})]})}const Ty={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function My(t){return t.trim().toLocaleLowerCase()}function Ly(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function $y({property:t}){const s=t.urls??[t.url];return s.length<=1?e.jsx("span",{children:s[0]??"No URL"}):e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-xs font-medium text-primary",children:[s.length," URLs"]}),e.jsx("ul",{className:"mt-2 space-y-1",children:s.map(n=>e.jsx("li",{className:"break-all font-mono text-xs text-secondary",children:n},n))})]})}function qy({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const l=!t||r==="reviewing",i=l||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function c(d,m){n({...s,[d]:m})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":r==="reviewing",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-import-heading",className:"text-lg font-semibold text-heading",children:"Import Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review sitemap entries before choosing the Properties to measure."})]}),t?null:e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm text-secondary",children:[e.jsx(Ne,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:d=>{d.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:l,onChange:d=>c("sitemapUrl",d.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:l,onChange:d=>c("examplePropertyUrl",d.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:l,onChange:d=>c("preferredHost",d.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:l,onChange:d=>c("propertyPathPattern",d.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:l,onChange:d=>c("additionalHost",d.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:l,onChange:d=>c("additionalPathPattern",d.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:l,onChange:d=>c("excludedPaths",d.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(P,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function Ey({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:l,onSelectedPropertyIdsChange:i,onContinue:c,isContinuing:d=!1,onRetryProperties:m,onReturnToImport:u,maxVisibleProperties:p,onShowAllProperties:x}){const h=My(a),y=s.filter(A=>Ly(A,h)),f=Math.max(1,p??y.length),b=y.slice(0,f),N=new Set(l),k=s.filter(A=>N.has(A.id)).map(A=>A.id),L=b.length<y.length;function S(A){const w=new Set(A);i(s.filter(V=>w.has(V.id)).map(V=>V.id))}function g(A,w){if(!t||d)return;const V=new Set(k);w?V.add(A):V.delete(A),S(V)}function v(){!t||d||S([...k,...b.map(A=>A.id)])}function C(){!t||d||i([])}function I(){!t||d||k.length===0||c(k)}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(P,{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(P,{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(P,{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:A=>r(A.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(P,{type:"button",variant:"outline",size:"sm",disabled:d,onClick:v,children:"Select all shown"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:d||k.length===0,onClick:C,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(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",b.length," of ",y.length," Properties"]}),e.jsxs("p",{children:[k.length," of ",s.length," selected"]})]}),e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"w-full min-w-150 text-left text-sm","aria-label":"Properties to review",children:[e.jsx("thead",{className:"bg-surface-subtle text-xs font-medium uppercase tracking-wide text-secondary",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-3 py-2",children:"Property"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"URL"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"State"}),t?e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Include"}):null]})}),e.jsx("tbody",{children:b.map(A=>{const w=Ty[A.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:A.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx($y,{property:A})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(Ne,{tone:w.tone,children:w.label})}),t?e.jsx("td",{className:"p-0 text-right",children:e.jsx("label",{className:"ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{type:"checkbox","aria-label":`Select ${A.name}`,checked:k.includes(A.id),disabled:d,onChange:V=>g(A.id,V.target.checked),className:"size-6 accent-accent"})})}):null]},A.id)})})]})}),L&&x?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:d,onClick:x,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(P,{type:"button",variant:"ghost",disabled:d,onClick:u,children:"Back"}),e.jsx(P,{type:"button",disabled:d||k.length===0,onClick:I,children:d?"Saving Properties…":"Continue"})]}):null]}):null]})}function Dy(t){return t.activeStep==="import"?e.jsx(qy,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(Ey,{...t})}const Oy=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function Fy({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:l}){const i=o.useRef(null),c=o.useRef(null),d=o.useRef(null),m=o.useRef(null),u=o.useRef(!1),[p,x]=o.useState(!1);return o.useEffect(()=>{s||x(!1)},[s]),o.useEffect(()=>{const h=u.current;u.current=p,p?d.current?.focus():h&&m.current?.focus()},[p]),o.useEffect(()=>{const h=i.current;if(i.current=t,h===null||h===t)return;const y=c.current?.querySelector('h1, h2, h3, [role="heading"]');y&&(y.tabIndex=-1,y.focus())},[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 w-full sm:flex-1",children:[e.jsx("h2",{children:"Advanced measurement setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties and queries you want to measure."})]}),s?e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end",children:[e.jsx(Ne,{tone:"caution",children:"Unpublished changes"}),n&&a?p?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",role:"group","aria-label":"Confirm discard",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Discard all unpublished changes?"}),e.jsx(P,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>x(!1),children:"Keep editing"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(P,{ref:m,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>x(!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:Oy.map(h=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===h.id?"step":void 0,onClick:()=>r(h.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===h.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:h.label}):e.jsx("span",{"aria-current":t===h.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===h.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:h.label})},h.id))})}),e.jsx("div",{ref:c,children:l})]})}function Gy(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Dy,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(Ry,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(Py,{...t.groups,access:s}):"review"in t?e.jsx(Iy,{...t.review,access:s}):null}function Xa(t){return e.jsx(Fy,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Gy(t)})}function Hc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Wt(t){return{"If-Match":t,"Idempotency-Key":Hc()}}function fn(t){return t instanceof Vn&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function os(t,s){return t instanceof Vn?s:(t instanceof Error?t.message.trim():"")||s}function Ky(t){const s="Could not calculate assignment impact.";if(!(t instanceof Vn)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const _y={loadSetup:t=>jt(()=>fm({client:Y,path:{name:t}})),loadDraft:t=>jt(()=>gm({client:Y,path:{name:t}})),createDraft:(t,s)=>jt(()=>xm({client:Y,path:{name:t},headers:{"Idempotency-Key":Hc()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>jt(()=>pm({client:Y,path:{name:t},headers:Wt(s),body:n})),applySitemapSelection:(t,s,n,a)=>jt(()=>hm({client:Y,path:{name:t},headers:Wt(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>jt(()=>mm({client:Y,path:{name:t},body:s})),applyAssignments:(t,s,n)=>jt(()=>um({client:Y,path:{name:t},headers:Wt(s),body:n})),replaceAssignments:(t,s,n)=>jt(()=>dm({client:Y,path:{name:t},headers:Wt(s),body:n})),applyPairedAssignments:(t,s,n)=>jt(()=>cm({client:Y,path:{name:t},headers:Wt(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>jt(()=>lm({client:Y,path:{name:t},headers:Wt(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>jt(()=>om({client:Y,path:{name:t},headers:Wt(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>jt(()=>im({client:Y,path:{name:t},headers:Wt(s),body:{target:n}})),upsertGroup:(t,s,n)=>jt(()=>rm({client:Y,path:{name:t},headers:Wt(s),body:{group:n}})),removeGroup:(t,s,n)=>jt(()=>am({client:Y,path:{name:t},headers:Wt(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>jt(()=>nm({client:Y,path:{name:t},headers:Wt(s),body:n})),removeCompetitor:(t,s,n,a)=>jt(()=>sm({client:Y,path:{name:t},headers:Wt(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>jt(()=>tm({client:Y,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>jt(()=>em({client:Y,path:{name:t},headers:Wt(s),body:n})),compilePreview:t=>jt(()=>Zu({client:Y,path:{name:t}})),diffPreview:t=>jt(()=>Xu({client:Y,path:{name:t}})),publish:(t,s,n)=>jt(()=>Ju({client:Y,path:{name:t},headers:Wt(s),body:n})),discard:(t,s)=>jt(()=>Yu({client:Y,path:{name:t},headers:Wt(s)}))},gl={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},oa={name:"",propertyIds:[],competitorDomains:""},fl=50;function ua(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Uy(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 yl(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 By(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,c=i.startsWith("*"),d=i.endsWith("*"),m=i.slice(c?1:0,d?-1:void 0).trim();if(!m)throw new Error("Ignored URL patterns must include text besides *.");const u=c&&d?"contains":c?"suffix":d?"prefix":"exact",p=`${u}:${m}`;n.has(p)||(n.add(p),s.push({kind:u,value:m}))}return s}function Vy(t){const s=Uy(t.sitemapUrl),n=t.examplePropertyUrl.trim()?ua(t.examplePropertyUrl):null,a=ua(t.preferredHost)??n??ua(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=ua(t.additionalHost),l=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(l!==i||l&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const c=By(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:yl(t)},...r?{aliases:[{host:r,pathTemplate:yl({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...c.length>0?{excludedSlugPatterns:c}:{}}}}function zy(t){return!t||t.authoring.targets.length===0?"import":t.authoring.targets.some(s=>s.status==="proposed")?"properties":t.authoring.assignments.length===0?"groups":t.baseActiveRevision===null?"review":"properties"}function Qy(t,s){return!t||t.authoring.targets.length===0?"import":!t.authoring.targets.some(n=>n.status!=="excluded")||t.authoring.targets.some(n=>n.status==="proposed")?"properties":t.authoring.assignments.length===0&&s==="review"?"groups":s}function bl(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function Hy(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Jr(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function Ni(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function vl(t){return ua(t)}function Wc(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 Yc(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 Jc(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Xc(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Wy(t,s){const n=Wc(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 Yy(t,s){const n=Yc(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=Xc(t.authoring,n.targetKeys[r]);return`${n.label} — ${l}`}return n.label}function Jy(t,s){const n=Jc(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${Xc(t.authoring,n.targetKey)} — ${a}`}function Xy(t,s){return s.path[0]==="identities"?"Project domain":Wy(t,s)??Yy(t,s)??Jy(t,s)}function jl(t,s,n){const a=Jc(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 Zy(t,s){const n=Xy(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,jl(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,jl(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 Za(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function Zc(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 eb(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${Za(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${Za(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${Za(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${Za(n,"item")} need review.`:s}})()}${Zc(a)}`}function tb(t,s){const n=new Map;for(const a of t){const r=Zy(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:eb(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function Xr(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function Zr(t,s,n){const a=Wc(n,t.path),r=Yc(n,t.path),l=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=l?n?.targets.find(u=>u.stableKey===l):void 0,c=a?.label??r?.label,d=Zc(c?[c]:[]),m={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...m,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${d}`};case"excluded-target-has-assignments":return{...m,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${d}`};case"group-unknown-target":return{...m,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${d}`};case"measurement.discovery.proposed_new_target":{const u=Xr(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=Xr(a)??"the proposed Property",p=i?.label??"an existing Property";return{...m,title:"Review a moved Property",detail:`Review ${u}. It may be the same Property as ${p}.`}}case"measurement.discovery.rebind_ambiguous":{const u=Xr(a)??"the proposed Property",p=i?.label??"an existing Property";return{...m,title:"Choose an existing Property",detail:`Review ${u}. It may match ${p}; 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 sb(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 Rs(t){return[...new Set(t)]}function Ys(t){return Rs(t).sort()}function nb(t,s,n){return t.kind==="groups"?{groupKeys:Ys(t.groupIds),queryIds:Ys(n)}:{targetKeys:Ys(t.kind==="all"?s:t.propertyIds),queryIds:Ys(n)}}function ab(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 Nl(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function rb(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(Nl).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(Nl).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:Ni(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function ib({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:l,canEdit:i=!0,onCreateQueries:c,onManageProjectQueries:d,onPublished:m,service:u=_y}){const[p,x]=o.useState(null),[h,y]=o.useState(null),[f,b]=o.useState("import"),[N,k]=o.useState(!0),[L,S]=o.useState(null),[g,v]=o.useState(null),[C,I]=o.useState([]),[A,w]=o.useState({...gl}),[V,G]=o.useState("idle"),[Q,B]=o.useState(""),[z,ne]=o.useState(fl),[F,_]=o.useState([]),[Z,$]=o.useState([]),[ee,T]=o.useState({kind:"all"}),[E,te]=o.useState(null),[re,le]=o.useState(null),[we,X]=o.useState(!1),[ue,xe]=o.useState(null),[J,he]=o.useState(0),[K,pe]=o.useState(null),[qe,Ae]=o.useState({...oa}),[ie,fe]=o.useState(null),[Ce,Ge]=o.useState(""),[Ee,O]=o.useState(null),[D,H]=o.useState(!1),[Me,Qe]=o.useState(!1),[Fe,tt]=o.useState(null),[ge,vt]=o.useState(null),[Ve,Je]=o.useState(null),[Dt,ct]=o.useState(null),[at,pt]=o.useState(null),Ct=o.useRef(0),It=o.useRef(0),He=h?.draft??null,R=h?.etag??null,Le=o.useMemo(()=>!i&&l?{baseActiveRevision:l.revision,authoring:rb(l)}:null,[i,l]),Pe=He??Le;async function Ke(U){const ae=++Ct.current;k(!0),S(null);try{let[me,ce]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);if(!ce.draft&&U&&i&&(await u.createDraft(t,me.activeRevision),[me,ce]=await Promise.all([u.loadSetup(t),u.loadDraft(t)])),ae!==Ct.current)return;x(me),y(ce),b(zy(ce.draft));const Ie=Jr(ce.draft);_(Ie)}catch(me){if(ae!==Ct.current)return;S(os(me,"Could not load advanced measurement setup."))}finally{ae===Ct.current&&k(!1)}}o.useEffect(()=>(Ke(!0),()=>{Ct.current+=1}),[t,i,u]),o.useEffect(()=>{!N&&!He&&Le&&b("properties")},[He,N,Le]);async function dt(){const U=await u.loadDraft(t);return y(U),U}async function ze(U){pt(null);try{const[ae,me]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);x(ae),y(me);const ce=Jr(me.draft);_(ce),b(Ie=>Qy(me.draft,Ie)),v(U)}catch(ae){v(os(ae,U))}}async function yt(U,ae,me,ce={}){const{preserveBusyAction:Ie=!1}=ce;if(!i||!R||Ve&&!Ie)return null;Ie||Je(U),v(null),pt(null);try{const Ue=await ae(R),mt=await dt();return I((Ue.warnings??[]).map((kt,vs)=>Zr(kt,vs,mt.draft?.authoring))),mt}catch(Ue){return fn(Ue)?await ze("This setup changed in another session. The latest draft is loaded; review your changes again."):v(os(Ue,me)),null}finally{Ie||Je(null)}}const se=o.useMemo(()=>(Pe?.authoring.targets??[]).map(U=>{const ae=bl(U);return{id:U.stableKey,name:U.label,url:ae[0]??"No URL",urls:ae,state:Hy(U.status)}}),[Pe]),_e=o.useMemo(()=>Pe?.authoring.targets.filter(U=>U.status==="included")??[],[Pe]),Re=o.useMemo(()=>_e.map(U=>({id:U.stableKey,label:U.label,urlCount:bl(U).length})),[_e]),ve=Pe?.authoring.assignments.length??0,Tt=o.useMemo(()=>{if(!Pe)return[];const U=new Set(s.map(ce=>ce.id)),ae=s.map(ce=>({id:ce.id,text:ce.query,source:"saved-project-queries",propertyIds:Rs(Pe.authoring.assignments.filter(Ie=>Ie.queryId===ce.id).map(Ie=>Ie.targetKey))})),me=Rs(Pe.authoring.assignments.map(ce=>ce.queryId).filter(ce=>!U.has(ce))).map(ce=>({id:ce,source:"unavailable-tracked-query",state:"missing",propertyIds:Rs(Pe.authoring.assignments.filter(Ie=>Ie.queryId===ce).map(Ie=>Ie.targetKey))}));return[...ae,...me]},[s,Pe]),Xt=o.useMemo(()=>(Pe?.authoring.groups??[]).map(U=>({id:U.stableKey,name:U.label,propertyIds:U.targetKeys,competitors:U.competitors.map(ae=>ae.domain)})),[Pe]),Zt=o.useMemo(()=>{if(Z.length===0)return null;const U=nb(ee,Re.map(me=>me.id),Z);return(U.groupKeys?.length??U.targetKeys?.length??0)>0?U:null},[ee,Re,Z]),Ot=Zt?JSON.stringify(Zt):"";o.useEffect(()=>{const U=Zt,ae=++It.current;if(!i||!He||!R||!U){te(null),le(null),xe(null),X(!1);return}te(null),le(null),xe(null),X(!0);const me=window.setTimeout(()=>{u.previewAssignments(t,U).then(ce=>{if(ae===It.current){if(ce.draftEtag!==R){te(null),le(null),xe("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}te(ce),le(Ot)}}).catch(ce=>{ae===It.current&&(te(null),le(null),xe(Ky(ce)))}).finally(()=>{ae===It.current&&X(!1)})},250);return()=>{window.clearTimeout(me),It.current+=1}},[Zt,Ot,J,i,He,R,t,u]);const ut=o.useMemo(()=>[...ve===0?[{id:"no-query-assignments",title:"Assign at least one query",detail:"Apply a tracked query to at least one Property before publishing.",tone:"negative"}]:[],...Pe?.authoring.assignments.some(U=>U.queryClass==="unclassified")&&!(Le&&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"}]:[],...C],[ve,Le,l,C,Pe]),es=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 it(U){let ae;try{ae=Vy(U)}catch(ce){v(os(ce,"Check the sitemap details and try again."));return}w(U),G("reviewing");const me=await yt("import",ce=>u.importSitemap(t,ce,ae),"Could not review this sitemap.");if(me?.draft){const ce=me.draft.authoring.targets.filter(Ue=>Ue.status==="proposed").map(Ue=>Ue.stableKey),Ie=me.draft.authoring.targets.filter(Ue=>Ue.status==="included").map(Ue=>Ue.stableKey);_([...Ie,...ce]),B(""),ne(fl),b("properties"),G("idle")}else G("error")}async function gs(U){if(!c||U.length===0||Ve)return[];Je("create-queries"),ct(null);try{return await c(U)}catch(ae){throw ct(St(ae)),ae}finally{Je(null)}}async function ps(U){if(!He||!R||Ve)return;const ae=new Set(U),ce=He.authoring.targets.filter(Ue=>Ue.status==="proposed"&&Ue.discoveryIdentity).map(Ue=>({discoveryIdentity:Ue.discoveryIdentity,action:ae.has(Ue.stableKey)?"create":"ignore"})),Ie=ce.length>0||He.authoring.targets.some(Ue=>Ue.status!=="proposed"&&Ue.status==="included"!==ae.has(Ue.stableKey));Je("properties"),v(null),pt(null);try{if(!Ie){_([...ae]),T({kind:"all"}),b("groups");return}await u.applySitemapSelection(t,R,ce,[...ae]);const Ue=await dt(),mt=Jr(Ue.draft);_(mt),T({kind:"all"}),b("groups")}catch(Ue){fn(Ue)?await ze("This setup changed in another session. The latest Properties are loaded."):v(os(Ue,"Could not save the selected Properties."))}finally{Je(null)}}async function Bs(U){const ae=U.groupIds&&U.groupIds.length>0?{groupKeys:Ys(U.groupIds),queryIds:Ys(U.queryIds)}:{targetKeys:Ys(U.propertyIds),queryIds:Ys(U.queryIds)};if(!E||re!==JSON.stringify(ae)||!R||E.draftEtag!==R){v("Review the latest assignment impact before assigning queries.");return}await yt("assignments",ce=>u.applyAssignments(t,ce,ae),"Could not apply these queries.")&&($([]),pe(`${E.assignments.added} new assignment${E.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function bt(U){if(U.propertyIds.length===0)return;await yt("replace-assignments",me=>u.replaceAssignments(t,me,{targetKeys:Rs(U.propertyIds),queryIds:[U.queryId]}),"Could not replace this query assignment.")&&($(me=>me.filter(ce=>ce!==U.queryId)),pe("Query assignments replaced."))}async function Vs(U,ae=!1){if(U.length===0)return;if(!await yt("paired-assignments",ce=>u.applyPairedAssignments(t,ce,[...U]),"Could not assign these queries.",{preserveBusyAction:ae}))throw new Error("Could not assign these queries.")}async function Mt(U){if(!(!i||!c||U.length===0||Ve)){Je("create-and-pair-questions"),ct(null);try{let ae;try{ae=await c(Rs(U.map(Ie=>Ie.text)))}catch(Ie){throw ct(St(Ie)),Ie}const me=new Map(ae.map(Ie=>[Ie.query,Ie.id])),ce=U.map(Ie=>({targetKey:Ie.propertyId,queryId:me.get(Ie.text)})).filter(Ie=>Ie.queryId!==void 0);if(ce.length!==U.length){const Ie=new Error("The created queries could not be matched to their Properties.");throw ct("The queries were added, but could not be paired with every Property. Try again to pair them."),Ie}try{await Vs(ce,!0)}catch(Ie){throw ct("The queries were added, but could not be assigned to their Properties. Try again to pair them."),Ie}}finally{Je(null)}}}async function as(U){if(!He)return;const ae=Rs(He.authoring.assignments.filter(ce=>ce.queryId===U).map(ce=>ce.targetKey));if(ae.length===0)return;await yt(`remove-${U}`,ce=>u.removeAssignment(t,ce,ae,U),"Could not clear this query assignment.")&&$(ce=>ce.filter(Ie=>Ie!==U))}async function Vt(U){if(!He||!R||Ve)return;const ae=U.name.trim();if(!ae)return;const me=ie??Ni(ae,"group"),ce=He.authoring.groups.find(kt=>kt.stableKey===me);if(ce&&ie===null){v(`A group named "${ce.label}" already exists. Edit it or choose a different name.`);return}const Ie=U.competitorDomains.split(/[\s,]+/).map(kt=>kt.trim()).filter(Boolean),Ue=Ie.find(kt=>vl(kt)===null);if(Ue){v(`"${Ue}" is not a valid competitor domain.`);return}const mt=Rs(Ie.map(kt=>vl(kt)));Je("group"),v(null),pt(null);try{const kt=await u.upsertGroup(t,R,{stableKey:me,label:ae,targetKeys:Rs(U.propertyIds),competitors:mt.map(q=>ce?.competitors.find(Se=>Se.domain===q)??{stableKey:Ni(q,"competitor"),label:q,domain:q,aliases:[]})}),vs=await dt();I(kt.warnings.map((q,Se)=>Zr(q,Se,vs.draft?.authoring))),Ae({...oa}),fe(null)}catch(kt){fn(kt)?await ze("This setup changed in another session. The latest groups are loaded."):v(os(kt,"Could not save this group."))}finally{Je(null)}}function xt(U){const ae=He?.authoring.groups.find(me=>me.stableKey===U);ae&&(fe(U),Ae({name:ae.label,propertyIds:[...ae.targetKeys],competitorDomains:ae.competitors.map(me=>me.domain).join(", ")}))}async function ts(U){await yt("remove-group",me=>u.removeGroup(t,me,U),"Could not remove this group.")&&(T(me=>me.kind==="groups"&&me.groupIds.includes(U)?{kind:"all"}:me),ie===U&&(fe(null),Ae({...oa})))}function zt(U){Ge(U),O(null),tt(null),vt(null)}async function fs(){if(!(!i||!Ce.trim()||D||Me)){H(!0),tt(null),vt(null);try{O(await u.previewGroupMembership(t,{csv:Ce}))}catch(U){O(null),tt(os(U,"Could not review this CSV."))}finally{H(!1)}}}async function Qt(U){if(!(!i||!R||!Ee||U.length===0||Ve)){if(Ee.draftEtag!==R){tt("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}Qe(!0),Je("group-import"),tt(null),vt(null),pt(null);try{const ae=await u.applyGroupMembership(t,R,{csv:Ce,sourceChecksum:Ee.sourceChecksum,previewChecksum:Ee.previewChecksum,acceptedRows:Rs(U.map(String)).map(Number)}),me=await dt();I(ae.warnings.map((ce,Ie)=>Zr(ce,Ie,me.draft?.authoring))),Ge(""),O(null),vt(`${ae.addedMemberships} membership${ae.addedMemberships===1?"":"s"} added${ae.unchangedMemberships>0?`; ${ae.unchangedMemberships} already present`:""}.`)}catch(ae){fn(ae)?(await ze("This setup changed in another session. The latest draft is loaded; review the CSV again."),tt("The setup changed while this CSV was open. Review the latest CSV before applying it.")):tt(os(ae,"Could not apply this CSV."))}finally{Je(null),Qe(!1)}}}async function gt(){if(!(!He||!R||Ve||ve===0)){Je("review"),v(null),pt(null);try{const[U,ae]=await Promise.all([u.compilePreview(t),u.diffPreview(t)]),me=[...U.checks,...ae.checks],ce=me.some(Ie=>Ie.ruleId==="active-revision-schema-v1");if(I(tb(me.filter(Ie=>Ie.ruleId!=="active-revision-schema-v1"),{authoring:Pe?.authoring,queries:s})),!U.ok||!ae.ok)return;if(ae.diff.activeRevision!==He.baseActiveRevision){await ze("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(U.compiledChecksum!==ae.compiledChecksum){v("The setup changed while it was being reviewed. Review the latest changes again.");return}pt({etag:R,baseActiveRevision:He.baseActiveRevision,compiledChecksum:U.compiledChecksum,changes:sb(ae.diff,ce),providerCalls:U.plan.executionNodes.reduce((Ie,Ue)=>Ie+Ue.expectedSnapshots,0)})}catch(U){v(os(U,"Could not review this setup."))}finally{Je(null)}}}async function Lt(){if(!(!He||!R||!at||Ve)){if(R!==at.etag||He.baseActiveRevision!==at.baseActiveRevision){pt(null),v("The setup changed after review. Review the latest changes before publishing.");return}Je("publish"),v(null);try{await u.publish(t,R,{expectedActiveRevision:at.baseActiveRevision,expectedCompiledChecksum:at.compiledChecksum}),y({draft:null,etag:null}),pt(null),m?.()}catch(U){fn(U)?await ze("The setup changed before it could be published. Review the latest draft and publish again."):v(os(U,"Could not publish this setup."))}finally{Je(null)}}}async function Nt(){if(!(!R||Ve)){Je("discard"),v(null);try{await u.discard(t,R),y({draft:null,etag:null}),pt(null),m?.()}catch(U){fn(U)?await ze("This setup changed in another session. The latest draft is loaded."):v(os(U,"Could not discard these changes."))}finally{Je(null)}}}async function ys(){if(!(!He||!R||!p||Ve)){Je("restart"),v(null),pt(null);try{await u.discard(t,R),await u.createDraft(t,p.activeRevision),w({...gl}),B(""),_([]),$([]),T({kind:"all"}),te(null),xe(null),pe(null),Ae({...oa}),fe(null),Ge(""),O(null),tt(null),vt(null),await Ke(!1)}catch(U){fn(U)?await ze("The setup changed again. Reloaded the latest draft and published setup."):v(os(U,"Could not restart this setup."))}finally{Je(null)}}}if(N)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-loading-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-loading-title",children:"Advanced measurement setup"})}),e.jsx("div",{className:"h-28 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement setup"})]});if(L)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-error-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-error-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:L}),e.jsx(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Ke(!0)},children:"Try again"})]})]});if(!Pe||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&&p&&He.baseActiveRevision!==p.activeRevision)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-stale-draft-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-stale-draft-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"This draft is based on an older published setup."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Restart from the latest setup before making more changes."}),e.jsx(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:Ve==="restart",onClick:()=>{ys()},children:Ve==="restart"?"Restarting…":"Discard draft and restart"})]}),g?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:g}):null]});const bs=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:r,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[p?.mode==="active-v1"?e.jsx("p",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-3 text-sm text-secondary",children:"Review and publish this setup to enable class-filtered reporting."}):null,g?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:g}):null,bs,f==="import"||f==="properties"?e.jsx(Xa,{currentStep:f,hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},importProperties:{importDraft:A,onImportDraftChange:U=>{w(U),G("idle"),v(null)},onReviewSitemap:U=>{it(U)},reviewState:V,properties:se,propertiesState:"ready",propertiesSearch:Q,onPropertiesSearchChange:B,maxVisibleProperties:z,onShowAllProperties:()=>ne(se.length),selectedPropertyIds:F,onSelectedPropertyIdsChange:U=>_([...U]),onContinue:U=>{ps(U)},isContinuing:Ve==="properties",onRetryProperties:()=>{dt()},onReturnToImport:()=>b("import")}}):f==="queries"?e.jsx(Xa,{currentStep:"queries",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},onManageProjectQueries:d,queries:{onCreateQueries:c?U=>gs(U):void 0,isCreatingQueries:Ve==="create-queries"||Ve==="create-and-pair-questions",isBusy:Ve!==null,createQueriesError:Dt,availability:es,properties:Re,queries:Tt,selectedQueryIds:Z,isApplying:Ve==="assignments"||Ve==="paired-assignments",onSelectedQueryIdsChange:U=>$([...U]),onApplySelectedQueries:U=>Bs(U),groups:Xt,audience:ee,onAudienceChange:U=>{T(U),pe(null)},assignmentImpact:E&&re===Ot&&E.draftEtag===R?ab(E):null,isPreviewingAssignmentImpact:we,assignmentImpactError:ue,onRetryAssignmentImpact:()=>he(U=>U+1),assignmentNotice:K,onReplaceAssignments:bt,isReplacingAssignments:Ve==="replace-assignments",onCreateAndPairQuestions:i&&c?Mt:void 0,onClearQueryAssignments:as,onRemoveQuery:as,canContinue:ve>0,onBack:()=>b("groups"),onContinue:()=>b("review")}}):f==="groups"?e.jsx(Xa,{currentStep:"groups",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},groups:{properties:Re,groups:Xt,groupDraft:qe,isSaving:Ve==="group",onGroupDraftChange:Ae,onSaveGroup:Vt,onEditGroup:U=>xt(U.id),onRemoveGroup:ts,onClearGroupDraft:()=>{fe(null),Ae({...oa})},membershipImport:{csv:Ce,preview:Ee,isReviewing:D,isApplying:Me,error:Fe,notice:ge,onCsvChange:zt,onReview:fs,onApply:Qt},onBack:()=>{b("properties")},onContinue:()=>b("queries")}}):e.jsx(Xa,{currentStep:"review",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},review:{counts:{properties:_e.length,queries:new Set(Pe.authoring.assignments.map(U=>U.queryId)).size,groups:Pe.authoring.groups.length,assignments:Pe.authoring.assignments.length,providerCalls:at?.providerCalls},flaggedExceptions:ut,reviewedChanges:at?.changes,isReviewing:Ve==="review",canReviewChanges:ve>0&&!Ve,onReviewChanges:gt,onBack:()=>b("queries"),canPublish:at!==null&&!Ve,isPublishing:Ve==="publish",onPublish:Lt}})]})}const ob=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function wl(t){return t.label!=="Complete"}const yn="__all_properties__",lb=50,ed=50,cb=20,db=50,ub=250,mb=5,hb=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],pb={"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"},td={plan_v1:"Setup update required.",no_completed_run:"Not measured yet.",no_population:"No matching queries.",evidence_incomplete:"Evidence incomplete.",identity_ambiguous:`${oo}.`,"identity-ambiguous":`${oo}.`,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."},xb={numerator:null,denominator:null,reason:"plan_v1"};function Gn(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 gb(t){return Gn(t)?`${t.numerator} of ${t.denominator} (${et(t.numerator/t.denominator)})`:"N/A"}function sd(t){if(Gn(t))return"";const s=t.reason??"unavailable";return td[s]??s}function Sl(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 fb(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function yb(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function bb(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function ma({metric:t,signal:s,compact:n=!1}){const a=n?Gn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Gn(t)?"text-lg font-semibold text-heading":"text-lg font-semibold text-secondary",r=Gn(t)?Pi(t,s):null;return e.jsxs("span",{className:"inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums",...Gn(t)?{}:{title:sd(t)},children:[e.jsx("span",{className:a,children:gb(t)}),r?e.jsx("span",{className:"text-xs text-secondary",children:r}):null]})}function Wi({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(P,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Cl({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,l]=o.useState(ed),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((c,d)=>e.jsx("li",{className:a,children:c},`${c}:${d}`))}),e.jsx(Wi,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>l(Number.MAX_SAFE_INTEGER)})]})]})}function vb({evidence:t,state:s="ready",onRetry:n}){const[a,r]=o.useState(ed),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(P,{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(Ne,{tone:i.tone,children:pb[i.kind]}),i.historical?e.jsx(Ne,{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(Wi,{shown:l.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function jb({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Cl,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Cl,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(vb,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function Nb({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(ma,{metric:s.coverage,signal:"mentioned",compact:!0})})]},s.name))})]})})]})}function kl({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function l(i){if(r)return;const c=n.findIndex(u=>u.value===s);let d=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?d=(c+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?d=(c-1+n.length)%n.length:i.key==="Home"?d=0:i.key==="End"&&(d=n.length-1),d===null)return;i.preventDefault();const m=n[d];a(m.value),i.currentTarget.querySelectorAll('[role="radio"]')[d].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:l,children:n.map(i=>{const c=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":c,tabIndex:c?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${c?"segmented-option-active":""}`,children:i.label},i.value)})})}function wb({outcomes:t}){const s=[{key:"both",count:t.bothSignals,label:"mentioned and cited",tone:"text-primary"},{key:"mentioned-only",count:t.mentionedOnly,label:"mentioned only",tone:"text-primary"},{key:"cited-only",count:t.citedOnly,label:"cited only",tone:"text-primary"},{key:"neither",count:t.neither,label:"neither signal",tone:"text-negative"},...t.notMeasured>0?[{key:"not-measured",count:t.notMeasured,label:"not measured",tone:"text-faint"}]:[]];return e.jsx("div",{"aria-label":"Property outcomes",className:"flex flex-wrap gap-x-8 gap-y-3 py-3",children:s.map(n=>e.jsxs("div",{className:"whitespace-nowrap",children:[e.jsx("p",{className:`font-mono text-xl font-semibold leading-none tabular-nums ${n.tone}`,children:n.count}),e.jsxs("p",{className:"mt-1 text-[13px] text-secondary",children:[n.label,n.key==="not-measured"?e.jsx(Oe,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function Sb({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:l=!1,isViewLoading:i=!1,isLoadingMore:c=!1,isLoadMoreError:d=!1,viewSearch:m,onViewChange:u,onLoadMore:p,onPropertyExpand:x,onRetryEvidence:h,renderPropertyLink:y}){const f=t.currentView!=null,b=t.classReporting==="available"&&(f||t.classScopes!=null),[N,k]=o.useState(t.currentView?.queryClass??"all"),[L,S]=o.useState(t.currentView?.scope.key??yn),[g,v]=o.useState(m??""),[C,I]=o.useState(lb),[A,w]=o.useState(cb),[V,G]=o.useState(t.currentView?.sort??"label-asc"),[Q,B]=o.useState(null),z=o.useRef(m??""),ne=b&&!f&&N!=="all"?N==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,F=f?{aggregate:t.currentView.aggregate,groups:[]}:ne,_=o.useCallback(O=>{if(!f||!u)return;const D=O.scope??(L===yn?"all":"group"),H=O.search??g;z.current=H,u({scope:D,...D==="group"?{groupKey:O.groupKey??L}:{},queryClass:O.queryClass??N,...H?{search:H}:{},...O.sort?{sort:O.sort}:{}})},[u,g,N,L,f]);o.useEffect(()=>{!t.currentView||i||(k(t.currentView.queryClass),S(t.currentView.scope.key??yn),t.currentView.sort&&G(t.currentView.sort))},[i,t.currentView]),o.useEffect(()=>{m!==void 0&&(z.current=m,v(O=>O.trim()===m.trim()?O:m))},[m]),o.useEffect(()=>{if(!f||!u||g===z.current)return;const O=window.setTimeout(()=>_({search:g}),ub);return()=>window.clearTimeout(O)},[u,_,g,f]);const Z=t.availableGroups??F.groups;o.useEffect(()=>{L===yn||Z.some(O=>O.id===L)||S(yn)},[Z,L]);const $=f?void 0:F.groups.find(O=>O.id===L),ee=$?.aggregate??F.aggregate,T=O=>b?O:xb,E=V,te=g.trim().toLocaleLowerCase(),re=o.useMemo(()=>!f&&te?ee.properties.filter(O=>O.name.toLocaleLowerCase().includes(te)):ee.properties,[ee.properties,te,f]),le=f?re:re.slice(0,C),we=(f?t.currentView?.scope.kind==="group":$!=null)&&N==="non-brand"&&b&&(f||$.confirmedCompetitorCount>0)&&(ee.shareOfVoice?.length??0)>0,X=b?ee.unavailablePropertyCount??0:0,ue=t.flaggedResults.reduce((O,D)=>O+(D.count??1),0),xe=t.flaggedResultsTotal??ue,J=[T(ee.metrics.propertiesMentioned),T(ee.metrics.mentionCoverage),T(ee.metrics.citationCoverage)].map(sd).find(Boolean),he=b?t.nextActionText??J??(X>0?`${X} ${X===1?"property is":"properties are"} unavailable.`:xe>0?`${xe} flagged ${xe===1?"result needs":"results need"} review.`:null):td.plan_v1,qe=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?fb(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Ae=yb(t.latestMeasurement.date),ie=[{value:yn,label:"All properties"},...Z.map(O=>({value:O.id,label:O.label}))],fe=Z.length>mb;function Ce(O){S(O),_(O===yn?{scope:"all"}:{scope:"group",groupKey:O})}function Ge(O){k(O),_({queryClass:O})}function Ee(O){const D=Q!==O;B(D?O:null),D&&x?.(O)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":i,className:"space-y-5",children:[e.jsx("header",{className:"border-b border-default pb-4",children:e.jsx("div",{role:"status","aria-label":"Measurement status and next action",className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:i?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(Ne,{tone:"caution",children:"Includes historical data"}):null,qe?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:qe}):null,Ae?e.jsx("span",{className:"text-sm text-secondary",children:Ae}):null,he?e.jsx("span",{className:"text-sm text-secondary",children:he}):null,s&&b&&n?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!b?e.jsx(P,{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:fe?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),fe?e.jsx("select",{id:"advanced-measurement-group",value:L,onChange:O=>Ce(O.target.value),className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-mono-400",children:ie.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))}):e.jsx(kl,{ariaLabelledBy:"advanced-measurement-group-label",value:L,options:ie,onChange:Ce})]}),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(kl,{ariaLabelledBy:"advanced-measurement-class-label",value:N,options:hb,onChange:Ge,disabled:!b})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:g,onChange:O=>v(O.target.value),placeholder:"Search properties",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]})]}),!i&&we?e.jsx(Nb,{values:ee.shareOfVoice??[]}):null,i?e.jsx("div",{className:"h-44 animate-pulse rounded-md bg-surface-subtle","aria-label":"Updating Property results"}):e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-title",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{id:"advanced-measurement-properties-title",className:"text-base font-semibold text-heading",children:["Properties",e.jsx(Oe,{text:"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??re.length," ",(t.currentView?.propertyTotal??re.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(wb,{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:[ob.map(O=>{const D=E.startsWith(`${O.key}-`),H=D&&E.endsWith("-desc")?"descending":D?"ascending":"none";return e.jsx("th",{"aria-sort":H,className:(O.numeric,void 0),children:u?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const Me=`${O.key}-${D&&E.endsWith("-asc")?"desc":"asc"}`;G(Me),_({sort:Me})},"aria-label":`Sort by ${O.label.toLowerCase()}`,children:[O.label,e.jsx(Qn,{className:`h-3 w-3 transition-transform ${D?"opacity-100":"opacity-0"} ${H==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):O.label},O.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[le.map(O=>{const D=Q===O.id;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:H=>{bb(H.target)||Ee(O.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[y?y({id:O.id,name:O.name}):O.name,wl(O.status)||O.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[wl(O.status)?e.jsx(Ne,{tone:O.status.tone,children:O.status.label}):null,O.historical?e.jsx(Ne,{tone:"caution",children:"Historical"}):null]}):null,Sl(O)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Sl(O)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(ma,{metric:O.mentionCoverage,signal:"mentioned",compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(ma,{metric:O.citationCoverage,signal:"cited",compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{size:"icon",variant:"ghost","aria-expanded":D,"aria-label":D?`Hide details for ${O.name}`:`Show details for ${O.name}`,onClick:()=>Ee(O.id),children:e.jsx(Qn,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${D?"rotate-180":""}`,"aria-hidden":"true"})})})]},O.id),D?(O.providers??[]).map(H=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:H.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(ma,{metric:H.mentionCoverage,signal:"mentioned",compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(ma,{metric:H.citationCoverage,signal:"cited",compact:!0})}),e.jsx("td",{})]},`${O.id}:${H.provider}`)):null,D?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(jb,{property:O,onRetryEvidence:h})})},`${O.id}:details`):null]},O.id)}),le.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]})]})}),f&&t.currentView.nextCursor&&p?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",le.length," of ",t.currentView.propertyTotal]}),d?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(P,{size:"sm",variant:"outline",disabled:c,onClick:()=>p(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more properties":"Show 50 more"})]}):f?le.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",le.length," of ",t.currentView.propertyTotal]}):null:e.jsx(Wi,{shown:le.length,total:re.length,itemLabel:"properties",onShowAll:()=>I(Number.MAX_SAFE_INTEGER)})]}),!i&&!te&&xe>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 (",xe,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,A).map(O=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(Ne,{tone:O.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:O.property}),e.jsx("span",{className:"text-secondary",children:O.summary})]},O.id))}),A<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,A).reduce((O,D)=>O+(D.count??1),0)," of ",xe," flagged results"]}),e.jsx(P,{size:"sm",variant:"outline",onClick:()=>w(O=>Math.min(t.flaggedResults.length,O+db)),children:"Show 50 more"})]}):ue<xe?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",ue," of ",xe," flagged results"]}),f&&t.currentView.nextCursor&&p?e.jsx(P,{size:"sm",variant:"outline",disabled:c,onClick:()=>p(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function nd(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function Cb(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 kb({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:l,onRunMeasurement:i,onRetryReport:c,onViewChange:d,onLoadMore:m,onPropertyExpand:u,onRetryEvidence:p,renderPropertyLink:x,isRunningMeasurement:h,isOpeningSetup:y,isViewLoading:f,isLoadingMore:b,isLoadMoreError:N,viewSearch:k}){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(P,{type:"button",size:"sm",disabled:y,onClick:l,children:y?"Opening setup…":nd(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,r==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):r==="error"&&!a?e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load the advanced measurement report."}),c?e.jsx(P,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:c,children:"Retry report"}):null]}):a?e.jsx(Sb,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:l,onViewChange:d,onLoadMore:m,onPropertyExpand:u,onRetryEvidence:p,renderPropertyLink:x,isRunningMeasurement:h,isRepublishingSetup:y,isViewLoading:f,isLoadingMore:b,isLoadMoreError:N,viewSearch:k}):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 Dn={numerator:null,denominator:null,reason:"plan_v1"};function Ab(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Al(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator,...t.unattributed===void 0?{}:{unattributed:t.unattributed},...t.unchecked===void 0?{}:{unchecked:t.unchecked}}}function Rb(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function Pb(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Ib(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 Tb(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function Mb(t){const s=new Map;for(const n of t){const a=Tb(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function Lb(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 f=l.get(y.targetKey)??[];f.push(...y.queryIds.map(b=>r.get(b)).filter(b=>!!b)),l.set(y.targetKey,[...new Set(f)])}const i=Mb(s.evidence),c=n.executionNodes.reduce((y,f)=>y+f.expectedSnapshots,0),d=s.run?.status==="completed"&&c>0,m=d?c:0,u=d?c:0,p=s.targets.map(y=>{const f=a.get(y.id),b=i.get(y.id)??[],N=b.map(S=>({id:`${S.observationId}:${S.usageEdgeId}:${S.sourceUrl}`,kind:Rb(S.classification),query:S.queryText,url:S.sourceUrl,tone:Pb(S.classification),historical:S.historical||S.bridged})),k=b.some(S=>S.historical||S.bridged),L=s.run?y.completeness.complete?f?.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:Al(y.mentionCoverage),citationCoverage:Al(y.citationCoverage),status:L,assignedQueries:l.get(y.id)??[],urls:f?.urls.map(Ab)??[],evidence:N,historical:k}}),x=new Map(p.map(y=>[y.id,y])),h=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:Ib(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Dn,mentionCoverage:Dn,citationCoverage:Dn},properties:p},groups:s.groups.map(y=>({id:y.id,label:y.label,confirmedCompetitorCount:h.get(y.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Dn,mentionCoverage:Dn,citationCoverage:Dn},properties:y.targetIds.map(f=>x.get(f)).filter(f=>!!f)}}))},flaggedResults:[]}}function $b({project:t,onUpdateProject:s}){const[n,a]=o.useState(!1),[r,l]=o.useState(!1),[i,c]=o.useState(null),[d,m]=o.useState(t.displayName),[u,p]=o.useState(t.canonicalDomain),[x,h]=o.useState(t.country),[y,f]=o.useState(t.language),[b,N]=o.useState(t.ownedDomains??[]),[k,L]=o.useState(""),[S,g]=o.useState(t.aliases??[]),[v,C]=o.useState(""),[I,A]=o.useState(null),[w,V]=o.useState(!1),[G,Q]=o.useState(!1),[B,z]=o.useState(""),[ne,F]=o.useState(""),[_,Z]=o.useState(""),[$,ee]=o.useState(""),[T,E]=o.useState(""),[te,re]=o.useState(null),[le,we]=o.useState(null);o.useEffect(()=>{n||(m(t.displayName),p(t.canonicalDomain),h(t.country),f(t.language),N(t.ownedDomains??[]),g(t.aliases??[]))},[t,n]);function X(){a(!1),c(null),m(t.displayName),p(t.canonicalDomain),h(t.country),f(t.language),N(t.ownedDomains??[]),g(t.aliases??[]),L(""),C("")}function ue(){const D=k.trim();D&&(b.includes(D)||N([...b,D]),L(""))}function xe(D){N(b.filter(H=>H!==D))}function J(){const D=v.trim();if(!D)return;const H=D.toLowerCase();S.some(Me=>Me.toLowerCase()===H)||g([...S,D]),C("")}function he(D){g(S.filter(H=>H!==D))}async function K(){if(!(!d.trim()||!u.trim()||!x.trim()||!y.trim())){l(!0),c(null);try{await s(t.name,{displayName:d.trim(),canonicalDomain:u.trim(),ownedDomains:b,aliases:S,country:x.trim(),language:y.trim()}),a(!1),De({title:"Project settings saved",detail:`${d.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(D){c(D instanceof Error?D.message:"Failed to save")}finally{l(!1)}}}async function pe(){const D=B.trim(),H=ne.trim(),Me=_.trim(),Qe=$.trim();if(!(!D||!H||!Me||!Qe)){V(!0),A(null);try{const Fe={label:D,city:H,region:Me,country:Qe};T.trim()&&(Fe.timezone=T.trim()),await vm(t.name,Fe),z(""),F(""),Z(""),ee(""),E(""),Q(!1),De({title:"Location added",detail:`${D} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${D}`,dedupeMode:"drop"})}catch(Fe){A(Fe instanceof Error?Fe.message:"Failed to add location")}finally{V(!1)}}}async function qe(D){V(!0),A(null);try{await bm(t.name,D),De({title:"Location removed",detail:`${D} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${D}`,dedupeMode:"drop"})}catch(H){A(H instanceof Error?H.message:"Failed to remove location")}finally{V(!1)}}async function Ae(D){V(!0),A(null);try{await ym(t.name,D),De({title:"Default location updated",detail:`${D} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(H){A(H instanceof Error?H.message:"Failed to set default location")}finally{V(!1)}}async function ie(D){re(D),we(null);try{await jm(t.name,D),De({title:`${D.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(H){we(H instanceof Error?H.message:"Could not download tracking results.")}finally{re(null)}}const fe=d!==t.displayName||u!==t.canonicalDomain||x!==t.country||y!==t.language||JSON.stringify(b)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(S)!==JSON.stringify(t.aliases??[]),Ce=!oe()&&!Ls(),Ge="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",Ee="mb-1 block text-sm font-medium text-secondary",O=B.trim()&&ne.trim()&&_.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"})]}),Ce&&!n&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>a(!0),children:"Edit settings"})]}),i&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[i,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>c(null),children:"×"})]}),Ce&&n?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:Ee,children:"Display name"}),e.jsx("input",{className:Ge,type:"text",value:d,onChange:D=>m(D.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ee,children:"Canonical domain"}),e.jsx("input",{className:Ge,type:"text",value:u,onChange:D=>p(D.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ee,children:"Country"}),e.jsx("input",{className:Ge,type:"text",value:x,onChange:D=>h(D.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ee,children:"Language"}),e.jsx("input",{className:Ge,type:"text",value:y,onChange:D=>f(D.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ee,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:b.map(D=>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:[D,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>xe(D),"aria-label":`Remove ${D}`,children:"×"})]},D))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ge} flex-1`,type:"text",placeholder:"docs.example.com",value:k,onChange:D=>L(D.target.value),onKeyDown:D=>D.key==="Enter"&&(D.preventDefault(),ue())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!k.trim(),onClick:ue,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ee,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:S.map(D=>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:[D,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>he(D),"aria-label":`Remove ${D}`,children:"×"})]},D))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ge} flex-1`,type:"text",placeholder:"Facebook",value:v,onChange:D=>C(D.target.value),onKeyDown:D=>D.key==="Enter"&&(D.preventDefault(),J())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!v.trim(),onClick:J,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(P,{type:"button",disabled:r||!fe||!d.trim()||!u.trim(),onClick:Ze(K),children:r?"Saving...":"Save changes"}),e.jsx(P,{type:"button",variant:"outline",disabled:r,onClick:X,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-default bg-surface overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(D=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:D},D))}):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(D=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:D},D))}):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(D=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:D},D))})})]}):null,e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[I&&e.jsxs("div",{className:"mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-xs text-negative",children:[I,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>A(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(D=>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 ${D.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[D.label,D.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:D.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:D.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:D.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:D.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ce&&D.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:w,onClick:()=>{Ae(D.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${D.label} as default location`,children:"Set default"}),Ce&&e.jsx("button",{type:"button",disabled:w,onClick:()=>{qe(D.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${D.label}`,children:"Remove"})]})})]},D.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),Ce?G?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:Ge,type:"text",value:B,onChange:D=>z(D.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:Ge,type:"text",value:ne,onChange:D=>F(D.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:Ge,type:"text",value:_,onChange:D=>Z(D.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:Ge,type:"text",value:$,onChange:D=>ee(D.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:Ge,type:"text",value:T,onChange:D=>E(D.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(P,{type:"button",size:"sm",disabled:w||!O,onClick:Ze(pe),children:w?"Adding...":"Add location"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:w,onClick:()=>{Q(!1),A(null)},children:"Cancel"})]})]}):e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>Q(!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(P,{type:"button",variant:"outline",size:"sm",disabled:te!==null,onClick:Ze(()=>ie("csv")),children:te==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:te!==null,onClick:Ze(()=>ie("json")),children:te==="json"?"Preparing JSON...":"Download JSON"})]})]}),le&&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:le})]})]})]})}function la(t){return{...t??{}}}function qb(t,s){const n=Object.entries(t).sort(([r],[l])=>r.localeCompare(l)),a=Object.entries(s).sort(([r],[l])=>r.localeCompare(l));return n.length===a.length&&n.every(([r,l],i)=>{const c=a[i];return c?.[0]===r&&c[1]===l})}function Eb({project:t,onSave:s}){const{isAdmin:n}=nn(),a=$e({queryKey:["settings"],queryFn:Gl,staleTime:6e4,enabled:n&&!oe()}),[r,l]=o.useState(t.providers.length===0),[i,c]=o.useState(t.providers),[d,m]=o.useState(()=>la(t.providerModels)),[u,p]=o.useState({providers:t.providers,providerModels:la(t.providerModels)}),[x,h]=o.useState(!1),[y,f]=o.useState(!1),[b,N]=o.useState(null),[k,L]=o.useState(null),S=o.useRef(null),g=a.data?.providerCatalog??[],v=o.useMemo(()=>new Set((a.data?.providers??[]).filter(B=>B.configured).map(B=>B.name)),[a.data]),C=o.useMemo(()=>{const B=new Map(a.data?.providers.map(ne=>[ne.name,ne.model])),z=new Map(g.map(ne=>[ne.name,{...ne,defaultModel:B.get(ne.name)||ne.defaultModel}]));for(const ne of Object.keys(d))z.has(ne)||z.set(ne,{name:ne,displayName:ne,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...z.values()].sort((ne,F)=>ne.displayName.localeCompare(F.displayName))},[g,d,a.data?.providers]),I=!qb(d,u.providerModels);o.useEffect(()=>{if(x||y)return;const B={providers:t.providers,providerModels:la(t.providerModels)};p(B),l(B.providers.length===0),c(B.providers),m(B.providerModels)},[t]);function A(){f(!0),l(!1),i.length===0&&c([...v])}function w(B,z,ne=!1){f(!0),m(F=>{const _={...F};return z==="__inherit__"?delete _[B]:z==="__custom__"?_[B]=ne?"":_[B]??"":_[B]=z,_}),z==="__custom__"&&queueMicrotask(()=>S.current?.focus())}function V(B,z){f(!0),c(ne=>z?[...new Set([...ne,B])]:ne.filter(F=>F!==B))}function G(){f(!1),l(u.providers.length===0),c(u.providers),m(la(u.providerModels)),N(null),L(null)}async function Q(){if(!(a.isError||a.isLoading||!r&&i.length===0)){h(!0),N(null),L(null);try{const B=Object.fromEntries(Object.entries(d).filter(([ne,F])=>F.trim()!==""&&(r||i.includes(ne)))),z={providers:r?[]:i,providerModels:B};await s(z),p({providers:[...z.providers],providerModels:la(z.providerModels)}),f(!1),L("Engine settings saved. They apply on the next sweep.")}catch(B){N(fa(B))}finally{h(!1)}}}return oe()||!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(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):g.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(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):v.size===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsxs("p",{className:"text-sm text-secondary",children:["Configure an answer engine in ",e.jsx(Ms,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":x,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:x,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:r,onChange:()=>{f(!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:A})," Choose engines"]}),!r&&e.jsx("div",{className:"project-engine-list",children:C.map(B=>{const z=i.includes(B.name),ne=v.has(B.name),F=z&&!ne,_=d[B.name],Z=B.knownModels.some(ee=>ee.id===_),$=_===void 0?"__inherit__":Z?_:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:z,disabled:!ne&&!z,onChange:ee=>V(B.name,ee.target.checked)})," ",e.jsx("span",{children:B.displayName}),F&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),z&&(B.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${B.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${B.name}`,value:$,onChange:ee=>w(B.name,ee.target.value,Z),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",B.defaultModel||"default"]}),B.knownModels.map(ee=>e.jsx("option",{value:ee.id,children:ee.displayName},ee.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),$==="__custom__"&&e.jsx("input",{ref:S,"aria-label":`${B.displayName} custom model ID`,value:_??"",onChange:ee=>{f(!0),m(T=>({...T,[B.name]:ee.target.value}))},"aria-describedby":`project-model-hint-${B.name}`}),e.jsxs("p",{id:`project-model-hint-${B.name}`,className:"project-engine-help",children:[_?"Project override":"Inherited from instance settings",". ",B.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},B.name)})})]}),!r&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),b&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:b}),k&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:k}),I&&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(P,{type:"button",onClick:()=>{Q()},disabled:x||!r&&i.length===0,children:x?"Saving engines…":"Save engines"}),e.jsx(P,{type:"button",variant:"outline",onClick:G,disabled:x,children:"Cancel"})]})]})}const As={heading:"Site Health scans",help:`Used by every scan that sets no budget, scheduled or manual. Onboarding's first look always checks ${$h(Sm)}.`,pageBudget:"Page budget",customOption:"Custom number...",customLabel:"Custom page budget",customError:`Enter a whole number from 1 to ${Jl.toLocaleString("en-US")}.`,save:"Save page budget",saving:"Saving page budget…",saved:"Page budget saved."},Yi="full",Kn="custom";function er(t){return t===null?{choice:Yi,customText:""}:ic.some(s=>s.value===t)?{choice:String(t),customText:""}:{choice:Kn,customText:String(t)}}function Db({choice:t,customText:s}){if(t===Yi)return null;if(t!==Kn)return Number(t);const n=s.trim();if(n==="")return;const a=wm.safeParse(Number(n));return a.success?a.data:void 0}function Ob({project:t,onSave:s}){const{canWrite:n,isAdmin:a}=nn(),r=n&&!oe()&&!Ls()&&(!Nm(Us["site-audit"])||a),l=t.siteAuditMaxPages??null,[i,c]=o.useState(l),[d,m]=o.useState(()=>er(l)),[u,p]=o.useState(!1),[x,h]=o.useState(!1),[y,f]=o.useState(!1),[b,N]=o.useState(null),[k,L]=o.useState(null),S=o.useRef(null),g=o.useId(),v=`${g}-heading`,C=`${g}-page-budget`,I=`${g}-custom-page-budget`,A=`${g}-custom-page-budget-error`;o.useEffect(()=>{y||x||(c(l),m(er(l)))},[l]);const w=Db(d),G=d.choice===Kn&&w===void 0&&(u||d.customText.trim()!==""),Q=w!==void 0&&w!==i;function B(Z){h(!0),N(null),L(null),m($=>({...$,choice:Z})),Z===Kn&&(p(!1),queueMicrotask(()=>S.current?.focus()))}function z(Z){h(!0),N(null),L(null),p(!0),m($=>({...$,customText:Z}))}function ne(){h(!1),m(er(i)),p(!1),N(null),L(null)}async function F(){if(!(y||w===void 0)){f(!0),N(null),L(null);try{await s(w),c(w),m(er(w)),p(!1),h(!1),L(As.saved)}catch(Z){N(fa(Z))}finally{f(!1)}}}const _="h-9 w-full rounded-md border border-base bg-bg px-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600 disabled:opacity-60";return e.jsxs("section",{className:"project-engine-settings","aria-labelledby":v,"aria-busy":y,children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:v,children:As.heading}),e.jsx(Oe,{text:As.help})]})}),r?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid max-w-sm gap-1",children:[e.jsx("label",{htmlFor:C,className:"text-sm font-medium text-heading",children:As.pageBudget}),e.jsxs("select",{id:C,value:d.choice,disabled:y,onChange:Z=>B(Z.target.value),className:_,children:[e.jsx("option",{value:Yi,children:Mh}),ic.map(Z=>e.jsx("option",{value:String(Z.value),children:Z.label},Z.value)),e.jsx("option",{value:Kn,children:As.customOption})]}),d.choice===Kn&&e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:I,className:"mt-2 text-sm font-medium text-heading",children:As.customLabel}),e.jsx("input",{ref:S,id:I,type:"number",inputMode:"numeric",min:1,max:Jl,step:1,value:d.customText,disabled:y,"aria-invalid":G,"aria-describedby":G?A:void 0,onChange:Z=>z(Z.target.value),className:_}),G&&e.jsx("p",{id:A,role:"alert",className:"text-sm text-negative",children:As.customError})]})]}),b&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:b}),k&&e.jsx("p",{role:"status",className:"mt-3 text-sm text-positive",children:k}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsx(P,{type:"button",onClick:()=>{F()},disabled:y||!Q,children:y?As.saving:As.save}),e.jsx(P,{type:"button",variant:"outline",onClick:ne,disabled:y||!x,children:"Cancel"})]})]}):e.jsxs("p",{className:"text-sm text-secondary",children:[As.pageBudget,": ",e.jsx("span",{className:"text-strong",children:Lh(i)})]})]})}const tr={edit:"Edit schedule",pause:"Pause",resume:"Resume",save:"Save schedule"},Fb=[{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"}],Rl=["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 ei(t,s){const n=s==="UTC"?"UTC":s.split("/").pop()?.replace(/_/g," ")??s,a=new Date(`${t.startDate}T00:00:00Z`),r=Number.isNaN(a.getTime())?t.startDate:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(a),[l,i]=t.time.split(":").map(Number),c=Number.isInteger(l)&&Number.isInteger(i)?new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",timeZone:"UTC"}).format(new Date(Date.UTC(1970,0,1,l,i))):t.time;return`Every ${t.everyDays} days starting ${r} at ${c} · ${n}`}function Gb({projectName:t}){const s=ds(),n=!oe()&&!Ls()&&!s,a=hs(),[r,l]=o.useState(!1),[i,c]=o.useState("daily"),[d,m]=o.useState(6),[u,p]=o.useState(""),[x,h]=o.useState(14),[y,f]=o.useState(""),[b,N]=o.useState("00:00"),[k,L]=o.useState("UTC"),[S,g]=o.useState(!1),[v,C]=o.useState(""),[I,A]=o.useState(!1),[w,V]=o.useState(!1),[G,Q]=o.useState(null),[B,z]=o.useState(void 0),ne=Cm({client:Y,path:{name:t}}),F=$e({...Xl({client:Y,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),_=F.isPending||F.isFetching,Z=F.isError,$=F.data?.find(J=>J.kind==="answer-visibility")??null,ee=r&&B!==void 0&&($?.updatedAt??null)!==B,T=J=>{a.setQueryData(ne,he=>{const K=(he??[]).filter(pe=>pe.kind!=="answer-visibility");return J?[...K,J]:K})},E=J=>{if(J){if(J.recurrence)c("calendar"),h(J.recurrence.everyDays),f(J.recurrence.startDate),N(J.recurrence.time);else{const K=Im(J.preset??null,J.cronExpr);c(K.freq),m(K.hour),p(K.customCron)}const he=Rl.includes(J.timezone);L(he?J.timezone:"Other"),g(!he),C(he?"":J.timezone)}else c("daily"),m(6),p(""),h(14),f(""),N("00:00"),L("UTC"),g(!1),C("");z(J?.updatedAt??null)},te=()=>{n&&(E($),Q(null),l(!0))},re=()=>{E($),Q(null)},le=async()=>{(await F.refetch()).isError?Q("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):Q(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},we=async(J,he)=>{if(J instanceof Vn&&J.code==="SCHEDULE_VERSION_CONFLICT"){await le();return}Q(J instanceof Error?J.message:he)},X=async()=>{if(n&&!(ee||B===void 0)){A(!0),Q(null);try{const J=await F.refetch();if(J.isError||J.data===void 0){Q("Canonry could not verify the latest schedule. Try again before saving.");return}const he=J.data.find(Ae=>Ae.kind==="answer-visibility")??null;if((he?.updatedAt??null)!==B)return;const pe={timezone:S?v.trim()||"UTC":k,enabled:he?.enabled??!0,providers:he?.providers??[],expectedUpdatedAt:B};i==="calendar"?pe.recurrence={everyDays:x,startDate:y,time:b}:i==="custom"?pe.cron=u.trim():pe.preset=Pm(i,d);const qe=await lo(t,pe);l(!1),z(void 0),T(qe),De({title:"Schedule saved",detail:qe.recurrence?ei(qe.recurrence,qe.timezone):kr(qe.preset??null,qe.cronExpr,qe.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(J){await we(J,"Failed to save schedule")}finally{A(!1)}}},ue=async()=>{if(!n||!$)return;const J=$.updatedAt;A(!0),Q(null);try{const he=await F.refetch();if(he.isError||he.data===void 0){Q("Canonry could not verify the latest schedule. Try again before updating it.");return}const K=he.data.find(Ae=>Ae.kind==="answer-visibility")??null;if(!K||K.updatedAt!==J){Q("This schedule changed elsewhere. Review the latest version and try again.");return}const pe={timezone:K.timezone,enabled:!K.enabled,providers:K.providers,expectedUpdatedAt:J};K.recurrence?pe.recurrence=K.recurrence:K.preset?pe.preset=K.preset:pe.cron=K.cronExpr;const qe=await lo(t,pe);T(qe),De({title:qe.enabled?"Schedule resumed":"Schedule paused",detail:qe.recurrence?ei(qe.recurrence,qe.timezone):kr(qe.preset??null,qe.cronExpr,qe.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(he){await we(he,"Failed to update schedule")}finally{A(!1)}},xe=async()=>{if(!n||!$)return;const J=$.updatedAt;V(!0),Q(null);try{await Rm(t,J),T(null),l(!1),z(void 0),De({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(he){await we(he,"Failed to remove schedule")}finally{V(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),n&&!_&&!Z&&!r&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:te,children:$?tr.edit:"+ Set schedule"})]}),_&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),G&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:G}),!_&&Z&&e.jsxs(je,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{F.refetch()},children:"Retry"})]}),!_&&!Z&&!r&&$===null&&e.jsx(je,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?zn:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!_&&!Z&&!r&&$!==null&&e.jsx(je,{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:zn}),e.jsx("p",{className:"text-sm font-medium text-strong",children:$.recurrence?ei($.recurrence,$.timezone):kr($.preset??null,$.cronExpr,$.timezone)}),!$.recurrence&&e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:$.cronExpr})]}),$.enabled&&$.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",km($.nextRunAt,$.timezone)]}),$.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date($.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(Ne,{tone:$.enabled?"positive":"neutral",children:$.enabled?"Active":"Paused"}),n&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:I,onClick:Ze(ue),children:$.enabled?tr.pause:tr.resume}),n&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:w,onClick:Ze(xe),children:w?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[ee&&!I&&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(P,{type:"button",variant:"outline",size:"sm",onClick:re,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:J=>c(J.target.value),children:Fb.map(J=>e.jsx("option",{value:J.value,children:J.label},J.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:J=>m(parseInt(J.target.value)),children:Array.from({length:24},(J,he)=>e.jsx("option",{value:he,children:Am(he)},he))})]})]}),i==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:u,onChange:J=>p(J.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:x,onChange:J=>h(Number(J.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:J=>f(J.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Recurrence time",type:"time",value:b,onChange:J=>N(J.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:S?"Other":k,onChange:J=>{J.target.value==="Other"?(g(!0),L("Other")):(g(!1),L(J.target.value))},children:[Rl.map(J=>e.jsx("option",{value:J,children:J},J)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),S&&e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:v,onChange:J=>C(J.target.value)})]}),G&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:G}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{l(!1),z(void 0),Q(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:I||F.isFetching||Z||ee||i==="custom"&&!u.trim()||i==="calendar"&&(!Number.isInteger(x)||x<1||x>3650||!y||!b),onClick:Ze(X),children:I?"Saving...":tr.save})]})]})]})}const Kb=[{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 _b({projectName:t}){const[s,n]=o.useState("loading"),[a,r]=o.useState(!1),[l,i]=o.useState(""),[c,d]=o.useState(["citation.lost","citation.gained"]),[m,u]=o.useState(!1),[p,x]=o.useState(null),[h,y]=o.useState({}),[f,b]=o.useState(new Set),N=!oe()&&!Ls();o.useEffect(()=>{Tm(t).then(n).catch(()=>n([]))},[t]);const k=v=>{d(C=>C.includes(v)?C.filter(I=>I!==v):[...C,v])},L=async()=>{if(!(!l.trim()||c.length===0)){u(!0),x(null);try{const v=await Mm(t,{channel:"webhook",url:l.trim(),events:c});n(C=>C==="loading"?[v]:[...C,v]),i(""),d(["citation.lost","citation.gained"]),r(!1),De({title:"Webhook added",detail:`Notifications will be sent to ${v.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(v){x(v instanceof Error?v.message:"Failed to add webhook")}finally{u(!1)}}},S=async v=>{if(!f.has(v)){b(C=>new Set(C).add(v));try{await $m(t,v),n(C=>C==="loading"?C:C.filter(I=>I.id!==v)),De({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${v}`,dedupeMode:"drop"})}catch(C){x(C instanceof Error?C.message:"Failed to remove webhook")}finally{b(C=>{const I=new Set(C);return I.delete(v),I})}}},g=async v=>{y(C=>({...C,[v]:{state:"testing"}}));try{const C=await Lm(t,v);y(I=>({...I,[v]:{state:C.ok?"ok":"fail",status:C.status}})),C.ok&&De({title:"Test notification sent",detail:`Webhook returned status ${C.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${v}`,dedupeMode:"replace"})}catch{y(C=>({...C,[v]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),N&&s!=="loading"&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),x(null)},children:a?"Cancel":"+ Add webhook"})]}),N&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:l,onChange:v=>i(v.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Kb.map(v=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:c.includes(v.value),onChange:()=>k(v.value)}),e.jsx("span",{className:"text-sm text-neutral",children:v.label})]},v.value))})]}),p&&e.jsx("p",{className:"text-negative-400 text-sm",children:p}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),x(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:m||!l.trim()||c.length===0,onClick:Ze(L),children:m?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(je,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-neutral break-all",title:v.urlHost,children:v.urlDisplay??v.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:v.events.map(C=>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:C.replace("."," ")},C))})}),e.jsx("td",{children:e.jsx(Ne,{tone:v.enabled?"positive":"neutral",children:v.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[h[v.id]&&(()=>{const C=h[v.id],I=C.state==="testing"?"Sending…":C.state==="ok"?`Delivered${C.status?` (${C.status})`:""}`:`Failed${C.status?` (${C.status})`:""}`;return e.jsx(Ne,{tone:C.state==="ok"?"positive":C.state==="fail"?"negative":"neutral",children:I})})(),N&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:h[v.id]?.state==="testing",onClick:()=>{g(v.id)},children:"Test"}),N&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:f.has(v.id),onClick:()=>{S(v.id)},children:f.has(v.id)?"Removing…":"Remove"})]})})]},v.id))})]}),p&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:p})]})]})}function Ub({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:l}){return oe()||ds()?null:e.jsx(Em,{open:t,onOpenChange:n,children:e.jsxs(Dm,{onCloseAutoFocus:i=>{r&&(i.preventDefault(),r())},children:[e.jsxs(Om,{children:[e.jsx(Fm,{children:"Run AI sweep for the whole project?"}),e.jsxs(Gm,{children:["Runs all tracked queries for ",s,". View filters do not limit the sweep. Provider charges apply."]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsx(P,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(Ye,{disabled:l,onClick:a,children:"Run project-wide sweep"})]})]})})}const Pl=2e3,Il=3e5;function Bb(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Vb(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 zb({projectName:t,refreshNonce:s}){const n=hs(),[a,r]=o.useState(null),[l,i]=o.useState([]),[c,d]=o.useState(null),[m,u]=o.useState([]),[p,x]=o.useState([]),[h,y]=o.useState(null),[f,b]=o.useState(""),[N,k]=o.useState(""),[L,S]=o.useState(""),[g,v]=o.useState(!0),[C,I]=o.useState(!1),[A,w]=o.useState(null),[V,G]=o.useState("performance");o.useEffect(()=>{Q()},[t,s]);async function Q(){v(!0),w(null);try{const T=await n.fetchQuery({...ac({client:Y,path:{name:t}}),staleTime:Yt});if(r(T),T.connected){const[E,te,re,le]=await Promise.all([n.fetchQuery({...Sh({client:Y,path:{name:t}}),staleTime:Yt}).catch(()=>null),n.fetchQuery({...Ch({client:Y,path:{name:t}}),staleTime:Yt}).catch(()=>[]),n.fetchQuery({...kh({client:Y,path:{name:t}}),staleTime:Yt}).catch(()=>[]),T.siteUrl?Promise.resolve([]):n.fetchQuery({...Ah({client:Y,path:{name:t}}),staleTime:Yt}).then(we=>we.sites).catch(()=>[])]);d(E),u(te),x(re),i(le)}else d(null),u([]),x([]),i([])}catch(T){w(T instanceof Error?T.message:"Failed to load Bing data")}finally{v(!1)}}async function B(){if(N.trim()){w(null);try{const T=await Rh(t,N.trim());await $t(n,"bing"),k(""),T.availableSites.length>0&&i(T.availableSites),await Q()}catch(T){w(T instanceof Error?T.message:"Failed to connect")}}}async function z(){try{await Ph(t),await $t(n,"bing"),r(null),i([]),d(null),u([]),x([]),y(null),S(""),w(null)}catch(T){w(T instanceof Error?T.message:"Failed to disconnect")}}async function ne(){if(L)try{await Ih(t,L),await $t(n,"bing"),await Q()}catch(T){w(T instanceof Error?T.message:"Failed to set site")}}async function F(){if(f.trim())try{const T=await Th(t,f.trim());await $t(n,"bing"),y(T),u(E=>[T,...E])}catch(T){w(T instanceof Error?T.message:"Inspection failed")}}async function _(T){I(!0),w(null);try{const E=await mo(t,{urls:[T]}),{succeeded:te,failed:re,total:le}=E.summary;De({title:"Bing submission requested",detail:re===0?`${te} URL submitted to Bing.`:`${te}/${le} submitted successfully, ${re} failed.`,tone:re===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${T}`,dedupeMode:"replace"})}catch(E){const te=E instanceof Error?E.message:"Submission failed";w(te),De({title:"Bing submission failed",detail:te,tone:"negative",dedupeKey:`bing:indexing:${t}:${T}`,dedupeMode:"replace"})}finally{I(!1)}}async function Z(){I(!0),w(null),De({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const T=await mo(t,{allUnindexed:!0}),{succeeded:E,failed:te,total:re}=T.summary;De({title:"Bing submissions requested",detail:te===0?`${E}/${re} URL${re!==1?"s":""} submitted to Bing.`:`${E}/${re} submitted successfully, ${te} failed.`,tone:te===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(T){const E=T instanceof Error?T.message:"Batch submission failed";w(E),De({title:"Bing submissions failed",detail:E,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{I(!1)}}if(g)return e.jsx(je,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return oe()?e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(Ne,{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(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(Ne,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:N,onChange:T=>k(T.target.value),onKeyDown:T=>{T.key==="Enter"&&B()}}),e.jsx(Ye,{size:"sm",disabled:!N.trim(),onClick:Ze(B),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-secondary hover:text-neutral underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),A&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:A})]});if(!a.siteUrl)return e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{tone:"positive",children:"Connected"}),!oe()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Ze(z),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?Jt(a.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Select site"}),l.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:L,onChange:T=>S(T.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(T=>e.jsxs("option",{value:T.url,children:[T.url,T.verified?" (verified)":""]},T.url))]}),!oe()&&e.jsx(Ye,{size:"sm",disabled:!L,onClick:Ze(ne),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."})]})]}),A&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:A})]});const $=[{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"}],ee=$.find(T=>T.key===V)??$[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{tone:"positive",children:"Connected"}),!oe()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Ze(z),children:"Disconnect"})]})]}),A&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:A}),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?Jt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:ee.eyebrow}),e.jsx("h3",{children:ee.title})]}),e.jsx("p",{className:"text-xs text-muted",children:c?.lastInspectedAt?`Last inspected ${Jt(c.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:$.map(T=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${V===T.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>G(T.key),children:T.label},T.key))}),V==="coverage"&&c&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Fa,{label:"Indexed",value:c.summary.indexed,tone:"positive"}),e.jsx(Fa,{label:"Not in index",value:c.summary.notIndexed+(c.summary.unknown??0),tone:"negative"}),e.jsx(Fa,{label:"Status unknown",value:c.summary.unknown??0,tone:"neutral"}),e.jsx(Fa,{label:"Coverage",value:et(c.summary.percentage,Yn.percent),tone:"neutral"})]}),c.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",c.notIndexed.length,")"]}),!oe()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:C,onClick:Ze(Z),children:C?"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"}),!oe()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:c.notIndexed.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.httpCode??"—"}),!oe()&&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:C,onClick:()=>{_(T.url)},children:"Submit"})})]},T.id))})]})})]}),(c.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(c.unknown??[]).length,")"]}),!oe()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:C,onClick:Ze(Z),children:C?"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"}),!oe()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(c.unknown??[]).map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.lastCrawledDate?Jt(T.lastCrawledDate):"—"}),!oe()&&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:C,onClick:()=>{_(T.url)},children:"Submit"})})]},T.id))})]})})]}),c.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",c.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:c.indexed.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.lastCrawledDate?Jt(T.lastCrawledDate):"—"})]},T.id))})]})})]})]}),V==="coverage"&&!c&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),V==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!oe()&&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:f,onChange:T=>b(T.target.value),onKeyDown:T=>{T.key==="Enter"&&F()}}),e.jsx(Ye,{size:"sm",disabled:!f.trim(),onClick:Ze(F),children:"Inspect"})]}),h&&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:h.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:h.inIndex?"text-positive-400":"text-negative-400",children:h.inIndex?"Yes":"No"})," · ","HTTP: ",h.httpCode??"—"," · ","Crawled: ",h.lastCrawledDate??"—"]})]}),m.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:m.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(Ne,{tone:T.inIndex?"positive":"negative",children:T.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Jt(T.inspectedAt)})]},T.id))})]})})]}),V==="performance"&&e.jsx("div",{className:"mt-4",children:p.length===0?e.jsx("p",{className:"text-xs text-muted",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Da[jn.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Da[jn.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Da[jn.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Da[jn.Position]})]})}),e.jsx("tbody",{children:p.map((T,E)=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:T.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:T.impressions}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:et(T.ctr)}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:T.averagePosition.toFixed(1)})]},E))})]})})})]})]})}function Qb({projectName:t}){const s=hs(),[n,a]=o.useState("google"),[r,l]=o.useState(!0),[i,c]=o.useState("idle"),[d,m]=o.useState(null),u=o.useRef(null),[p,x]=o.useState(null),[h,y]=o.useState(null),[f,b]=o.useState(0);async function N(L=!1){L||l(!0),m(null);try{const[S,g]=await Promise.all([s.fetchQuery({...Ai({client:Y,path:{name:t}}),staleTime:Yt}).catch(()=>[]),s.fetchQuery({...ac({client:Y,path:{name:t}}),staleTime:Yt}).catch(()=>null)]),v=S.find(C=>C.connectionType==="gsc")??null;x(v),y(g)}catch(S){m(S instanceof Error?S.message:"Failed to load search engine connections")}finally{l(!1)}}async function k(){if(i!=="idle")return;u.current?.abort();const L=new AbortController;u.current=L;const S=L.signal;c("syncing"),m(null),De({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const g=[],v=[];try{async function C(){if(!p)return;const w=await Nh(t);if(!w?.id)return;const V=Date.now()+Il;for(;Date.now()<V;){if(S.aborted||(await new Promise(Q=>setTimeout(Q,Pl)),S.aborted))return;const G=await ti(w.id).catch(()=>null);if(!G)break;if(["completed","failed","cancelled"].includes(G.status)){G.status!=="completed"&&g.push(`Google sync ${G.status}`);return}}v.push("Google sync is still running — search data will appear shortly")}async function I(){if(!h?.connected)return;const w=await wh(t).catch(()=>null);if(!w?.id){g.push("Bing sweep could not be started");return}const V=Date.now()+Il;for(;Date.now()<V;){if(S.aborted||(await new Promise(Q=>setTimeout(Q,Pl)),S.aborted))return;const G=await ti(w.id).catch(()=>null);if(!G)break;if(["completed","failed","cancelled","partial"].includes(G.status)){G.status==="failed"?g.push("Bing sweep failed"):G.status==="partial"&&v.push("Bing sweep finished with some pages unverified");return}}v.push("Bing sweep is still running — coverage will update shortly")}const A=await Promise.allSettled([C(),I()]);for(const w of A)w.status==="rejected"&&g.push(w.reason instanceof Error?w.reason.message:"Sync failed");if(await Promise.all([$t(s,"gsc"),$t(s,"bing")]),S.aborted)return;if(c("reloading"),await N(!0),b(w=>w+1),g.length>0){const w=`Partial refresh: ${[...g,...v].join("; ")}`;m(w),De({title:"Search coverage partially refreshed",detail:w,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else v.length>0?De({title:"Search coverage refresh incomplete",detail:v.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):De({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(C){if(!S.aborted){const I=C instanceof Error?C.message:"Refresh failed";m(I),De({title:"Search coverage refresh failed",detail:I,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{S.aborted||c("idle")}}return o.useEffect(()=>(N(),()=>{u.current?.abort()}),[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([L,S])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===L,className:`project-subnav-link ${n===L?"project-subnav-link-active":""}`,onClick:()=>a(L),children:S},L))}),!oe()&&e.jsxs(Ye,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{k()},children:[e.jsx(ba,{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(qx,{projectName:t,refreshNonce:f}),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(zb,{projectName:t,refreshNonce:f})]})]})}function Tl({label:t,summary:s,displayValue:n,tooltip:a}){const{figure:r,sign:l}=Si(s.value),i=s.progress!==void 0?Math.min(Math.max(s.progress,0),100):0;return e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("p",{className:"aeo-hero-row-label",children:[t,(a||s.tooltip)&&e.jsx(Oe,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${ga[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 Hb({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(Qn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:r})]})}function Wb({insights:t,suggestedQueries:s,onManageQueries:n}){const{openEvidence:a}=Ci(),r=n?s.rows:[];if(t.length===0&&r.length===0)return null;const l=x=>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:x.title}),x.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:x.detail}):null]}),e.jsx(Ne,{tone:x.tone,children:x.actionLabel})]}),x.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 · ",x.affectedPhrases.length," affected ",x.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:x.affectedPhrases.map((h,y)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(ri,{state:h.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:h.query}),h.provider?e.jsx(jh,{provider:h.provider}):null,!oe()&&h.evidenceId?e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(h.evidenceId)},children:"View evidence"}):null]},h.evidenceId||`${x.id}-${y}`))})]}):null]},x.id),i=x=>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:x.query}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:x.reason})]}),n?e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},x.query),c=t.slice(0,1),d=r.slice(0,1),m=t.slice(1),u=r.slice(1),p=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:[c.map(l),d.map(i)]}),p>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[p," more ",p===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[m.map(l),u.map(i)]})]}):null]})}function hv(t){const{projectName:s}=id({from:"/projects/$projectName"}),a=Zl()?.dashboard.projects.find(v=>v.project.name===s||v.project.id===s)?.project.name??null,r=$e({...qm({client:Y}),enabled:!a}),l=a??r.data?.find(v=>v.name===s||v.id===s)?.name??null,i=ec(),c=tc(t.tab,sc(i)),[d,m]=o.useState(null),u=l!==null&&d===l,p=o.useCallback(()=>{l&&m(l)},[l]),{commandCenter:x,isLoading:h,overviewLoading:y,overviewError:f,isError:b,latestVisibilityRevision:N,competitorHistoryRevision:k,refetch:L}=nc(l,{overview:c==="overview"&&u}),S=!a&&r.isLoading||h;return!l&&!a&&r.isSuccess&&!h?e.jsx("div",{className:"page-container",children:e.jsxs(je,{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(P,{asChild:!0,children:e.jsx(Ms,{to:"/",children:"Return to overview"})})]})}):!x&&(b||r.isError)?e.jsxs("div",{className:"page-container",role:"alert",children:[e.jsx("p",{children:"Could not load this project."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{Promise.all([r.refetch(),L()])},children:"Retry"})]}):!x||S?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(v=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},v))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(v=>e.jsx("div",{className:"skeleton-text-sm w-full"},v))})]})]}):e.jsx(ev,{model:x,refetch:L,latestVisibilityRevision:N,competitorHistoryRevision:k,overviewLoading:y,overviewError:f,overviewRequested:u,onRequestOverview:p,...t})}function Yb({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=o.useRef(null),l=o.useRef(null),[i,c]=o.useState(null);o.useLayoutEffect(()=>{const u=r.current,p=l.current;if(!u||!p)return;const x=()=>{const y=u.getBoundingClientRect().width;if(!y)return;const f=Number.parseFloat(getComputedStyle(u).columnGap)||0,b=new Map([...p.querySelectorAll("[data-project-tab]")].map(v=>[v.dataset.projectTab,v.getBoundingClientRect().width])),N=v=>b.get(v)??0,k=v=>v.reduce((C,I)=>C+N(I),0)+Math.max(0,v.length-1)*f,L=[...t.map(v=>v.key),...s.length?["more"]:[],...n?[n.key]:[]];let S=t.map(v=>v.key),g=!1;if(k(L)>y){const v=t.find(A=>A.key===a),C=v?[v.key]:[];g=!!(n&&k([...C,"more",n.key])>y);const I=["more",...n&&!g?[n.key]:[]];for(const A of t)if(A.key!==v?.key){if(k([...C,A.key,...I])>y)break;C.push(A.key)}S=t.filter(A=>C.includes(A.key)).map(A=>A.key)}c(v=>v?.settingsInMore===g&&v.visibleKeys.join()===S.join()?v:{visibleKeys:S,settingsInMore:g})};if(x(),typeof ResizeObserver>"u")return window.addEventListener("resize",x),()=>window.removeEventListener("resize",x);const h=new ResizeObserver(x);return h.observe(u),h.observe(p),()=>h.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(Qn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),d.map(u=>e.jsx(Ms,{to:u.href,search:p=>({...p,onboarding:void 0}),className:`project-subnav-link ${u.key===a?"project-subnav-link-active project-subnav-current":""}`,"aria-current":u.key===a?"page":void 0,children:e.jsx("span",{className:"project-subnav-label",children:u.label})},u.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(Jb,{items:m,activeTab:a}),n&&!i?.settingsInMore&&e.jsx(Ms,{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 Jb({items:t,activeTab:s}){const[n,a]=o.useState(!1),r=o.useRef(null),l=o.useRef(null),i=o.useRef("first"),c=o.useId(),d=t.map(u=>u.key).join();if(o.useEffect(()=>{a(!1)},[d]),o.useEffect(()=>{if(!n)return;const u=r.current?.querySelectorAll('[role="menuitem"]');(i.current==="last"?u?.[u.length-1]:u?.[0])?.focus()},[n]),o.useEffect(()=>{if(!n)return;const u=x=>{r.current&&!r.current.contains(x.target)&&a(!1)},p=x=>{x.key==="Escape"&&(a(!1),l.current?.focus())};return document.addEventListener("pointerdown",u),document.addEventListener("keydown",p),()=>{document.removeEventListener("pointerdown",u),document.removeEventListener("keydown",p)}},[n]),t.length===0)return null;const m=t.some(u=>u.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",ref:l,className:`project-subnav-link project-subnav-more-trigger ${m?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?c:void 0,onClick:()=>{i.current="first",a(u=>!u)},onKeyDown:u=>{u.key!=="ArrowDown"&&u.key!=="ArrowUp"||(u.preventDefault(),i.current=u.key==="ArrowUp"?"last":"first",a(!0))},children:["More",e.jsx(Qn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:c,"aria-label":"More project sections",onKeyDown:u=>{const p=[...u.currentTarget.querySelectorAll('[role="menuitem"]')],x=p.indexOf(document.activeElement),h=u.key==="Home"?0:u.key==="End"?p.length-1:u.key==="ArrowDown"?(x+1)%p.length:u.key==="ArrowUp"?(x-1+p.length)%p.length:null;h!==null&&(u.preventDefault(),p[h]?.focus())},onBlur:u=>{r.current?.contains(u.relatedTarget)||a(!1)},children:t.map(u=>e.jsx(Ms,{to:u.href,search:p=>({...p,onboarding:void 0}),role:"menuitem",tabIndex:-1,className:`project-subnav-menu-item ${u.key===s?"project-subnav-menu-item-active":""}`,"aria-current":u.key===s?"page":void 0,onClick:()=>a(!1),children:u.label},u.key))}):null]})}const Xb=20,Zb=5;function ev({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r,overviewLoading:l,overviewError:i,overviewRequested:c,onRequestOverview:d}){const m=od(),u=hs(),{account:p,canWrite:x}=nn(),[h,y]=o.useState(null),f=o.useRef(null),b=Zl(),N=s.project.name,k=b?.dashboard.projects.some(M=>M.project.name===N)??!1,L=ld({strict:!1}),S=Km(L),g=dp(S),v=$e({..._m({client:Y,path:{name:N}}),enabled:!oe()&&!!N&&(x||t==="portfolio"||t==="overview"||t==="settings"||g),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),C=b?b.dashboard.settings.providerStatuses.filter(M=>M.state==="ready").map(M=>co(M.name)):void 0,I=v.data?.answerVisibilityProviderReady,A=C,w=s.project.providers.map(co),V=A?.some(M=>w.length===0||w.includes(M))===!0,G=w.length===0||w.includes(Um),Q=$e({...Bm({client:Y}),enabled:!oe()&&x&&I===void 0&&G&&!V,staleTime:6e4,retry:!1}),B=G?Q.isSuccess?typeof Q.data.browserVersion=="string":Q.isError?!1:void 0:!1,z=I??Vm({projectProviders:w,configuredApiProviders:A,cdpConfigured:B}),ne=o.useMemo(()=>sc(ec()),[]),F=tc(t,ne),_=o.useMemo(()=>s.competitors.map(M=>M.domain),[s.competitors]),Z=o.useMemo(()=>Object.fromEntries(s.competitors.map(M=>[M.domain,M.aliases??[]])),[s.competitors]),$=o.useMemo(()=>Object.fromEntries(s.competitors.map(M=>[M.domain,M.autoAliases??[]])),[s.competitors]),ee=o.useMemo(()=>Object.fromEntries(s.competitors.map(M=>[M.domain,[...M.aliases??[],...M.autoAliases??[]]])),[s.competitors]),[T,E]=o.useState(!1),[te,re]=o.useState(!1),le=zm(),we=o.useCallback((M,be)=>{m({to:".",search:ye=>Qm(ye,M),replace:be?.replace===!0})},[m]),X=L.queryWorkspace==="research"||F==="discovery"&&L.queryWorkspace===void 0?"research":"tracked",ue=uc(X,dc(p?.role,p?.role==="viewer"?Wl():null)),xe=$e({...Ii({client:Y,path:{name:N}}),enabled:!oe()&&(F==="queries"||F==="discovery")&&ue==="tracked"}),J=L.manageQueries===!0,he=o.useCallback(()=>{m({to:".",replace:!0,search:M=>({...M,siteHealthRunId:void 0})})},[m]),[K,pe]=o.useState(J),[qe,Ae]=o.useState(""),[ie,fe]=o.useState(!1),[Ce,Ge]=o.useState(null),[Ee,O]=o.useState("30d"),[D,H]=o.useState(void 0),[Me,Qe]=o.useState(""),[Fe,tt]=o.useState(!1),[ge,vt]=o.useState(null),[Ve,Je]=o.useState(!1),Dt=Hm(L),[ct,at]=o.useState(void 0),[pt,Ct]=o.useState(void 0),It=o.useCallback(M=>{at(M.search),M.sort&&Ct(M.sort),m({to:".",search:be=>({...be,...Wm(M)}),replace:!1})},[m]),[He,R]=o.useState(!1),Le=s?.project.displayName||s?.project.name||N,Pe=Ym(),Ke=$e({...uo({client:Y,path:{name:N}}),enabled:F==="portfolio"&&!!N,staleTime:0,refetchOnMount:"always"}),dt=$e({...Jm({client:Y,path:{name:N}}),enabled:!oe()&&!!N&&(x||F==="portfolio"||F==="overview"||F==="settings"),staleTime:0,refetchOnMount:"always"}),ze=dt.data?.active??null,yt=dt.data!==void 0,se=new Set(ze&&Number(ze.plan.schemaVersion)===2?ze.plan.groups?.map(M=>M.stableKey)??[]:[]),Re={...Dt.scope==="group"&&!!Dt.groupKey&&yt&&!se.has(Dt.groupKey)?{scope:"all",queryClass:Dt.queryClass}:Dt,...ct?{search:ct}:{}},ve=ze===null?null:Number(ze.plan.schemaVersion),Tt=ze?.revision??0,Xt=yt?`${N}:${Tt}`:null,Zt=o.useRef(null);o.useEffect(()=>{const M=Zt.current;Xt!==null&&(Zt.current=Xt),Xm(M,Xt)&&(It({scope:"all",queryClass:"all"}),R(!1))},[Xt,It]);const Ot={client:Y,path:{name:N},query:{scope:Re.scope,...Re.groupKey?{groupKey:Re.groupKey}:{},queryClass:Re.queryClass,...Re.search?{search:Re.search}:{},...pt?{sort:pt}:{},limit:50}},ut=Ml({...Zm(Ot),enabled:!1,initialPageParam:Ot,getNextPageParam:(M,be)=>{if(!M.properties.nextCursor)return;const ye=be[0]?.measurement.displayedRunId;return{path:Ot.path,query:{...Ot.query,cursor:M.properties.nextCursor,...ye?{runId:ye}:{}}}},placeholderData:wi,staleTime:0,refetchOnMount:"always"}),es=ut.data?.pages[0]?.measurement.displayedRunId,it=$e({...eh({client:Y,path:{name:N},query:{revision:Tt,...es?{runId:es}:{}}}),enabled:F==="overview"&&!!N&&ze!==null&&ve===1,staleTime:0,refetchOnMount:"always"}),gs=dt.data!==void 0,ps=Ke.data!==void 0,Bs=dt.isPending&&!gs,bt=dt.isError&&!gs,Vs=Ke.isPending&&!ps,Mt=Ke.isError&&!ps,as=it.data!==void 0,Vt=Cb({activePlanSchemaVersion:v.data?.activeSchemaVersion??ve,hasDraft:v.data?.draft!==null&&v.data?.draft!==void 0}),xt=Vt.surface==="simple-overview",ts=v.data===void 0&&dt.data===void 0&&(dt.isLoading||v.isLoading);o.useEffect(()=>{F==="overview"&&xt&&!ts&&d()},[ts,xt,d,F]);const zt=up({tab:F,surface:ts?"unresolved":Vt.surface,embedded:oe(),scoped:g,queryWorkspace:ue,tracking:xe.isError?{state:"error"}:xe.data?{state:"ready",mode:xe.data.mode,scopeUnavailable:mc(xe.data,S)}:{state:"pending"}}),fs=Mc(N,S,{enabled:zt.kind==="report-picker"}),Qt=F==="overview"&&xt&&!ts,gt=nc(N,{evidence:Qt}),Lt=gt.commandCenter?.visibilityEvidence??s.visibilityEvidence,Nt=o.useMemo(()=>{const M=new Map(Lt.map(ye=>[Bn(ye.query),ye.queryClass??null])),be=th(sh(s.project));return ye=>{const ft=M.get(Bn(ye));return ft!==void 0?ft:be?.classify(ye)??null}},[Lt,s.project]),ys=o.useMemo(()=>[...new Set([...Lt.map(M=>M.query),...s.movementComparison.addedQueries,...s.movementComparison.removedQueries])],[Lt,s.movementComparison]),bs=o.useMemo(()=>s.visibilitySweeps.map(M=>M.createdAt),[s.visibilitySweeps]),U=x&&!oe()&&!ds()&&F!=="overview",ae=$e({...uo({client:Y,path:{name:N}}),enabled:U,staleTime:Ri,refetchOnWindowFocus:"always"}),me=ve===2&&S.measurementScope==="group"?S.measurementScopeKey:void 0,ce=ve===2&&S.measurementScope==="project",Ie=o.useMemo(()=>{if(!(ze?.plan.schemaVersion!==2||!me))return ze.plan.groups.find(M=>M.stableKey===me)},[ze,me]),Ue={client:Y,path:{name:N},query:{window:Ee,queryClass:ve===2&&S.queryClass!=="unknown"?S.queryClass:"non-brand",...me?{groupKey:me}:{},...ce?{scope:"all-markets"}:{}}},mt=F==="overview"&&!S.marketKey&&!!N&&(xt||yt)&&!ts&&(xt||(S.measurementScope==="project"||ve===2&&S.measurementScope==="group")&&S.queryClass!=="unknown"&&(ve===2||S.queryClass!=="branded")),[kt,vs]=o.useState(null);o.useEffect(()=>{mt||vs(null)},[mt]),o.useEffect(()=>{vs(null)},[N]);const q=kt===N,Se=mt&&q,st=$e({...nh(Ue),enabled:Se,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});ah(N,JSON.stringify([r,s.competitors.map(M=>`${M.domain}=${[...M.aliases??[],...M.autoAliases??[]].join("|")}`).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,Tt,v.data?.draft?.etag??null]),Se);const qt=st.isError?st.data===void 0?"Could not load competitors over time. Your pinned competitors remain available.":"Could not refresh competitors over time. Showing the last available data.":void 0,Ft=o.useMemo(()=>s.competitors.map(M=>({domain:M.domain,label:M.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:M.citationCount,answeredResults:M.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),Be=o.useMemo(()=>{if(ze?.plan.schemaVersion!==2)return Ft;const M=me?Ie?.competitors??[]:ze.plan.groups.flatMap(ye=>ye.competitors),be=new Map;for(const ye of M){const ft=ye.domain.trim().toLowerCase();!ft||be.has(ft)||be.set(ft,{domain:ye.domain,label:ye.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const ye of Ft){const ft=ye.domain.trim().toLowerCase();!ft||be.has(ft)||be.set(ft,ye)}return[...be.values()]},[ze,me,Ft,Ie]),wt=ve===2?Be:Ft,qs=Et({...rh({client:Y}),meta:{skipGlobalErrorToast:!0}}),Xn=v.data!==void 0?"success":v.isError?"error":"pending",ss=o.useMemo(()=>{const M=ut.data?.pages;return M?!Dh(M):!1},[ut.data]),an=o.useMemo(()=>{const M=ut.data?.pages,be=M?.[0],ye=M?.at(-1);if(!(!be||!ye||ss))return{...be,properties:{...be.properties,items:M.flatMap(ft=>ft.properties.items),nextCursor:ye.properties.nextCursor}}},[ss,ut.data]),Gt=o.useMemo(()=>{if(ze)return ze.plan.schemaVersion===1?it.data?Lb(ze,it.data):void 0:an?Oh({overview:an,activePlan:ze,sort:pt,report:it.data,reportState:an.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},[ze,it.data,it.isError,it.isFetching,an]),Es=ve===2?ss?"error":ut.isPending?"loading":ut.isError&&Gt===void 0?"error":"ready":it.isPending&&!as?"loading":it.isError&&!as?"error":"ready",Ds=(s?.recentRuns??[]).some(M=>M.kind===Us["answer-visibility"]&&(M.status===Ts.running||M.status===Ts.queued)),kn=s.queryCounts.total>0,Pa=o.useMemo(()=>(s?.project.locations??[]).map(M=>M.label),[s?.project.locations]),Zn=o.useMemo(()=>new Set(Lt.map(M=>M.location??"")),[Lt]),ea=Zn.has(""),rn=o.useMemo(()=>[...new Set(Lt.map(M=>M.query))].sort((M,be)=>M.localeCompare(be)),[Lt]),on=rn.length>0||s.queryCounts.total>0||(ae.data?.length??0)>0||ze!==null,Rn=x&&!on&&(dt.data===void 0&&dt.isPending||ae.isLoading||Qt&&gt.evidenceLoading),ln=x&&(v.isError&&!v.isFetching||U&&ae.isError&&!ae.isFetching),cn=x&&!ln&&(Rn||z===void 0||v.isFetching),ta=!cn&&!ln&&on&&z===!0,dn=x&&!cn&&!ta,sa=!oe()&&F==="overview"&&dn&&!on,js=$e({...ih({client:Y,path:{name:N},query:{limit:Xb}}),enabled:sa&&!!N,retry:!1}),Ia=js.isSuccess&&js.data.scans.some(M=>M.status==="completed"||M.status==="partial"),Ta=sa&&js.isSuccess&&!Ia,Ma=sa&&Ia,un=$e({...Xl({client:Y,path:{name:N}}),enabled:!oe()&&!ds()&&!!N,retry:!1}).data?.find(M=>M.kind===Us["answer-visibility"]),Pn=un?.enabled&&un.nextRunAt?oh(un.nextRunAt,un.timezone):null,na=Pn?`Next AI sweep ${Pn}`:null,La=o.useMemo(()=>{const M=[...Zn].filter(Boolean);return M.length>1?M:Pa},[Zn,Pa]);o.useEffect(()=>{if(!Qt||D===void 0||D===""||!N){vt(null),Je(!1);return}Je(!0),lh(N,D,20).then(M=>{vt(M),Je(!1)}).catch(()=>{vt(null),Je(!1)})},[D,N,Qt]);const In=o.useMemo(()=>{if(!ge)return null;const M=new Map;for(const be of ge){for(const[ye,ft]of Object.entries(be.providerRuns??{}))M.set(`${be.query}::${ye}`,ft.map(Ss=>({runId:Ss.runId,citationState:Ss.citationState,createdAt:Ss.createdAt,answerMentioned:Ss.answerMentioned,visibilityState:Ss.visibilityState,visibilityTransition:Ss.visibilityTransition,mentionState:Ss.mentionState,mentionTransition:Ss.mentionTransition})));(!be.providerRuns||Object.keys(be.providerRuns).length===0)&&M.set(`${be.query}::`,be.runs.map(ye=>({runId:ye.runId,citationState:ye.citationState,createdAt:ye.createdAt,answerMentioned:ye.answerMentioned,visibilityState:ye.visibilityState,visibilityTransition:ye.visibilityTransition,mentionState:ye.mentionState,mentionTransition:ye.mentionTransition})))}return M},[ge]),$a=o.useMemo(()=>{const M=D!==void 0?Lt.filter(be=>D===""?!be.location:be.location===D):Lt;return In?M.map(be=>{const ye=In.get(`${be.query}::${be.provider}`)??In.get(`${be.query}::`);return ye?{...be,runHistory:ye}:be}):M},[Lt,D,In]);async function br(){if(!(h!==N||!x||oe()||ds()||Pe.isPending||Ds||!ta))try{await Pe.mutateAsync({projectName:N,projectLabel:Le,sourceAction:"project-run"}),y(null)}catch{}}function qa(){m({to:"/setup",search:{experience:"legacy",setupProject:N}})}function j(){m({to:"/projects/$projectName/technical-aeo",params:{projectName:N}})}async function W(){re(!0);try{await vh(N),De({title:"Project deleted",detail:`${Le} was removed.`,tone:"positive",dedupeKey:`project:delete:${N}`,dedupeMode:"drop"}),await m({to:"/"})}catch(M){console.error("Failed to delete project:",M)}finally{re(!1)}}async function de(){const M=qe.split(`
7
- `).map(be=>be.trim()).filter(Boolean);if(M.length!==0){fe(!0);try{await hh(N,M),Ae("")}finally{fe(!1)}}}async function ke(M){Ge(M);try{await mh(N,[M])}catch(be){De({title:"Could not remove query",detail:be instanceof Error?be.message:`Failed to remove "${M}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{Ge(null)}}async function rt(M){const be=M.trim();if(!be)return!1;try{return await dh(N,[be]),!0}catch(ye){return De({title:"Could not add competitor",detail:ye instanceof Error?ye.message:`Failed to add ${be}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function nt(M){const be=s.competitors.find(ye=>ye.domain===M);if(!be)return De({title:"Could not remove competitor",detail:`Could not find ${M} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await uh(N,be.id),!0}catch(ye){return De({title:"Could not remove competitor",detail:ye instanceof Error?ye.message:`Failed to remove ${be.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function ht(M){const be=M.trim();if(!be||!me||ve!==2||!x||oe()||qs.isPending)return!1;try{const ye=await qs.mutateAsync({client:Y,path:{name:N},headers:{"Idempotency-Key":Bb()},body:{expectedActiveRevision:Tt,groupKey:me,domain:be}});return Promise.allSettled([v.refetch()]),De({title:ye.draftCreated?"Competitor added to a market draft":"Market competitor updated",detail:`Publish the Advanced Measurement draft before ${be} is used in future market runs.`,tone:"positive",dedupeKey:`competitor:market-pin:${me}:${be}`,dedupeMode:"replace"}),!0}catch(ye){return De({title:"Could not add market competitor",detail:ye instanceof Error?ye.message:`Failed to add ${be} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function Rt(M,be){const ye=await yh(M,be);return u.setQueryData(bh({client:Y,path:{name:M}}),ye),Vb(u,ye),ye}const Xe=`/projects/${encodeURIComponent(s.project.name)}`,Te=[{key:"overview",label:"AI Visibility",href:Xe},{key:"search-console",label:"Search Engines",href:`${Xe}/search-console`},{key:"activity",label:"Activity",href:`${Xe}/activity`},{key:"technical-aeo",label:"Site Health",href:`${Xe}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${Xe}/conversions`},{key:"local",label:"Local Presence",href:`${Xe}/local`},{key:"queries",label:"Queries",href:`${Xe}/queries`},{key:"backlinks",label:"Backlinks",href:`${Xe}/backlinks`}],Ns=[{key:"history",label:"Change History",href:`${Xe}/history`}],mn=Te.filter(M=>Ar(M.key,ne)),Tn=Ns.filter(M=>Ar(M.key,ne)),ws=Ar("settings",ne)?{key:"settings",label:"Settings",href:`${Xe}/settings`}:null;function vr(M){const be=xt?M:e.jsx(Dg,{projectName:N,selection:S,showUnmeasuredFallback:!ze&&!kn&&S.measurementScope==="project"&&S.queryClass==="all"&&!S.provider&&!S.model&&!S.location&&!S.from&&!S.to&&!S.revision&&!S.measurementRunId&&!S.queryKey&&!S.marketKey,onSelectionChange:we,onManageQueries:oe()?void 0:()=>{m({to:"/projects/$projectName/queries",params:{projectName:N},search:ft=>({...ft,queryWorkspace:"tracked",trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:oe()?void 0:({id:ft,label:Ss})=>e.jsx(Ms,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:N,targetKey:ft},search:ph,"aria-label":`Property details for ${Ss}`,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:M});if(oe())return be;let ye=xh(S,xt?"simple":"advanced",typeof L.sentimentEvaluationDefinitionId=="string"?L.sentimentEvaluationDefinitionId:void 0);return xt&&(ye.location=D===""?"none":D,ye=gh(ye,$a,Me)),e.jsx(fh,{hasSourceEvidence:!xt||!!(ye.runId||ye.runIds?.length),evidenceReady:!xt||!(gt.isLoading||gt.evidenceLoading||gt.evidenceError),waitForResolvedRun:!xt,projectName:N,runOptions:s.visibilitySweeps.slice(0,Zb).map(ft=>({id:ft.id,label:Jt(ft.finishedAt??ft.createdAt)})),selection:ye,children:be})}function ad(){switch(zt.kind){case"report-picker":{if(fs.error)return zl(Ql(fs.error))?e.jsx("p",{className:"text-[13px] text-secondary",children:Oa.savedScopeUnavailable}):null;const M=fs.data;if(!M)return e.jsx("div",{className:"skeleton-text h-11 w-56",role:"status","aria-label":"Loading measurement scope"});if(M.selection.availability.state!=="available"||M.scopeOptions.length<=1)return null;const be=ai(M.scopeOptions,S)??M.selection.scope;return e.jsx(ho,{labelVisibility:"sr-only",options:M.scopeOptions,selected:be,marketKey:S.marketKey,onSelect:(ye,ft)=>we({measurementScope:ye.kind,measurementScopeKey:ye.kind==="project"?void 0:ye.id,measurementMarketKey:ft})})}case"tracking-picker":{const M=xe.data?.scopeOptions??[],be=ai(M,S);return be?e.jsx(ho,{labelVisibility:"sr-only",options:M,selected:be,onSelect:ye=>we({measurementScope:ye.kind,measurementScopeKey:ye.kind==="project"?void 0:ye.id})}):null}case"scope-unavailable":return e.jsx("p",{className:"text-[13px] text-secondary",children:Oa.savedScopeUnavailable});case"project-wide":return e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[13px] text-secondary",children:Oa.projectWide}),e.jsx(Oe,{text:Oa.projectWideHelp})]});case"none":return null}}const Ji=F==="overview"&&!xt&&(S.from||S.to)?`${S.from?.slice(0,10)??"First measurement"} to ${S.to?.slice(0,10)??"Latest measurement"}`:null,Xi=ad(),Zi=mt?e.jsx(Ap,{window:Ee,landscape:st.data,pinnedFallback:wt,competitorAliases:Z,competitorAutoAliases:$,canWrite:x,isEmbed:oe(),onWindowChange:O,onPin:me&&x&&!oe()?ht:!ce&&x&&!oe()?rt:void 0,onUnpin:me||ce||!x||oe()?void 0:nt,onAddCompetitor:me&&x&&!oe()?ht:!ce&&x&&!oe()?rt:void 0,error:qt,onRetry:Se?()=>{st.refetch()}:void 0,isLoading:Se&&st.isPending&&st.data===void 0,scopeLabel:me?`${Ie?.label??me} group`:ce?"All markets":"Project-wide"}):null,jr=oe()?null:e.jsx(e.Fragment,{children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>pe(!K),children:K?"Done":"Manage queries"})}),eo=!oe()&&K?e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[rn.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:rn.map(M=>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:M,children:M}),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 ${M}`,title:`Stop tracking "${M}"`,disabled:Ce!==null,onClick:()=>{ke(M)},children:Ce===M?"Removing…":"Remove"})]},M))}):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:qe,onChange:M=>Ae(M.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[qe.split(`
8
- `).filter(M=>M.trim()).length," to add"]}),e.jsx(Ye,{type:"button",size:"sm",disabled:!qe.trim()||ie,onClick:Ze(de),children:ie?"Adding...":"Add queries"})]})]}):null;return e.jsxs("div",{className:"page-container",children:[oe()?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:ds()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:Ji!==null?e.jsx("p",{className:"text-sm text-muted",children:Ji}):null})]}):e.jsxs("div",{className:"project-context-row",children:[e.jsx("h1",{className:"project-context-title md:sr-only",children:s.project.displayName||s.project.name}),Xi!==null?e.jsx("div",{className:"project-context-scope",children:Xi}):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:ds()?e.jsx(ch,{projectName:N,running:Ds,portfolio:!xt}):e.jsxs(e.Fragment,{children:[na?e.jsx("p",{className:"text-sm text-secondary",children:na}):null,Ta?e.jsx(Ye,{type:"button",onClick:j,children:"Map site"}):Ma?e.jsx(Ye,{type:"button",onClick:j,children:"View Page Health"}):null,e.jsx(Ye,{type:"button",variant:"outline",disabled:Pe.isPending||Ds||cn,onClick:ln?()=>{Promise.all([v.refetch(),...U?[ae.refetch()]:[]])}:dn?qa:M=>{f.current=M.currentTarget,y(N)},children:Pe.isPending?"Starting…":Ds?"AI sweep running…":cn?"Checking AI readiness…":ln?"Retry AI readiness":dn?"Set up AI Visibility":"Run AI sweep"})]})})]}),!oe()&&!ds()&&e.jsx(Ub,{open:h===N,projectLabel:Le,onOpenChange:M=>y(M?N:null),onConfirm:Ze(br),onClosed:()=>f.current?.focus(),disabled:Pe.isPending||Ds||!ta}),e.jsx(Yb,{items:mn,overflowItems:Tn,settingsItem:ws,activeTab:F}),F==="portfolio"&&!oe()?e.jsx(ib,{projectName:N,canEdit:x,queries:Ke.data??[],isQueryLoading:Vs,isQueryError:Mt,onRetryQueries:()=>{Ke.refetch()},publishedPlan:ze,onCreateQueries:async M=>(await le.mutateAsync({projectName:N,queries:[...M]}),(await Ke.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{m({to:"/projects/$projectName",params:{projectName:N},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([v.refetch(),dt.refetch()]).finally(()=>{m({to:"/projects/$projectName",params:{projectName:N}})})}},N):F==="overview"?ts||xt&&!k&&(!c||l)?e.jsxs("div",{role:"status","aria-live":"polite",children:[e.jsx("span",{className:"sr-only",children:"Loading project overview"}),e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-hidden":"true"})]}):xt&&i?e.jsxs("div",{role:"alert",className:"page-section-divider",children:[e.jsx("p",{children:"Could not load AI visibility."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[bt?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(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{dt.refetch()},children:"Retry setup check"})]}):null,vr(e.jsx(kb,{mode:Vt,canEdit:x&&!oe()&&!Bs&&!bt,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(ef,{projectName:s.project.name,competitorDomains:_,competitorAliases:ee,analyticsRevision:a,queryTexts:ys,classifyQuery:Nt,sweepTimes:bs})}),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"}),kn?e.jsx("p",{className:"av-card-meta",children:"Latest sweep"}):null]}),kn?e.jsxs("div",{className:"competitive-summary",children:[e.jsx(gp,{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(Tl,{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(Tl,{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(hg,{projectName:s.project.name,classify:Nt,hasCompetitors:_.length>0,providerScores:s.providerScores})}),e.jsxs(Hb,{id:"evidence-section",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${D===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":D===void 0,onClick:()=>{H(void 0)},children:"All locations"}),s.project.locations.map(M=>e.jsx("button",{className:`filter-chip ${D===M.label?"filter-chip-active":""}`,type:"button","aria-pressed":D===M.label,onClick:()=>{H(M.label),tt(!1)},children:M.label},M.label)),ea&&e.jsx("button",{className:`filter-chip ${D===""?"filter-chip-active":""}`,type:"button","aria-pressed":D==="",onClick:()=>{H(""),tt(!1)},children:"No location"}),La.length>1&&D===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${Fe?"filter-chip-active":""}`,type:"button","aria-pressed":Fe,onClick:()=>tt(M=>!M),title:"Side-by-side location comparison",children:"Compare"})]}),gt.evidenceLoading||gt.evidenceError?e.jsxs(e.Fragment,{children:[jr&&e.jsx(wc,{actions:jr}),eo,gt.evidenceLoading?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading query evidence…"}):e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load query evidence."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{gt.refetch()},children:"Retry"})]})]}):e.jsx(ix,{evidence:$a,compareLocations:Fe,providerSelection:Me,onProviderSelectionChange:Qe,addedQueries:s.movementComparison.addedQueries,actions:jr,actionPanel:eo})]}),!oe()&&e.jsx("div",{className:"page-section-divider",children:e.jsx(xg,{runs:s.recentRuns,collapsed:!0})})]}),report:Gt,reportState:Es,onOpenSetup:oe()?void 0:()=>{m({to:"/projects/$projectName/portfolio",params:{projectName:N}})},onRetryReport:()=>{ve===2?Promise.all([ut.refetch(),it.refetch()]):it.refetch()},onViewChange:M=>{It({scope:M.scope,...M.groupKey?{groupKey:M.groupKey}:{},queryClass:M.queryClass,...M.search?.trim()?{search:M.search.trim()}:{}})},onLoadMore:M=>{M===an?.properties.nextCursor&&ut.fetchNextPage()},onPropertyExpand:()=>{He&&it.isError&&it.refetch(),R(!0)},onRetryEvidence:()=>{it.refetch()},isViewLoading:ut.isPlaceholderData,isLoadingMore:ut.isFetchingNextPage,isLoadMoreError:ut.isFetchNextPageError,viewSearch:Re.search??""},`${N}:${Tt}`)),!xt&&S.measurementScope==="project"?e.jsxs("details",{className:"visibility-disclosure",onToggle:M=>{M.currentTarget.open&&d()},children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Project signals"})}),!c||l?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading project signals…"}):i?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load project signals."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsx(Wb,{insights:s.insights,suggestedQueries:s.suggestedQueries,onManageQueries:oe()?void 0:()=>{m({to:"/projects/$projectName/queries",params:{projectName:N},search:M=>({...M,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]},N):null,Zi!==null?e.jsxs("details",{className:`visibility-disclosure${xt?" page-section-divider":""}`,open:q,onToggle:M=>vs(M.currentTarget.open?N:null),children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Competitor history"})}),e.jsx("div",{className:"visibility-disclosure-panel",children:Zi})]}):null]}):F==="settings"?e.jsxs(e.Fragment,{children:[e.jsx($b,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(M,be)=>{await Rt(M,be)}}),e.jsx(Eb,{project:s.project,onSave:async M=>{await Rt(s.project.name,M)}}),e.jsx(Ob,{project:s.project,onSave:async M=>{await Rt(s.project.name,{siteAuditMaxPages:M})}},s.project.id),x&&!oe()?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."}),Xn==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):Xn==="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(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{v.refetch()},children:"Retry"})]}):e.jsx(P,{type:"button",variant:"outline",onClick:()=>{m({to:"/projects/$projectName/portfolio",params:{projectName:N}})},children:nd(Vt.setupAction)})]}):null,e.jsx(Gb,{projectName:s.project.name}),e.jsx(_b,{projectName:s.project.name}),x&&!oe()?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."}),T?e.jsxs(je,{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(P,{type:"button",variant:"destructive",disabled:te,onClick:Ze(W),children:te?"Deleting...":"Yes, delete project"}),e.jsx(P,{type:"button",variant:"outline",disabled:te,onClick:()=>E(!1),children:"Cancel"})]})]}):e.jsxs(Ye,{type:"button",variant:"outline",onClick:()=>E(!0),children:[e.jsx(cc,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):F==="queries"||F==="discovery"?e.jsx(mf,{projectName:N,queryWorkspace:X,onQueryWorkspaceChange:M=>we({queryWorkspace:M,trackingQueryId:void 0}),researchMode:L.researchMode==="test"?"test":"find",onResearchModeChange:M=>we({researchMode:M}),selection:S,onSelectionChange:we,trackingQueryId:typeof L.trackingQueryId=="string"?L.trackingQueryId:void 0,onTrackingQueryIdChange:M=>we({trackingQueryId:M})}):F==="technical-aeo"?e.jsx(qh,{projectName:s.project.name,projectId:s.project.id,initialRunId:L.siteHealthRunId,onReleaseInitialRun:he}):F==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(Ny,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(ly,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):F==="history"?e.jsx(Of,{projectName:s.project.name}):F==="activity"?e.jsx(jx,{projectName:s.project.name}):F==="backlinks"?e.jsx(ig,{projectName:s.project.name}):F==="local"?e.jsx(Dx,{projectName:s.project.name,projectId:s.project.id}):F==="search-console"?e.jsx(Qb,{projectName:s.project.name}):null]})}export{hv as ProjectPage,Yb as ProjectSubnav,Ub as ProjectSweepConfirmation,Vb as patchProjectDashboardCache};
6
+ pet friendly apartments austin`}),f?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:f}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:ge.length===0||y||i,onClick:()=>{Promise.resolve(x(ge)).then(()=>L(""),()=>{})},children:y?"Adding…":`Add ${ge.length||""} ${ge.length===1?"query":"queries"}`.replace(" "," ")}),b?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:b,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:ee,onChange:H=>T(H.target.value),placeholder:"apartments near {property}"}),ee.trim()===""?null:we.length===0?e.jsxs("p",{className:"mt-2 text-sm text-caution",children:["Add ","{property}"," to the pattern, or use the box above for a single query."]}):_e.length===0?e.jsx("p",{className:"mt-2 text-sm text-caution",children:"Select at least one Property to write queries for."}):e.jsxs("div",{className:"mt-2 rounded-md border border-base bg-bg-elevated p-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:[O.length," ",O.length===1?"query":"queries",", one per selected Property:"]}),e.jsx("ul",{className:"mt-1 mb-0 list-none space-y-0.5 p-0",children:O.slice(0,3).map(H=>e.jsx("li",{className:"text-sm text-strong",children:H},H))}),O.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",O.length-3," more"]}):null]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Ee.length===0||y||i||!h,onClick:()=>{h&&Promise.resolve(h(Ee)).then(()=>T(""),()=>{})},children:y?"Adding…":`Add ${Ee.length||""} ${Ee.length===1?"query":"queries"}`.replace(" "," ")}),Ee.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"," ",Ee.length," assignment",Ee.length===1?"":"s","."]}):null]})]})]}),re?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(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:ie.length===0,onClick:D,children:"Select all shown queries"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>d([]),children:"Clear query selection"}),e.jsx(P,{type:"button",size:"sm",className:"min-h-11",disabled:!pe,onClick:()=>{m({queryIds:r,propertyIds:X,...ce.kind==="groups"?{groupIds:ce.groupIds}:{}})},children:l?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${ky(ce,N,ue)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[g?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,S?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",S.assignmentCount," Property assignment",S.assignmentCount===1?"":"s"," · ",S.addedAssignments," new, ",S.alreadyPresentAssignments," already assigned"," · ",S.fullRunProviderCalls," provider request",S.fullRunProviderCalls===1?"":"s"," per full run"," · ",S.addedProviderCalls," new",ce.kind==="groups"?` · ${S.resolvedPropertyCount} unique ${S.resolvedPropertyCount===1?"Property":"Properties"}${S.overlapCount>0?`, ${S.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):v?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:v}),C?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:C,children:"Retry impact"}):null,V?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:V,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",ue," Properties = ",r.length*ue," assignments"]})]}),I?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:I}):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:Q,onChange:H=>{B(H.currentTarget.value),ne(!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 ",Re.length," of ",qe.length," queries,"," ",K.length-he.length," of ",K.length," applied"]}),re||he.length===0?null:e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{_(H=>!H),ne(!1)},children:F?"Show all queries":`Show the ${he.length} not applied`})]})]}):null,Re.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:[re?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),re?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:Re.map(H=>{const Me=vi(H),Qe=Yr(H),Ge=r.includes(H.id),et=(H.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[re?null:Me?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 ${Qe}`,checked:Ge,type:"checkbox",onChange:xe=>d(zc(r,H.id,xe.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:Qe})}),e.jsx("td",{className:"text-secondary",children:Qc(H.propertyIds??[],n)}),re?null:e.jsx("td",{className:"text-right",children:et?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[A?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||w,onClick:()=>te({queryId:H.id,propertyIds:[...H.propertyIds??[]]}),"aria-label":`Replace query assignments for ${Qe}`,children:"Replace assignments"}):null,e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{J(H.id)},"aria-label":`Clear query assignments for ${Qe}`,children:"Clear assignments"})]}):null})]},H.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,re||!E?null:(()=>{const H=a.find(Ge=>Ge.id===E.queryId),Me=H?Yr(H):"this query",Qe=E.propertyIds.filter(Ge=>n.some(et=>et.id===Ge));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 “",Me,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(ji,{legend:"Properties for this query",properties:n,selectedPropertyIds:Qe,onSelectedPropertyIdsChange:Ge=>te(et=>et&&{...et,propertyIds:[...Ge]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:w||i,onClick:()=>te(null),children:"Keep current assignments"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Qe.length===0||w||i||!A,onClick:()=>{A&&Promise.resolve(A({queryId:E.queryId,propertyIds:Qe}))},children:w?"Replacing assignments…":`Replace with ${Qe.length} ${Qe.length===1?"Property":"Properties"}`})]})]})})(),Re.length<qe.length?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>ne(!0),children:"Show all queries"}):null,re?null:e.jsxs(e.Fragment,{children:[c?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${V?"justify-between":"justify-end"}`,children:[V?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:V,children:"Back"}):null,e.jsx(P,{type:"button",variant:pe?"outline":"default",className:"min-h-11",disabled:!c||i,onClick:G,children:"Continue"})]})]})]})}function Iy({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:l=!1,onGroupDraftChange:i,onSaveGroup:c,onEditGroup:d,onRemoveGroup:m,onClearGroupDraft:u,membershipImport:p,onBack:x,onContinue:h}){if(zi(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(Hi,{message:s.message})});const y=Vi(t),f=r.name.trim().length>0&&r.propertyIds.length>0&&!l,b=n.filter(S=>r.propertyIds.includes(S.id)).length,N=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,k=!y&&(d!==void 0||m!==void 0);function $(){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(Qi,{}):null,y||!p?null:e.jsx(Ay,{value:p}),y?null:e.jsxs("div",{className:"space-y-4 border-y border-default py-4",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Group name"}),e.jsx("input",{"aria-label":"Group name",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.name,onChange:S=>i({...r,name:S.currentTarget.value}),placeholder:"Waterfront venues"})]}),e.jsxs("details",{children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:[b," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(ji,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:S=>i({...r,propertyIds:S})})})]}),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:S=>i({...r,competitorDomains:S.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!f,onClick:()=>{c(r)},children:l?"Saving group…":"Save group"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!N,onClick:$,children:"Clear form"}),e.jsx("p",{className:"text-sm text-secondary",children:"Competitor domains are used only in this group's competitor report. Membership changes affect future assignments only."})]}),N?e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Save this group or clear the form before continuing."}):null]}),e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Competitors"}),k?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.name}),e.jsx("td",{className:"text-secondary",children:Qc(S.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:S.competitors.length>0?S.competitors.join(", "):"None"}),k?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[d?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${S.name}`,onClick:()=>d(S),children:"Edit"}):null,m?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${S.name}`,onClick:()=>{m(S.id)},children:"Remove"}):null]})}):null]},S.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 ${x?"justify-between":"justify-end"}`,children:[x?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:x,children:"Back"}):null,e.jsx(P,{type:"button",className:"min-h-11",disabled:N,onClick:h,children:a.length===0&&!N?"Continue without groups":"Continue"})]})]})}function Ty({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:l,onReviewChanges:i,isReviewing:c=!1,canReviewChanges:d=!0,reviewedChanges:m,reviewChangesError:u,canPublish:p,isPublishing:x=!1,onPublish:h}){const[y,f]=o.useState(Hr),[b,N]=o.useState(Hr),[k,$]=o.useState(Hr);if(zi(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(Hi,{message:s.message})});const S=Vi(t),g=r?.items??[],v=r?.coverageItems??[],C=g.slice(0,y),I=v.slice(0,b),A=a.slice(0,k),w=i!==void 0,V=m!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),S?e.jsx(Qi,{}):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,")"]}),g.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:C.map(G=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:G.url}),e.jsx("p",{className:"mt-1 text-secondary",children:G.reason})]},`${G.url}-${G.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 ",C.length," of ",g.length]}),C.length<g.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>f(G=>G+Es),children:"Show next 50 URLs"}):null]})]}):null,S?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,")"]}),I.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[I.map(G=>e.jsxs("section",{"aria-label":`${G.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:G.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:G.savedUrls.map(Q=>e.jsx("li",{className:"break-all text-secondary",children:Q},Q))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),G.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:G.currentSitemapUrls.map(Q=>e.jsx("li",{className:"break-all text-secondary",children:Q},Q))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},G.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",I.length," of ",v.length]}),I.length<v.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>N(G=>G+Es),children:"Show next 50 URL changes"}):null]})]}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected Properties before confirming."})]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="keep-existing",onChange:()=>r.onCoverageResolutionChange("keep-existing")}),"Keep existing Property URLs"]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="replace-with-imported",onChange:()=>r.onCoverageResolutionChange("replace-with-imported")}),"Use current sitemap URLs"]})]}):null,e.jsx(P,{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??Ry})]})})]})}),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((G,Q)=>e.jsx("li",{children:G},`${G}-${Q}`))}):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:A.map(G=>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:G.title}),G.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:G.detail}):null]}),e.jsx(je,{tone:G.tone??"caution",children:"Needs attention"})]},G.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",A.length," of ",a.length]}),A.length<a.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>$(G=>G+Es),children:"Show next 50 exceptions"}):null]})]})]}),S?null:e.jsxs(e.Fragment,{children:[w&&u?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:u}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${l?"justify-between":"justify-end"}`,children:[l?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:l,children:"Back"}):null,i!==void 0&&!V?e.jsx(P,{type:"button",className:"min-h-11",disabled:c||!d,onClick:()=>{i()},children:c?"Reviewing changes…":"Review changes"}):e.jsx(P,{type:"button",className:"min-h-11",disabled:!p||x,onClick:()=>{h()},children:x?"Publishing setup…":"Publish setup"})]})]})]})}const My={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function $y(t){return t.trim().toLocaleLowerCase()}function Ly(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function qy({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 Ey({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const l=!t||r==="reviewing",i=l||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function c(d,m){n({...s,[d]:m})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":r==="reviewing",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-import-heading",className:"text-lg font-semibold text-heading",children:"Import Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review sitemap entries before choosing the Properties to measure."})]}),t?null:e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm text-secondary",children:[e.jsx(je,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:d=>{d.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:l,onChange:d=>c("sitemapUrl",d.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:l,onChange:d=>c("examplePropertyUrl",d.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:l,onChange:d=>c("preferredHost",d.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:l,onChange:d=>c("propertyPathPattern",d.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:l,onChange:d=>c("additionalHost",d.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:l,onChange:d=>c("additionalPathPattern",d.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:l,onChange:d=>c("excludedPaths",d.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(P,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function Dy({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:l,onSelectedPropertyIdsChange:i,onContinue:c,isContinuing:d=!1,onRetryProperties:m,onReturnToImport:u,maxVisibleProperties:p,onShowAllProperties:x}){const h=$y(a),y=s.filter(A=>Ly(A,h)),f=Math.max(1,p??y.length),b=y.slice(0,f),N=new Set(l),k=s.filter(A=>N.has(A.id)).map(A=>A.id),$=b.length<y.length;function S(A){const w=new Set(A);i(s.filter(V=>w.has(V.id)).map(V=>V.id))}function g(A,w){if(!t||d)return;const V=new Set(k);w?V.add(A):V.delete(A),S(V)}function v(){!t||d||S([...k,...b.map(A=>A.id)])}function C(){!t||d||i([])}function I(){!t||d||k.length===0||c(k)}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(P,{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(P,{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(P,{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:A=>r(A.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(P,{type:"button",variant:"outline",size:"sm",disabled:d,onClick:v,children:"Select all shown"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:d||k.length===0,onClick:C,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(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",b.length," of ",y.length," Properties"]}),e.jsxs("p",{children:[k.length," of ",s.length," selected"]})]}),e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"w-full min-w-150 text-left text-sm","aria-label":"Properties to review",children:[e.jsx("thead",{className:"bg-surface-subtle text-xs font-medium uppercase tracking-wide text-secondary",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-3 py-2",children:"Property"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"URL"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"State"}),t?e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Include"}):null]})}),e.jsx("tbody",{children:b.map(A=>{const w=My[A.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:A.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(qy,{property:A})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(je,{tone:w.tone,children:w.label})}),t?e.jsx("td",{className:"p-0 text-right",children:e.jsx("label",{className:"ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{type:"checkbox","aria-label":`Select ${A.name}`,checked:k.includes(A.id),disabled:d,onChange:V=>g(A.id,V.target.checked),className:"size-6 accent-accent"})})}):null]},A.id)})})]})}),$&&x?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:d,onClick:x,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(P,{type:"button",variant:"ghost",disabled:d,onClick:u,children:"Back"}),e.jsx(P,{type:"button",disabled:d||k.length===0,onClick:I,children:d?"Saving Properties…":"Continue"})]}):null]}):null]})}function Oy(t){return t.activeStep==="import"?e.jsx(Ey,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(Dy,{...t})}const Fy=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function Gy({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:l}){const i=o.useRef(null),c=o.useRef(null),d=o.useRef(null),m=o.useRef(null),u=o.useRef(!1),[p,x]=o.useState(!1);return o.useEffect(()=>{s||x(!1)},[s]),o.useEffect(()=>{const h=u.current;u.current=p,p?d.current?.focus():h&&m.current?.focus()},[p]),o.useEffect(()=>{const h=i.current;if(i.current=t,h===null||h===t)return;const y=c.current?.querySelector('h1, h2, h3, [role="heading"]');y&&(y.tabIndex=-1,y.focus())},[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 w-full sm:flex-1",children:[e.jsx("h2",{children:"Advanced measurement setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties and queries you want to measure."})]}),s?e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end",children:[e.jsx(je,{tone:"caution",children:"Unpublished changes"}),n&&a?p?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",role:"group","aria-label":"Confirm discard",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Discard all unpublished changes?"}),e.jsx(P,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>x(!1),children:"Keep editing"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(P,{ref:m,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>x(!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:Fy.map(h=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===h.id?"step":void 0,onClick:()=>r(h.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===h.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:h.label}):e.jsx("span",{"aria-current":t===h.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===h.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:h.label})},h.id))})}),e.jsx("div",{ref:c,children:l})]})}function Ky(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Oy,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(Py,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(Iy,{...t.groups,access:s}):"review"in t?e.jsx(Ty,{...t.review,access:s}):null}function Za(t){return e.jsx(Gy,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Ky(t)})}function Hc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Qt(t){return{"If-Match":t,"Idempotency-Key":Hc()}}function xn(t){return t instanceof _n&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function is(t,s){return t instanceof _n?s:(t instanceof Error?t.message.trim():"")||s}function _y(t){const s="Could not calculate assignment impact.";if(!(t instanceof _n)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const Uy={loadSetup:t=>wt(()=>ym({client:Y,path:{name:t}})),loadDraft:t=>wt(()=>fm({client:Y,path:{name:t}})),createDraft:(t,s)=>wt(()=>gm({client:Y,path:{name:t},headers:{"Idempotency-Key":Hc()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>wt(()=>xm({client:Y,path:{name:t},headers:Qt(s),body:n})),applySitemapSelection:(t,s,n,a)=>wt(()=>pm({client:Y,path:{name:t},headers:Qt(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>wt(()=>hm({client:Y,path:{name:t},body:s})),applyAssignments:(t,s,n)=>wt(()=>mm({client:Y,path:{name:t},headers:Qt(s),body:n})),replaceAssignments:(t,s,n)=>wt(()=>um({client:Y,path:{name:t},headers:Qt(s),body:n})),applyPairedAssignments:(t,s,n)=>wt(()=>dm({client:Y,path:{name:t},headers:Qt(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>wt(()=>cm({client:Y,path:{name:t},headers:Qt(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>wt(()=>lm({client:Y,path:{name:t},headers:Qt(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>wt(()=>om({client:Y,path:{name:t},headers:Qt(s),body:{target:n}})),upsertGroup:(t,s,n)=>wt(()=>im({client:Y,path:{name:t},headers:Qt(s),body:{group:n}})),removeGroup:(t,s,n)=>wt(()=>rm({client:Y,path:{name:t},headers:Qt(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>wt(()=>am({client:Y,path:{name:t},headers:Qt(s),body:n})),removeCompetitor:(t,s,n,a)=>wt(()=>nm({client:Y,path:{name:t},headers:Qt(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>wt(()=>sm({client:Y,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>wt(()=>tm({client:Y,path:{name:t},headers:Qt(s),body:n})),compilePreview:t=>wt(()=>em({client:Y,path:{name:t}})),diffPreview:t=>wt(()=>Zu({client:Y,path:{name:t}})),publish:(t,s,n)=>wt(()=>Xu({client:Y,path:{name:t},headers:Qt(s),body:n})),discard:(t,s)=>wt(()=>Ju({client:Y,path:{name:t},headers:Qt(s)}))},gl={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},la={name:"",propertyIds:[],competitorDomains:""},fl=50;function ma(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function By(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 yl(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 Vy(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,c=i.startsWith("*"),d=i.endsWith("*"),m=i.slice(c?1:0,d?-1:void 0).trim();if(!m)throw new Error("Ignored URL patterns must include text besides *.");const u=c&&d?"contains":c?"suffix":d?"prefix":"exact",p=`${u}:${m}`;n.has(p)||(n.add(p),s.push({kind:u,value:m}))}return s}function zy(t){const s=By(t.sitemapUrl),n=t.examplePropertyUrl.trim()?ma(t.examplePropertyUrl):null,a=ma(t.preferredHost)??n??ma(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=ma(t.additionalHost),l=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(l!==i||l&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const c=Vy(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:yl(t)},...r?{aliases:[{host:r,pathTemplate:yl({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...c.length>0?{excludedSlugPatterns:c}:{}}}}function Qy(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 Hy(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 bl(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function Wy(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Jr(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function Ni(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function vl(t){return ma(t)}function Wc(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 Yc(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 Jc(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Xc(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Yy(t,s){const n=Wc(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 Jy(t,s){const n=Yc(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=Xc(t.authoring,n.targetKeys[r]);return`${n.label} — ${l}`}return n.label}function Xy(t,s){const n=Jc(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${Xc(t.authoring,n.targetKey)} — ${a}`}function Zy(t,s){return s.path[0]==="identities"?"Project domain":Yy(t,s)??Jy(t,s)??Xy(t,s)}function jl(t,s,n){const a=Jc(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 eb(t,s){const n=Zy(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,jl(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,jl(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 er(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function Zc(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 tb(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${er(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${er(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${er(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${er(n,"item")} need review.`:s}})()}${Zc(a)}`}function sb(t,s){const n=new Map;for(const a of t){const r=eb(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:tb(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function Xr(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function Zr(t,s,n){const a=Wc(n,t.path),r=Yc(n,t.path),l=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=l?n?.targets.find(u=>u.stableKey===l):void 0,c=a?.label??r?.label,d=Zc(c?[c]:[]),m={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...m,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${d}`};case"excluded-target-has-assignments":return{...m,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${d}`};case"group-unknown-target":return{...m,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${d}`};case"measurement.discovery.proposed_new_target":{const u=Xr(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=Xr(a)??"the proposed Property",p=i?.label??"an existing Property";return{...m,title:"Review a moved Property",detail:`Review ${u}. It may be the same Property as ${p}.`}}case"measurement.discovery.rebind_ambiguous":{const u=Xr(a)??"the proposed Property",p=i?.label??"an existing Property";return{...m,title:"Choose an existing Property",detail:`Review ${u}. It may match ${p}; 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 nb(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 As(t){return[...new Set(t)]}function Xs(t){return As(t).sort()}function ab(t,s,n){return t.kind==="groups"?{groupKeys:Xs(t.groupIds),queryIds:Xs(n)}:{targetKeys:Xs(t.kind==="all"?s:t.propertyIds),queryIds:Xs(n)}}function rb(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 Nl(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function ib(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(Nl).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(Nl).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:Ni(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function ob({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:l,canEdit:i=!0,onCreateQueries:c,onManageProjectQueries:d,onPublished:m,service:u=Uy}){const[p,x]=o.useState(null),[h,y]=o.useState(null),[f,b]=o.useState("import"),[N,k]=o.useState(!0),[$,S]=o.useState(null),[g,v]=o.useState(null),[C,I]=o.useState([]),[A,w]=o.useState({...gl}),[V,G]=o.useState("idle"),[Q,B]=o.useState(""),[z,ne]=o.useState(fl),[F,_]=o.useState([]),[Z,L]=o.useState([]),[ee,T]=o.useState({kind:"all"}),[E,te]=o.useState(null),[re,ce]=o.useState(null),[Ne,X]=o.useState(!1),[ue,pe]=o.useState(null),[J,me]=o.useState(0),[K,he]=o.useState(null),[qe,Re]=o.useState({...la}),[ie,ge]=o.useState(null),[we,_e]=o.useState(""),[Ee,O]=o.useState(null),[D,H]=o.useState(!1),[Me,Qe]=o.useState(!1),[Ge,et]=o.useState(null),[xe,jt]=o.useState(null),[ze,Je]=o.useState(null),[Ot,dt]=o.useState(null),[st,ht]=o.useState(null),kt=o.useRef(0),Mt=o.useRef(0),He=h?.draft??null,R=h?.etag??null,$e=o.useMemo(()=>!i&&l?{baseActiveRevision:l.revision,authoring:ib(l)}:null,[i,l]),Te=He??$e;async function Ue(U){const oe=++kt.current;k(!0),S(null);try{let[ke,ae]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);if(!ae.draft&&U&&i&&(await u.createDraft(t,ke.activeRevision),[ke,ae]=await Promise.all([u.loadSetup(t),u.loadDraft(t)])),oe!==kt.current)return;x(ke),y(ae),b(Qy(ae.draft));const Pe=Jr(ae.draft);_(Pe)}catch(ke){if(oe!==kt.current)return;S(is(ke,"Could not load advanced measurement setup."))}finally{oe===kt.current&&k(!1)}}o.useEffect(()=>(Ue(!0),()=>{kt.current+=1}),[t,i,u]),o.useEffect(()=>{!N&&!He&&$e&&b("properties")},[He,N,$e]);async function ut(){const U=await u.loadDraft(t);return y(U),U}async function Be(U){ht(null);try{const[oe,ke]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);x(oe),y(ke);const ae=Jr(ke.draft);_(ae),b(Pe=>Hy(ke.draft,Pe)),v(U)}catch(oe){v(is(oe,U))}}async function yt(U,oe,ke,ae={}){const{preserveBusyAction:Pe=!1}=ae;if(!i||!R||ze&&!Pe)return null;Pe||Je(U),v(null),ht(null);try{const Ke=await oe(R),gt=await ut();return I((Ke.warnings??[]).map((vt,Us)=>Zr(vt,Us,gt.draft?.authoring))),gt}catch(Ke){return xn(Ke)?await Be("This setup changed in another session. The latest draft is loaded; review your changes again."):v(is(Ke,ke)),null}finally{Pe||Je(null)}}const se=o.useMemo(()=>(Te?.authoring.targets??[]).map(U=>{const oe=bl(U);return{id:U.stableKey,name:U.label,url:oe[0]??"No URL",urls:oe,state:Wy(U.status)}}),[Te]),Ve=o.useMemo(()=>Te?.authoring.targets.filter(U=>U.status==="included")??[],[Te]),Ie=o.useMemo(()=>Ve.map(U=>({id:U.stableKey,label:U.label,urlCount:bl(U).length})),[Ve]),be=Te?.authoring.assignments.length??0,$t=o.useMemo(()=>{if(!Te)return[];const U=new Set(s.map(ae=>ae.id)),oe=s.map(ae=>({id:ae.id,text:ae.query,source:"saved-project-queries",propertyIds:As(Te.authoring.assignments.filter(Pe=>Pe.queryId===ae.id).map(Pe=>Pe.targetKey))})),ke=As(Te.authoring.assignments.map(ae=>ae.queryId).filter(ae=>!U.has(ae))).map(ae=>({id:ae,source:"unavailable-tracked-query",state:"missing",propertyIds:As(Te.authoring.assignments.filter(Pe=>Pe.queryId===ae).map(Pe=>Pe.targetKey))}));return[...oe,...ke]},[s,Te]),Yt=o.useMemo(()=>(Te?.authoring.groups??[]).map(U=>({id:U.stableKey,name:U.label,propertyIds:U.targetKeys,competitors:U.competitors.map(oe=>oe.domain)})),[Te]),Jt=o.useMemo(()=>{if(Z.length===0)return null;const U=ab(ee,Ie.map(ke=>ke.id),Z);return(U.groupKeys?.length??U.targetKeys?.length??0)>0?U:null},[ee,Ie,Z]),Ft=Jt?JSON.stringify(Jt):"";o.useEffect(()=>{const U=Jt,oe=++Mt.current;if(!i||!He||!R||!U){te(null),ce(null),pe(null),X(!1);return}te(null),ce(null),pe(null),X(!0);const ke=window.setTimeout(()=>{u.previewAssignments(t,U).then(ae=>{if(oe===Mt.current){if(ae.draftEtag!==R){te(null),ce(null),pe("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}te(ae),ce(Ft)}}).catch(ae=>{oe===Mt.current&&(te(null),ce(null),pe(_y(ae)))}).finally(()=>{oe===Mt.current&&X(!1)})},250);return()=>{window.clearTimeout(ke),Mt.current+=1}},[Jt,Ft,J,i,He,R,t,u]);const mt=o.useMemo(()=>[...be===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"}]:[],...Te?.authoring.assignments.some(U=>U.queryClass==="unclassified")&&!($e&&l?.plan.schemaVersion===1)?[{id:"unclassified-query-assignments",title:"Remove an unavailable query",detail:"One or more saved assignments no longer have a tracked query. Clear them before publishing.",tone:"negative"}]:[],...C],[be,$e,l,C,Te]),Zt=n?{status:"unavailable",message:"Tracked queries are loading."}:a?{status:"unavailable",message:"Tracked queries could not be loaded. Retry before assigning Properties."}:{status:"available"};async function ot(U){let oe;try{oe=zy(U)}catch(ae){v(is(ae,"Check the sitemap details and try again."));return}w(U),G("reviewing");const ke=await yt("import",ae=>u.importSitemap(t,ae,oe),"Could not review this sitemap.");if(ke?.draft){const ae=ke.draft.authoring.targets.filter(Ke=>Ke.status==="proposed").map(Ke=>Ke.stableKey),Pe=ke.draft.authoring.targets.filter(Ke=>Ke.status==="included").map(Ke=>Ke.stableKey);_([...Pe,...ae]),B(""),ne(fl),b("properties"),G("idle")}else G("error")}async function fs(U){if(!c||U.length===0||ze)return[];Je("create-queries"),dt(null);try{return await c(U)}catch(oe){throw dt(Ct(oe)),oe}finally{Je(null)}}async function ps(U){if(!He||!R||ze)return;const oe=new Set(U),ae=He.authoring.targets.filter(Ke=>Ke.status==="proposed"&&Ke.discoveryIdentity).map(Ke=>({discoveryIdentity:Ke.discoveryIdentity,action:oe.has(Ke.stableKey)?"create":"ignore"})),Pe=ae.length>0||He.authoring.targets.some(Ke=>Ke.status!=="proposed"&&Ke.status==="included"!==oe.has(Ke.stableKey));Je("properties"),v(null),ht(null);try{if(!Pe){_([...oe]),T({kind:"all"}),b("groups");return}await u.applySitemapSelection(t,R,ae,[...oe]);const Ke=await ut(),gt=Jr(Ke.draft);_(gt),T({kind:"all"}),b("groups")}catch(Ke){xn(Ke)?await Be("This setup changed in another session. The latest Properties are loaded."):v(is(Ke,"Could not save the selected Properties."))}finally{Je(null)}}async function Ks(U){const oe=U.groupIds&&U.groupIds.length>0?{groupKeys:Xs(U.groupIds),queryIds:Xs(U.queryIds)}:{targetKeys:Xs(U.propertyIds),queryIds:Xs(U.queryIds)};if(!E||re!==JSON.stringify(oe)||!R||E.draftEtag!==R){v("Review the latest assignment impact before assigning queries.");return}await yt("assignments",ae=>u.applyAssignments(t,ae,oe),"Could not apply these queries.")&&(L([]),he(`${E.assignments.added} new assignment${E.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function bt(U){if(U.propertyIds.length===0)return;await yt("replace-assignments",ke=>u.replaceAssignments(t,ke,{targetKeys:As(U.propertyIds),queryIds:[U.queryId]}),"Could not replace this query assignment.")&&(L(ke=>ke.filter(ae=>ae!==U.queryId)),he("Query assignments replaced."))}async function _s(U,oe=!1){if(U.length===0)return;if(!await yt("paired-assignments",ae=>u.applyPairedAssignments(t,ae,[...U]),"Could not assign these queries.",{preserveBusyAction:oe}))throw new Error("Could not assign these queries.")}async function Lt(U){if(!(!i||!c||U.length===0||ze)){Je("create-and-pair-questions"),dt(null);try{let oe;try{oe=await c(As(U.map(Pe=>Pe.text)))}catch(Pe){throw dt(Ct(Pe)),Pe}const ke=new Map(oe.map(Pe=>[Pe.query,Pe.id])),ae=U.map(Pe=>({targetKey:Pe.propertyId,queryId:ke.get(Pe.text)})).filter(Pe=>Pe.queryId!==void 0);if(ae.length!==U.length){const Pe=new Error("The created queries could not be matched to their Properties.");throw dt("The queries were added, but could not be paired with every Property. Try again to pair them."),Pe}try{await _s(ae,!0)}catch(Pe){throw dt("The queries were added, but could not be assigned to their Properties. Try again to pair them."),Pe}}finally{Je(null)}}}async function ss(U){if(!He)return;const oe=As(He.authoring.assignments.filter(ae=>ae.queryId===U).map(ae=>ae.targetKey));if(oe.length===0)return;await yt(`remove-${U}`,ae=>u.removeAssignment(t,ae,oe,U),"Could not clear this query assignment.")&&L(ae=>ae.filter(Pe=>Pe!==U))}async function Vt(U){if(!He||!R||ze)return;const oe=U.name.trim();if(!oe)return;const ke=ie??Ni(oe,"group"),ae=He.authoring.groups.find(vt=>vt.stableKey===ke);if(ae&&ie===null){v(`A group named "${ae.label}" already exists. Edit it or choose a different name.`);return}const Pe=U.competitorDomains.split(/[\s,]+/).map(vt=>vt.trim()).filter(Boolean),Ke=Pe.find(vt=>vl(vt)===null);if(Ke){v(`"${Ke}" is not a valid competitor domain.`);return}const gt=As(Pe.map(vt=>vl(vt)));Je("group"),v(null),ht(null);try{const vt=await u.upsertGroup(t,R,{stableKey:ke,label:oe,targetKeys:As(U.propertyIds),competitors:gt.map(q=>ae?.competitors.find(Ae=>Ae.domain===q)??{stableKey:Ni(q,"competitor"),label:q,domain:q,aliases:[]})}),Us=await ut();I(vt.warnings.map((q,Ae)=>Zr(q,Ae,Us.draft?.authoring))),Re({...la}),ge(null)}catch(vt){xn(vt)?await Be("This setup changed in another session. The latest groups are loaded."):v(is(vt,"Could not save this group."))}finally{Je(null)}}function pt(U){const oe=He?.authoring.groups.find(ke=>ke.stableKey===U);oe&&(ge(U),Re({name:oe.label,propertyIds:[...oe.targetKeys],competitorDomains:oe.competitors.map(ke=>ke.domain).join(", ")}))}async function $s(U){await yt("remove-group",ke=>u.removeGroup(t,ke,U),"Could not remove this group.")&&(T(ke=>ke.kind==="groups"&&ke.groupIds.includes(U)?{kind:"all"}:ke),ie===U&&(ge(null),Re({...la})))}function Rt(U){_e(U),O(null),et(null),jt(null)}async function Ls(){if(!(!i||!we.trim()||D||Me)){H(!0),et(null),jt(null);try{O(await u.previewGroupMembership(t,{csv:we}))}catch(U){O(null),et(is(U,"Could not review this CSV."))}finally{H(!1)}}}async function Xt(U){if(!(!i||!R||!Ee||U.length===0||ze)){if(Ee.draftEtag!==R){et("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}Qe(!0),Je("group-import"),et(null),jt(null),ht(null);try{const oe=await u.applyGroupMembership(t,R,{csv:we,sourceChecksum:Ee.sourceChecksum,previewChecksum:Ee.previewChecksum,acceptedRows:As(U.map(String)).map(Number)}),ke=await ut();I(oe.warnings.map((ae,Pe)=>Zr(ae,Pe,ke.draft?.authoring))),_e(""),O(null),jt(`${oe.addedMemberships} membership${oe.addedMemberships===1?"":"s"} added${oe.unchangedMemberships>0?`; ${oe.unchangedMemberships} already present`:""}.`)}catch(oe){xn(oe)?(await Be("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(is(oe,"Could not apply this CSV."))}finally{Je(null),Qe(!1)}}}async function Pt(){if(!(!He||!R||ze||be===0)){Je("review"),v(null),ht(null);try{const[U,oe]=await Promise.all([u.compilePreview(t),u.diffPreview(t)]),ke=[...U.checks,...oe.checks],ae=ke.some(Pe=>Pe.ruleId==="active-revision-schema-v1");if(I(sb(ke.filter(Pe=>Pe.ruleId!=="active-revision-schema-v1"),{authoring:Te?.authoring,queries:s})),!U.ok||!oe.ok)return;if(oe.diff.activeRevision!==He.baseActiveRevision){await Be("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(U.compiledChecksum!==oe.compiledChecksum){v("The setup changed while it was being reviewed. Review the latest changes again.");return}ht({etag:R,baseActiveRevision:He.baseActiveRevision,compiledChecksum:U.compiledChecksum,changes:nb(oe.diff,ae),providerCalls:U.plan.executionNodes.reduce((Pe,Ke)=>Pe+Ke.expectedSnapshots,0)})}catch(U){v(is(U,"Could not review this setup."))}finally{Je(null)}}}async function Gt(){if(!(!He||!R||!st||ze)){if(R!==st.etag||He.baseActiveRevision!==st.baseActiveRevision){ht(null),v("The setup changed after review. Review the latest changes before publishing.");return}Je("publish"),v(null);try{await u.publish(t,R,{expectedActiveRevision:st.baseActiveRevision,expectedCompiledChecksum:st.compiledChecksum}),y({draft:null,etag:null}),ht(null),m?.()}catch(U){xn(U)?await Be("The setup changed before it could be published. Review the latest draft and publish again."):v(is(U,"Could not publish this setup."))}finally{Je(null)}}}async function nt(){if(!(!R||ze)){Je("discard"),v(null);try{await u.discard(t,R),y({draft:null,etag:null}),ht(null),m?.()}catch(U){xn(U)?await Be("This setup changed in another session. The latest draft is loaded."):v(is(U,"Could not discard these changes."))}finally{Je(null)}}}async function xs(){if(!(!He||!R||!p||ze)){Je("restart"),v(null),ht(null);try{await u.discard(t,R),await u.createDraft(t,p.activeRevision),w({...gl}),B(""),_([]),L([]),T({kind:"all"}),te(null),pe(null),he(null),Re({...la}),ge(null),_e(""),O(null),et(null),jt(null),await Ue(!1)}catch(U){xn(U)?await Be("The setup changed again. Reloaded the latest draft and published setup."):v(is(U,"Could not restart this setup."))}finally{Je(null)}}}if(N)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-loading-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-loading-title",children:"Advanced measurement setup"})}),e.jsx("div",{className:"h-28 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement setup"})]});if($)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:$}),e.jsx(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Ue(!0)},children:"Try again"})]})]});if(!Te||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&&p&&He.baseActiveRevision!==p.activeRevision)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-stale-draft-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-stale-draft-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"This draft is based on an older published setup."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Restart from the latest setup before making more changes."}),e.jsx(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:ze==="restart",onClick:()=>{xs()},children:ze==="restart"?"Restarting…":"Discard draft and restart"})]}),g?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:g}):null]});const ys=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:r,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[p?.mode==="active-v1"?e.jsx("p",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-3 text-sm text-secondary",children:"Review and publish this setup to enable class-filtered reporting."}):null,g?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:g}):null,ys,f==="import"||f==="properties"?e.jsx(Za,{currentStep:f,hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{nt()},importProperties:{importDraft:A,onImportDraftChange:U=>{w(U),G("idle"),v(null)},onReviewSitemap:U=>{ot(U)},reviewState:V,properties:se,propertiesState:"ready",propertiesSearch:Q,onPropertiesSearchChange:B,maxVisibleProperties:z,onShowAllProperties:()=>ne(se.length),selectedPropertyIds:F,onSelectedPropertyIdsChange:U=>_([...U]),onContinue:U=>{ps(U)},isContinuing:ze==="properties",onRetryProperties:()=>{ut()},onReturnToImport:()=>b("import")}}):f==="queries"?e.jsx(Za,{currentStep:"queries",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{nt()},onManageProjectQueries:d,queries:{onCreateQueries:c?U=>fs(U):void 0,isCreatingQueries:ze==="create-queries"||ze==="create-and-pair-questions",isBusy:ze!==null,createQueriesError:Ot,availability:Zt,properties:Ie,queries:$t,selectedQueryIds:Z,isApplying:ze==="assignments"||ze==="paired-assignments",onSelectedQueryIdsChange:U=>L([...U]),onApplySelectedQueries:U=>Ks(U),groups:Yt,audience:ee,onAudienceChange:U=>{T(U),he(null)},assignmentImpact:E&&re===Ft&&E.draftEtag===R?rb(E):null,isPreviewingAssignmentImpact:Ne,assignmentImpactError:ue,onRetryAssignmentImpact:()=>me(U=>U+1),assignmentNotice:K,onReplaceAssignments:bt,isReplacingAssignments:ze==="replace-assignments",onCreateAndPairQuestions:i&&c?Lt:void 0,onClearQueryAssignments:ss,onRemoveQuery:ss,canContinue:be>0,onBack:()=>b("groups"),onContinue:()=>b("review")}}):f==="groups"?e.jsx(Za,{currentStep:"groups",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{nt()},groups:{properties:Ie,groups:Yt,groupDraft:qe,isSaving:ze==="group",onGroupDraftChange:Re,onSaveGroup:Vt,onEditGroup:U=>pt(U.id),onRemoveGroup:$s,onClearGroupDraft:()=>{ge(null),Re({...la})},membershipImport:{csv:we,preview:Ee,isReviewing:D,isApplying:Me,error:Ge,notice:xe,onCsvChange:Rt,onReview:Ls,onApply:Xt},onBack:()=>{b("properties")},onContinue:()=>b("queries")}}):e.jsx(Za,{currentStep:"review",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{nt()},review:{counts:{properties:Ve.length,queries:new Set(Te.authoring.assignments.map(U=>U.queryId)).size,groups:Te.authoring.groups.length,assignments:Te.authoring.assignments.length,providerCalls:st?.providerCalls},flaggedExceptions:mt,reviewedChanges:st?.changes,isReviewing:ze==="review",canReviewChanges:be>0&&!ze,onReviewChanges:Pt,onBack:()=>b("queries"),canPublish:st!==null&&!ze,isPublishing:ze==="publish",onPublish:Gt}})]})}const lb=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function wl(t){return t.label!=="Complete"}const gn="__all_properties__",cb=50,ed=50,db=20,ub=50,mb=250,hb=5,pb=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],xb={"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"},td={plan_v1:"Setup update required.",no_completed_run:"Not measured yet.",no_population:"No matching queries.",evidence_incomplete:"Evidence incomplete.",identity_ambiguous:`${oo}.`,"identity-ambiguous":`${oo}.`,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."},gb={numerator:null,denominator:null,reason:"plan_v1"};function Dn(t){return t.numerator===null?!1:Number.isFinite(t.numerator)&&Number.isFinite(t.denominator)&&t.numerator>=0&&t.denominator>0&&t.numerator<=t.denominator}function fb(t){return Dn(t)?`${t.numerator} of ${t.denominator} (${Ze(t.numerator/t.denominator)})`:"N/A"}function sd(t){if(Dn(t))return"";const s=t.reason??"unavailable";return td[s]??s}function Sl(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 yb(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function bb(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function vb(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function ha({metric:t,signal:s,compact:n=!1}){const a=n?Dn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Dn(t)?"text-lg font-semibold text-heading":"text-lg font-semibold text-secondary",r=Dn(t)?Pi(t,s):null;return e.jsxs("span",{className:"inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums",...Dn(t)?{}:{title:sd(t)},children:[e.jsx("span",{className:a,children:fb(t)}),r?e.jsx("span",{className:"text-xs text-secondary",children:r}):null]})}function Wi({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(P,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Cl({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,l]=o.useState(ed),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((c,d)=>e.jsx("li",{className:a,children:c},`${c}:${d}`))}),e.jsx(Wi,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>l(Number.MAX_SAFE_INTEGER)})]})]})}function jb({evidence:t,state:s="ready",onRetry:n}){const[a,r]=o.useState(ed),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(P,{type:"button",size:"sm",variant:"outline",onClick:n,children:"Retry evidence"}):null]}):t.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"No source evidence is available."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[640px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children:l.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(je,{tone:i.tone,children:xb[i.kind]}),i.historical?e.jsx(je,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:i.query}),i.provider||i.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[i.provider,i.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:i.url})]},i.id))})]})}),e.jsx(Wi,{shown:l.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function Nb({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Cl,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Cl,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(jb,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function wb({values:t}){return e.jsxs("section",{"aria-labelledby":"advanced-measurement-share-of-voice",className:"border-y border-default py-4",children:[e.jsx("h2",{id:"advanced-measurement-share-of-voice",className:"text-sm font-medium text-heading",children:"Brand share of voice"}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[420px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Name"}),e.jsx("th",{children:"Share of voice"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.name}),e.jsx("td",{className:"text-secondary",children:e.jsx(ha,{metric:s.coverage,signal:"mentioned",compact:!0})})]},s.name))})]})})]})}function kl({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function l(i){if(r)return;const c=n.findIndex(u=>u.value===s);let d=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?d=(c+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?d=(c-1+n.length)%n.length:i.key==="Home"?d=0:i.key==="End"&&(d=n.length-1),d===null)return;i.preventDefault();const m=n[d];a(m.value),i.currentTarget.querySelectorAll('[role="radio"]')[d].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:l,children:n.map(i=>{const c=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":c,tabIndex:c?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${c?"segmented-option-active":""}`,children:i.label},i.value)})})}function Sb({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(Fe,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function Cb({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:l=!1,isViewLoading:i=!1,isLoadingMore:c=!1,isLoadMoreError:d=!1,viewSearch:m,onViewChange:u,onLoadMore:p,onPropertyExpand:x,onRetryEvidence:h,renderPropertyLink:y}){const f=t.currentView!=null,b=t.classReporting==="available"&&(f||t.classScopes!=null),[N,k]=o.useState(t.currentView?.queryClass??"all"),[$,S]=o.useState(t.currentView?.scope.key??gn),[g,v]=o.useState(m??""),[C,I]=o.useState(cb),[A,w]=o.useState(db),[V,G]=o.useState(t.currentView?.sort??"label-asc"),[Q,B]=o.useState(null),z=o.useRef(m??""),ne=b&&!f&&N!=="all"?N==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,F=f?{aggregate:t.currentView.aggregate,groups:[]}:ne,_=o.useCallback(O=>{if(!f||!u)return;const D=O.scope??($===gn?"all":"group"),H=O.search??g;z.current=H,u({scope:D,...D==="group"?{groupKey:O.groupKey??$}:{},queryClass:O.queryClass??N,...H?{search:H}:{},...O.sort?{sort:O.sort}:{}})},[u,g,N,$,f]);o.useEffect(()=>{!t.currentView||i||(k(t.currentView.queryClass),S(t.currentView.scope.key??gn),t.currentView.sort&&G(t.currentView.sort))},[i,t.currentView]),o.useEffect(()=>{m!==void 0&&(z.current=m,v(O=>O.trim()===m.trim()?O:m))},[m]),o.useEffect(()=>{if(!f||!u||g===z.current)return;const O=window.setTimeout(()=>_({search:g}),mb);return()=>window.clearTimeout(O)},[u,_,g,f]);const Z=t.availableGroups??F.groups;o.useEffect(()=>{$===gn||Z.some(O=>O.id===$)||S(gn)},[Z,$]);const L=f?void 0:F.groups.find(O=>O.id===$),ee=L?.aggregate??F.aggregate,T=O=>b?O:gb,E=V,te=g.trim().toLocaleLowerCase(),re=o.useMemo(()=>!f&&te?ee.properties.filter(O=>O.name.toLocaleLowerCase().includes(te)):ee.properties,[ee.properties,te,f]),ce=f?re:re.slice(0,C),Ne=(f?t.currentView?.scope.kind==="group":L!=null)&&N==="non-brand"&&b&&(f||L.confirmedCompetitorCount>0)&&(ee.shareOfVoice?.length??0)>0,X=b?ee.unavailablePropertyCount??0:0,ue=t.flaggedResults.reduce((O,D)=>O+(D.count??1),0),pe=t.flaggedResultsTotal??ue,J=[T(ee.metrics.propertiesMentioned),T(ee.metrics.mentionCoverage),T(ee.metrics.citationCoverage)].map(sd).find(Boolean),me=b?t.nextActionText??J??(X>0?`${X} ${X===1?"property is":"properties are"} unavailable.`:pe>0?`${pe} flagged ${pe===1?"result needs":"results need"} review.`:null):td.plan_v1,qe=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?yb(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Re=bb(t.latestMeasurement.date),ie=[{value:gn,label:"All properties"},...Z.map(O=>({value:O.id,label:O.label}))],ge=Z.length>hb;function we(O){S(O),_(O===gn?{scope:"all"}:{scope:"group",groupKey:O})}function _e(O){k(O),_({queryClass:O})}function Ee(O){const D=Q!==O;B(D?O:null),D&&x?.(O)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":i,className:"space-y-5",children:[e.jsx("header",{className:"border-b border-default pb-4",children:e.jsx("div",{role:"status","aria-label":"Measurement status and next action",className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:i?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(je,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(je,{tone:"caution",children:"Includes historical data"}):null,qe?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:qe}):null,Re?e.jsx("span",{className:"text-sm text-secondary",children:Re}):null,me?e.jsx("span",{className:"text-sm text-secondary",children:me}):null,s&&b&&n?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!b?e.jsx(P,{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:ge?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),ge?e.jsx("select",{id:"advanced-measurement-group",value:$,onChange:O=>we(O.target.value),className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-mono-400",children:ie.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))}):e.jsx(kl,{ariaLabelledBy:"advanced-measurement-group-label",value:$,options:ie,onChange:we})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-class-label",className:"block text-sm font-medium text-heading",children:"Query type"}),e.jsx(kl,{ariaLabelledBy:"advanced-measurement-class-label",value:N,options:pb,onChange:_e,disabled:!b})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:g,onChange:O=>v(O.target.value),placeholder:"Search properties",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]})]}),!i&&Ne?e.jsx(wb,{values:ee.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(Fe,{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??re.length," ",(t.currentView?.propertyTotal??re.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(Sb,{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:[lb.map(O=>{const D=E.startsWith(`${O.key}-`),H=D&&E.endsWith("-desc")?"descending":D?"ascending":"none";return e.jsx("th",{"aria-sort":H,className:(O.numeric,void 0),children:u?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const Me=`${O.key}-${D&&E.endsWith("-asc")?"desc":"asc"}`;G(Me),_({sort:Me})},"aria-label":`Sort by ${O.label.toLowerCase()}`,children:[O.label,e.jsx(Bn,{className:`h-3 w-3 transition-transform ${D?"opacity-100":"opacity-0"} ${H==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):O.label},O.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[ce.map(O=>{const D=Q===O.id;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:H=>{vb(H.target)||Ee(O.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[y?y({id:O.id,name:O.name}):O.name,wl(O.status)||O.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[wl(O.status)?e.jsx(je,{tone:O.status.tone,children:O.status.label}):null,O.historical?e.jsx(je,{tone:"caution",children:"Historical"}):null]}):null,Sl(O)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Sl(O)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(ha,{metric:O.mentionCoverage,signal:"mentioned",compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(ha,{metric:O.citationCoverage,signal:"cited",compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{size:"icon",variant:"ghost","aria-expanded":D,"aria-label":D?`Hide details for ${O.name}`:`Show details for ${O.name}`,onClick:()=>Ee(O.id),children:e.jsx(Bn,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${D?"rotate-180":""}`,"aria-hidden":"true"})})})]},O.id),D?(O.providers??[]).map(H=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:H.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(ha,{metric:H.mentionCoverage,signal:"mentioned",compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(ha,{metric:H.citationCoverage,signal:"cited",compact:!0})}),e.jsx("td",{})]},`${O.id}:${H.provider}`)):null,D?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(Nb,{property:O,onRetryEvidence:h})})},`${O.id}:details`):null]},O.id)}),ce.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]})]})}),f&&t.currentView.nextCursor&&p?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",ce.length," of ",t.currentView.propertyTotal]}),d?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(P,{size:"sm",variant:"outline",disabled:c,onClick:()=>p(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more properties":"Show 50 more"})]}):f?ce.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",ce.length," of ",t.currentView.propertyTotal]}):null:e.jsx(Wi,{shown:ce.length,total:re.length,itemLabel:"properties",onShowAll:()=>I(Number.MAX_SAFE_INTEGER)})]}),!i&&!te&&pe>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 (",pe,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,A).map(O=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(je,{tone:O.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:O.property}),e.jsx("span",{className:"text-secondary",children:O.summary})]},O.id))}),A<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,A).reduce((O,D)=>O+(D.count??1),0)," of ",pe," flagged results"]}),e.jsx(P,{size:"sm",variant:"outline",onClick:()=>w(O=>Math.min(t.flaggedResults.length,O+ub)),children:"Show 50 more"})]}):ue<pe?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",ue," of ",pe," flagged results"]}),f&&t.currentView.nextCursor&&p?e.jsx(P,{size:"sm",variant:"outline",disabled:c,onClick:()=>p(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function nd(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function kb(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 Ab(t){const s=t.targets.length,n=t.groups.filter(r=>r.parentGroupKey===void 0).length,a=[`${s} ${s===1?"property":"properties"}`];return n>0&&a.push(`${n} ${n===1?"market":"markets"}`),a.join(" · ")}function Rb({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:l,onRunMeasurement:i,onRetryReport:c,onViewChange:d,onLoadMore:m,onPropertyExpand:u,onRetryEvidence:p,renderPropertyLink:x,isRunningMeasurement:h,isOpeningSetup:y,isViewLoading:f,isLoadingMore:b,isLoadMoreError:N,viewSearch:k}){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(P,{type:"button",size:"sm",disabled:y,onClick:l,children:y?"Opening setup…":nd(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,r==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):r==="error"&&!a?e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load the advanced measurement report."}),c?e.jsx(P,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:c,children:"Retry report"}):null]}):a?e.jsx(Cb,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:l,onViewChange:d,onLoadMore:m,onPropertyExpand:u,onRetryEvidence:p,renderPropertyLink:x,isRunningMeasurement:h,isRepublishingSetup:y,isViewLoading:f,isLoadingMore:b,isLoadMoreError:N,viewSearch:k}):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 Ln={numerator:null,denominator:null,reason:"plan_v1"};function Pb(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Al(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator,...t.unattributed===void 0?{}:{unattributed:t.unattributed},...t.unchecked===void 0?{}:{unchecked:t.unchecked}}}function Ib(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function Tb(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Mb(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 $b(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function Lb(t){const s=new Map;for(const n of t){const a=$b(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function qb(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 f=l.get(y.targetKey)??[];f.push(...y.queryIds.map(b=>r.get(b)).filter(b=>!!b)),l.set(y.targetKey,[...new Set(f)])}const i=Lb(s.evidence),c=n.executionNodes.reduce((y,f)=>y+f.expectedSnapshots,0),d=s.run?.status==="completed"&&c>0,m=d?c:0,u=d?c:0,p=s.targets.map(y=>{const f=a.get(y.id),b=i.get(y.id)??[],N=b.map(S=>({id:`${S.observationId}:${S.usageEdgeId}:${S.sourceUrl}`,kind:Ib(S.classification),query:S.queryText,url:S.sourceUrl,tone:Tb(S.classification),historical:S.historical||S.bridged})),k=b.some(S=>S.historical||S.bridged),$=s.run?y.completeness.complete?f?.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:Al(y.mentionCoverage),citationCoverage:Al(y.citationCoverage),status:$,assignedQueries:l.get(y.id)??[],urls:f?.urls.map(Pb)??[],evidence:N,historical:k}}),x=new Map(p.map(y=>[y.id,y])),h=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:Mb(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Ln,mentionCoverage:Ln,citationCoverage:Ln},properties:p},groups:s.groups.map(y=>({id:y.id,label:y.label,confirmedCompetitorCount:h.get(y.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Ln,mentionCoverage:Ln,citationCoverage:Ln},properties:y.targetIds.map(f=>x.get(f)).filter(f=>!!f)}}))},flaggedResults:[]}}function Eb({project:t,onUpdateProject:s}){const[n,a]=o.useState(!1),[r,l]=o.useState(!1),[i,c]=o.useState(null),[d,m]=o.useState(t.displayName),[u,p]=o.useState(t.canonicalDomain),[x,h]=o.useState(t.country),[y,f]=o.useState(t.language),[b,N]=o.useState(t.ownedDomains??[]),[k,$]=o.useState(""),[S,g]=o.useState(t.aliases??[]),[v,C]=o.useState(""),[I,A]=o.useState(null),[w,V]=o.useState(!1),[G,Q]=o.useState(!1),[B,z]=o.useState(""),[ne,F]=o.useState(""),[_,Z]=o.useState(""),[L,ee]=o.useState(""),[T,E]=o.useState(""),[te,re]=o.useState(null),[ce,Ne]=o.useState(null);o.useEffect(()=>{n||(m(t.displayName),p(t.canonicalDomain),h(t.country),f(t.language),N(t.ownedDomains??[]),g(t.aliases??[]))},[t,n]);function X(){a(!1),c(null),m(t.displayName),p(t.canonicalDomain),h(t.country),f(t.language),N(t.ownedDomains??[]),g(t.aliases??[]),$(""),C("")}function ue(){const D=k.trim();D&&(b.includes(D)||N([...b,D]),$(""))}function pe(D){N(b.filter(H=>H!==D))}function J(){const D=v.trim();if(!D)return;const H=D.toLowerCase();S.some(Me=>Me.toLowerCase()===H)||g([...S,D]),C("")}function me(D){g(S.filter(H=>H!==D))}async function K(){if(!(!d.trim()||!u.trim()||!x.trim()||!y.trim())){l(!0),c(null);try{await s(t.name,{displayName:d.trim(),canonicalDomain:u.trim(),ownedDomains:b,aliases:S,country:x.trim(),language:y.trim()}),a(!1),De({title:"Project settings saved",detail:`${d.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(D){c(D instanceof Error?D.message:"Failed to save")}finally{l(!1)}}}async function he(){const D=B.trim(),H=ne.trim(),Me=_.trim(),Qe=L.trim();if(!(!D||!H||!Me||!Qe)){V(!0),A(null);try{const Ge={label:D,city:H,region:Me,country:Qe};T.trim()&&(Ge.timezone=T.trim()),await jm(t.name,Ge),z(""),F(""),Z(""),ee(""),E(""),Q(!1),De({title:"Location added",detail:`${D} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${D}`,dedupeMode:"drop"})}catch(Ge){A(Ge instanceof Error?Ge.message:"Failed to add location")}finally{V(!1)}}}async function qe(D){V(!0),A(null);try{await vm(t.name,D),De({title:"Location removed",detail:`${D} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${D}`,dedupeMode:"drop"})}catch(H){A(H instanceof Error?H.message:"Failed to remove location")}finally{V(!1)}}async function Re(D){V(!0),A(null);try{await bm(t.name,D),De({title:"Default location updated",detail:`${D} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(H){A(H instanceof Error?H.message:"Failed to set default location")}finally{V(!1)}}async function ie(D){re(D),Ne(null);try{await Nm(t.name,D),De({title:`${D.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(H){Ne(H instanceof Error?H.message:"Could not download tracking results.")}finally{re(null)}}const ge=d!==t.displayName||u!==t.canonicalDomain||x!==t.country||y!==t.language||JSON.stringify(b)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(S)!==JSON.stringify(t.aliases??[]),we=!le()&&!ms(),_e="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",Ee="mb-1 block text-sm font-medium text-secondary",O=B.trim()&&ne.trim()&&_.trim()&&L.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),we&&!n&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>a(!0),children:"Edit settings"})]}),i&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[i,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>c(null),children:"×"})]}),we&&n?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:Ee,children:"Display name"}),e.jsx("input",{className:_e,type:"text",value:d,onChange:D=>m(D.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ee,children:"Canonical domain"}),e.jsx("input",{className:_e,type:"text",value:u,onChange:D=>p(D.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ee,children:"Country"}),e.jsx("input",{className:_e,type:"text",value:x,onChange:D=>h(D.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ee,children:"Language"}),e.jsx("input",{className:_e,type:"text",value:y,onChange:D=>f(D.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ee,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:b.map(D=>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:[D,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>pe(D),"aria-label":`Remove ${D}`,children:"×"})]},D))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${_e} flex-1`,type:"text",placeholder:"docs.example.com",value:k,onChange:D=>$(D.target.value),onKeyDown:D=>D.key==="Enter"&&(D.preventDefault(),ue())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!k.trim(),onClick:ue,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ee,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:S.map(D=>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:[D,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>me(D),"aria-label":`Remove ${D}`,children:"×"})]},D))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${_e} flex-1`,type:"text",placeholder:"Facebook",value:v,onChange:D=>C(D.target.value),onKeyDown:D=>D.key==="Enter"&&(D.preventDefault(),J())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!v.trim(),onClick:J,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(P,{type:"button",disabled:r||!ge||!d.trim()||!u.trim(),onClick:Xe(K),children:r?"Saving...":"Save changes"}),e.jsx(P,{type:"button",variant:"outline",disabled:r,onClick:X,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-default bg-surface overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(D=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:D},D))}):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(D=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:D},D))}):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(D=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:D},D))})})]}):null,e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[I&&e.jsxs("div",{className:"mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-xs text-negative",children:[I,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>A(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(D=>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 ${D.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[D.label,D.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:D.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:D.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:D.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:D.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[we&&D.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:w,onClick:()=>{Re(D.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${D.label} as default location`,children:"Set default"}),we&&e.jsx("button",{type:"button",disabled:w,onClick:()=>{qe(D.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${D.label}`,children:"Remove"})]})})]},D.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),we?G?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:_e,type:"text",value:B,onChange:D=>z(D.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:_e,type:"text",value:ne,onChange:D=>F(D.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:_e,type:"text",value:_,onChange:D=>Z(D.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:_e,type:"text",value:L,onChange:D=>ee(D.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:_e,type:"text",value:T,onChange:D=>E(D.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(P,{type:"button",size:"sm",disabled:w||!O,onClick:Xe(he),children:w?"Adding...":"Add location"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:w,onClick:()=>{Q(!1),A(null)},children:"Cancel"})]})]}):e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>Q(!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(P,{type:"button",variant:"outline",size:"sm",disabled:te!==null,onClick:Xe(()=>ie("csv")),children:te==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:te!==null,onClick:Xe(()=>ie("json")),children:te==="json"?"Preparing JSON...":"Download JSON"})]})]}),ce&&e.jsx("p",{className:"mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:ce})]})]})]})}function ca(t){return{...t??{}}}function Db(t,s){const n=Object.entries(t).sort(([r],[l])=>r.localeCompare(l)),a=Object.entries(s).sort(([r],[l])=>r.localeCompare(l));return n.length===a.length&&n.every(([r,l],i)=>{const c=a[i];return c?.[0]===r&&c[1]===l})}function Ob({project:t,onSave:s}){const{isAdmin:n}=rn(),a=Le({queryKey:["settings"],queryFn:Gl,staleTime:6e4,enabled:n&&!le()}),[r,l]=o.useState(t.providers.length===0),[i,c]=o.useState(t.providers),[d,m]=o.useState(()=>ca(t.providerModels)),[u,p]=o.useState({providers:t.providers,providerModels:ca(t.providerModels)}),[x,h]=o.useState(!1),[y,f]=o.useState(!1),[b,N]=o.useState(null),[k,$]=o.useState(null),S=o.useRef(null),g=a.data?.providerCatalog??[],v=o.useMemo(()=>new Set((a.data?.providers??[]).filter(B=>B.configured).map(B=>B.name)),[a.data]),C=o.useMemo(()=>{const B=new Map(a.data?.providers.map(ne=>[ne.name,ne.model])),z=new Map(g.map(ne=>[ne.name,{...ne,defaultModel:B.get(ne.name)||ne.defaultModel}]));for(const ne of Object.keys(d))z.has(ne)||z.set(ne,{name:ne,displayName:ne,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...z.values()].sort((ne,F)=>ne.displayName.localeCompare(F.displayName))},[g,d,a.data?.providers]),I=!Db(d,u.providerModels);o.useEffect(()=>{if(x||y)return;const B={providers:t.providers,providerModels:ca(t.providerModels)};p(B),l(B.providers.length===0),c(B.providers),m(B.providerModels)},[t]);function A(){f(!0),l(!1),i.length===0&&c([...v])}function w(B,z,ne=!1){f(!0),m(F=>{const _={...F};return z==="__inherit__"?delete _[B]:z==="__custom__"?_[B]=ne?"":_[B]??"":_[B]=z,_}),z==="__custom__"&&queueMicrotask(()=>S.current?.focus())}function V(B,z){f(!0),c(ne=>z?[...new Set([...ne,B])]:ne.filter(F=>F!==B))}function G(){f(!1),l(u.providers.length===0),c(u.providers),m(ca(u.providerModels)),N(null),$(null)}async function Q(){if(!(a.isError||a.isLoading||!r&&i.length===0)){h(!0),N(null),$(null);try{const B=Object.fromEntries(Object.entries(d).filter(([ne,F])=>F.trim()!==""&&(r||i.includes(ne)))),z={providers:r?[]:i,providerModels:B};await s(z),p({providers:[...z.providers],providerModels:ca(z.providerModels)}),f(!1),$("Engine settings saved. They apply on the next sweep.")}catch(B){N(ya(B))}finally{h(!1)}}}return le()||!n?null:a.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):a.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):g.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(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):v.size===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsxs("p",{className:"text-sm text-secondary",children:["Configure an answer engine in ",e.jsx(Ts,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":x,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:x,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:r,onChange:()=>{f(!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:A})," Choose engines"]}),!r&&e.jsx("div",{className:"project-engine-list",children:C.map(B=>{const z=i.includes(B.name),ne=v.has(B.name),F=z&&!ne,_=d[B.name],Z=B.knownModels.some(ee=>ee.id===_),L=_===void 0?"__inherit__":Z?_:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:z,disabled:!ne&&!z,onChange:ee=>V(B.name,ee.target.checked)})," ",e.jsx("span",{children:B.displayName}),F&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),z&&(B.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${B.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${B.name}`,value:L,onChange:ee=>w(B.name,ee.target.value,Z),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",B.defaultModel||"default"]}),B.knownModels.map(ee=>e.jsx("option",{value:ee.id,children:ee.displayName},ee.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),L==="__custom__"&&e.jsx("input",{ref:S,"aria-label":`${B.displayName} custom model ID`,value:_??"",onChange:ee=>{f(!0),m(T=>({...T,[B.name]:ee.target.value}))},"aria-describedby":`project-model-hint-${B.name}`}),e.jsxs("p",{id:`project-model-hint-${B.name}`,className:"project-engine-help",children:[_?"Project override":"Inherited from instance settings",". ",B.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},B.name)})})]}),!r&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),b&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:b}),k&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:k}),I&&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(P,{type:"button",onClick:()=>{Q()},disabled:x||!r&&i.length===0,children:x?"Saving engines…":"Save engines"}),e.jsx(P,{type:"button",variant:"outline",onClick:G,disabled:x,children:"Cancel"})]})]})}const ks={heading:"Site Health scans",help:`Used by every scan that sets no budget, scheduled or manual. Onboarding's first look always checks ${qh(Cm)}.`,pageBudget:"Page budget",customOption:"Custom number...",customLabel:"Custom page budget",customError:`Enter a whole number from 1 to ${Jl.toLocaleString("en-US")}.`,save:"Save page budget",saving:"Saving page budget…",saved:"Page budget saved."},Yi="full",On="custom";function tr(t){return t===null?{choice:Yi,customText:""}:ic.some(s=>s.value===t)?{choice:String(t),customText:""}:{choice:On,customText:String(t)}}function Fb({choice:t,customText:s}){if(t===Yi)return null;if(t!==On)return Number(t);const n=s.trim();if(n==="")return;const a=Sm.safeParse(Number(n));return a.success?a.data:void 0}function Gb({project:t,onSave:s}){const{canWrite:n,isAdmin:a}=rn(),r=n&&!le()&&!ms()&&(!wm(Gs["site-audit"])||a),l=t.siteAuditMaxPages??null,[i,c]=o.useState(l),[d,m]=o.useState(()=>tr(l)),[u,p]=o.useState(!1),[x,h]=o.useState(!1),[y,f]=o.useState(!1),[b,N]=o.useState(null),[k,$]=o.useState(null),S=o.useRef(null),g=o.useId(),v=`${g}-heading`,C=`${g}-page-budget`,I=`${g}-custom-page-budget`,A=`${g}-custom-page-budget-error`;o.useEffect(()=>{y||x||(c(l),m(tr(l)))},[l]);const w=Fb(d),G=d.choice===On&&w===void 0&&(u||d.customText.trim()!==""),Q=w!==void 0&&w!==i;function B(Z){h(!0),N(null),$(null),m(L=>({...L,choice:Z})),Z===On&&(p(!1),queueMicrotask(()=>S.current?.focus()))}function z(Z){h(!0),N(null),$(null),p(!0),m(L=>({...L,customText:Z}))}function ne(){h(!1),m(tr(i)),p(!1),N(null),$(null)}async function F(){if(!(y||w===void 0)){f(!0),N(null),$(null);try{await s(w),c(w),m(tr(w)),p(!1),h(!1),$(ks.saved)}catch(Z){N(ya(Z))}finally{f(!1)}}}const _="h-9 w-full rounded-md border border-base bg-bg px-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600 disabled:opacity-60";return e.jsxs("section",{className:"project-engine-settings","aria-labelledby":v,"aria-busy":y,children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:v,children:ks.heading}),e.jsx(Fe,{text:ks.help})]})}),r?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid max-w-sm gap-1",children:[e.jsx("label",{htmlFor:C,className:"text-sm font-medium text-heading",children:ks.pageBudget}),e.jsxs("select",{id:C,value:d.choice,disabled:y,onChange:Z=>B(Z.target.value),className:_,children:[e.jsx("option",{value:Yi,children:$h}),ic.map(Z=>e.jsx("option",{value:String(Z.value),children:Z.label},Z.value)),e.jsx("option",{value:On,children:ks.customOption})]}),d.choice===On&&e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:I,className:"mt-2 text-sm font-medium text-heading",children:ks.customLabel}),e.jsx("input",{ref:S,id:I,type:"number",inputMode:"numeric",min:1,max:Jl,step:1,value:d.customText,disabled:y,"aria-invalid":G,"aria-describedby":G?A:void 0,onChange:Z=>z(Z.target.value),className:_}),G&&e.jsx("p",{id:A,role:"alert",className:"text-sm text-negative",children:ks.customError})]})]}),b&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:b}),k&&e.jsx("p",{role:"status",className:"mt-3 text-sm text-positive",children:k}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsx(P,{type:"button",onClick:()=>{F()},disabled:y||!Q,children:y?ks.saving:ks.save}),e.jsx(P,{type:"button",variant:"outline",onClick:ne,disabled:y||!x,children:"Cancel"})]})]}):e.jsxs("p",{className:"text-sm text-secondary",children:[ks.pageBudget,": ",e.jsx("span",{className:"text-strong",children:Lh(i)})]})]})}const sr={edit:"Edit schedule",pause:"Pause",resume:"Resume",save:"Save schedule"},Kb=[{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"}],Rl=["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 ei(t,s){const n=s==="UTC"?"UTC":s.split("/").pop()?.replace(/_/g," ")??s,a=new Date(`${t.startDate}T00:00:00Z`),r=Number.isNaN(a.getTime())?t.startDate:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(a),[l,i]=t.time.split(":").map(Number),c=Number.isInteger(l)&&Number.isInteger(i)?new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",timeZone:"UTC"}).format(new Date(Date.UTC(1970,0,1,l,i))):t.time;return`Every ${t.everyDays} days starting ${r} at ${c} · ${n}`}function _b({projectName:t}){const s=cs(),n=!le()&&!ms()&&!s,a=hs(),[r,l]=o.useState(!1),[i,c]=o.useState("daily"),[d,m]=o.useState(6),[u,p]=o.useState(""),[x,h]=o.useState(14),[y,f]=o.useState(""),[b,N]=o.useState("00:00"),[k,$]=o.useState("UTC"),[S,g]=o.useState(!1),[v,C]=o.useState(""),[I,A]=o.useState(!1),[w,V]=o.useState(!1),[G,Q]=o.useState(null),[B,z]=o.useState(void 0),ne=km({client:Y,path:{name:t}}),F=Le({...Xl({client:Y,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),_=F.isPending||F.isFetching,Z=F.isError,L=F.data?.find(J=>J.kind==="answer-visibility")??null,ee=r&&B!==void 0&&(L?.updatedAt??null)!==B,T=J=>{a.setQueryData(ne,me=>{const K=(me??[]).filter(he=>he.kind!=="answer-visibility");return J?[...K,J]:K})},E=J=>{if(J){if(J.recurrence)c("calendar"),h(J.recurrence.everyDays),f(J.recurrence.startDate),N(J.recurrence.time);else{const K=Tm(J.preset??null,J.cronExpr);c(K.freq),m(K.hour),p(K.customCron)}const me=Rl.includes(J.timezone);$(me?J.timezone:"Other"),g(!me),C(me?"":J.timezone)}else c("daily"),m(6),p(""),h(14),f(""),N("00:00"),$("UTC"),g(!1),C("");z(J?.updatedAt??null)},te=()=>{n&&(E(L),Q(null),l(!0))},re=()=>{E(L),Q(null)},ce=async()=>{(await F.refetch()).isError?Q("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):Q(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},Ne=async(J,me)=>{if(J instanceof _n&&J.code==="SCHEDULE_VERSION_CONFLICT"){await ce();return}Q(J instanceof Error?J.message:me)},X=async()=>{if(n&&!(ee||B===void 0)){A(!0),Q(null);try{const J=await F.refetch();if(J.isError||J.data===void 0){Q("Canonry could not verify the latest schedule. Try again before saving.");return}const me=J.data.find(Re=>Re.kind==="answer-visibility")??null;if((me?.updatedAt??null)!==B)return;const he={timezone:S?v.trim()||"UTC":k,enabled:me?.enabled??!0,providers:me?.providers??[],expectedUpdatedAt:B};i==="calendar"?he.recurrence={everyDays:x,startDate:y,time:b}:i==="custom"?he.cron=u.trim():he.preset=Im(i,d);const qe=await lo(t,he);l(!1),z(void 0),T(qe),De({title:"Schedule saved",detail:qe.recurrence?ei(qe.recurrence,qe.timezone):kr(qe.preset??null,qe.cronExpr,qe.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(J){await Ne(J,"Failed to save schedule")}finally{A(!1)}}},ue=async()=>{if(!n||!L)return;const J=L.updatedAt;A(!0),Q(null);try{const me=await F.refetch();if(me.isError||me.data===void 0){Q("Canonry could not verify the latest schedule. Try again before updating it.");return}const K=me.data.find(Re=>Re.kind==="answer-visibility")??null;if(!K||K.updatedAt!==J){Q("This schedule changed elsewhere. Review the latest version and try again.");return}const he={timezone:K.timezone,enabled:!K.enabled,providers:K.providers,expectedUpdatedAt:J};K.recurrence?he.recurrence=K.recurrence:K.preset?he.preset=K.preset:he.cron=K.cronExpr;const qe=await lo(t,he);T(qe),De({title:qe.enabled?"Schedule resumed":"Schedule paused",detail:qe.recurrence?ei(qe.recurrence,qe.timezone):kr(qe.preset??null,qe.cronExpr,qe.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(me){await Ne(me,"Failed to update schedule")}finally{A(!1)}},pe=async()=>{if(!n||!L)return;const J=L.updatedAt;V(!0),Q(null);try{await Pm(t,J),T(null),l(!1),z(void 0),De({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(me){await Ne(me,"Failed to remove schedule")}finally{V(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),n&&!_&&!Z&&!r&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:te,children:L?sr.edit:"+ Set schedule"})]}),_&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),G&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:G}),!_&&Z&&e.jsxs(ve,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{F.refetch()},children:"Retry"})]}),!_&&!Z&&!r&&L===null&&e.jsx(ve,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?Un:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!_&&!Z&&!r&&L!==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:Un}),e.jsx("p",{className:"text-sm font-medium text-strong",children:L.recurrence?ei(L.recurrence,L.timezone):kr(L.preset??null,L.cronExpr,L.timezone)}),!L.recurrence&&e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:L.cronExpr})]}),L.enabled&&L.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",Am(L.nextRunAt,L.timezone)]}),L.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(L.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(je,{tone:L.enabled?"positive":"neutral",children:L.enabled?"Active":"Paused"}),n&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:I,onClick:Xe(ue),children:L.enabled?sr.pause:sr.resume}),n&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:w,onClick:Xe(pe),children:w?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[ee&&!I&&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(P,{type:"button",variant:"outline",size:"sm",onClick:re,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:J=>c(J.target.value),children:Kb.map(J=>e.jsx("option",{value:J.value,children:J.label},J.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:J=>m(parseInt(J.target.value)),children:Array.from({length:24},(J,me)=>e.jsx("option",{value:me,children:Rm(me)},me))})]})]}),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:J=>p(J.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:x,onChange:J=>h(Number(J.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:J=>f(J.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Recurrence time",type:"time",value:b,onChange:J=>N(J.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:S?"Other":k,onChange:J=>{J.target.value==="Other"?(g(!0),$("Other")):(g(!1),$(J.target.value))},children:[Rl.map(J=>e.jsx("option",{value:J,children:J},J)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),S&&e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:v,onChange:J=>C(J.target.value)})]}),G&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:G}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{l(!1),z(void 0),Q(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:I||F.isFetching||Z||ee||i==="custom"&&!u.trim()||i==="calendar"&&(!Number.isInteger(x)||x<1||x>3650||!y||!b),onClick:Xe(X),children:I?"Saving...":sr.save})]})]})]})}const Ub=[{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 Bb({projectName:t}){const[s,n]=o.useState("loading"),[a,r]=o.useState(!1),[l,i]=o.useState(""),[c,d]=o.useState(["citation.lost","citation.gained"]),[m,u]=o.useState(!1),[p,x]=o.useState(null),[h,y]=o.useState({}),[f,b]=o.useState(new Set),N=!le()&&!ms();o.useEffect(()=>{Mm(t).then(n).catch(()=>n([]))},[t]);const k=v=>{d(C=>C.includes(v)?C.filter(I=>I!==v):[...C,v])},$=async()=>{if(!(!l.trim()||c.length===0)){u(!0),x(null);try{const v=await $m(t,{channel:"webhook",url:l.trim(),events:c});n(C=>C==="loading"?[v]:[...C,v]),i(""),d(["citation.lost","citation.gained"]),r(!1),De({title:"Webhook added",detail:`Notifications will be sent to ${v.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(v){x(v instanceof Error?v.message:"Failed to add webhook")}finally{u(!1)}}},S=async v=>{if(!f.has(v)){b(C=>new Set(C).add(v));try{await qm(t,v),n(C=>C==="loading"?C:C.filter(I=>I.id!==v)),De({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${v}`,dedupeMode:"drop"})}catch(C){x(C instanceof Error?C.message:"Failed to remove webhook")}finally{b(C=>{const I=new Set(C);return I.delete(v),I})}}},g=async v=>{y(C=>({...C,[v]:{state:"testing"}}));try{const C=await Lm(t,v);y(I=>({...I,[v]:{state:C.ok?"ok":"fail",status:C.status}})),C.ok&&De({title:"Test notification sent",detail:`Webhook returned status ${C.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${v}`,dedupeMode:"replace"})}catch{y(C=>({...C,[v]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),N&&s!=="loading"&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),x(null)},children:a?"Cancel":"+ Add webhook"})]}),N&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:l,onChange:v=>i(v.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Ub.map(v=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:c.includes(v.value),onChange:()=>k(v.value)}),e.jsx("span",{className:"text-sm text-neutral",children:v.label})]},v.value))})]}),p&&e.jsx("p",{className:"text-negative-400 text-sm",children:p}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),x(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:m||!l.trim()||c.length===0,onClick:Xe($),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(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-neutral break-all",title:v.urlHost,children:v.urlDisplay??v.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:v.events.map(C=>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:C.replace("."," ")},C))})}),e.jsx("td",{children:e.jsx(je,{tone:v.enabled?"positive":"neutral",children:v.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[h[v.id]&&(()=>{const C=h[v.id],I=C.state==="testing"?"Sending…":C.state==="ok"?`Delivered${C.status?` (${C.status})`:""}`:`Failed${C.status?` (${C.status})`:""}`;return e.jsx(je,{tone:C.state==="ok"?"positive":C.state==="fail"?"negative":"neutral",children:I})})(),N&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:h[v.id]?.state==="testing",onClick:()=>{g(v.id)},children:"Test"}),N&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:f.has(v.id),onClick:()=>{S(v.id)},children:f.has(v.id)?"Removing…":"Remove"})]})})]},v.id))})]}),p&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:p})]})]})}function Vb({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:l}){return le()||cs()?null:e.jsx(Dm,{open:t,onOpenChange:n,children:e.jsxs(Om,{onCloseAutoFocus:i=>{r&&(i.preventDefault(),r())},children:[e.jsxs(Fm,{children:[e.jsx(Gm,{children:"Run AI sweep for the whole project?"}),e.jsxs(Km,{children:["Runs all tracked queries for ",s,". View filters do not limit the sweep. Provider charges apply."]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsx(P,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(Ye,{disabled:l,onClick:a,children:"Run project-wide sweep"})]})]})})}const Pl=2e3,Il=3e5;function zb(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Qb(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 Hb({projectName:t,refreshNonce:s}){const n=hs(),[a,r]=o.useState(null),[l,i]=o.useState([]),[c,d]=o.useState(null),[m,u]=o.useState([]),[p,x]=o.useState([]),[h,y]=o.useState(null),[f,b]=o.useState(""),[N,k]=o.useState(""),[$,S]=o.useState(""),[g,v]=o.useState(!0),[C,I]=o.useState(!1),[A,w]=o.useState(null),[V,G]=o.useState("performance");o.useEffect(()=>{Q()},[t,s]);async function Q(){v(!0),w(null);try{const T=await n.fetchQuery({...ac({client:Y,path:{name:t}}),staleTime:Ht});if(r(T),T.connected){const[E,te,re,ce]=await Promise.all([n.fetchQuery({...Ch({client:Y,path:{name:t}}),staleTime:Ht}).catch(()=>null),n.fetchQuery({...kh({client:Y,path:{name:t}}),staleTime:Ht}).catch(()=>[]),n.fetchQuery({...Ah({client:Y,path:{name:t}}),staleTime:Ht}).catch(()=>[]),T.siteUrl?Promise.resolve([]):n.fetchQuery({...Rh({client:Y,path:{name:t}}),staleTime:Ht}).then(Ne=>Ne.sites).catch(()=>[])]);d(E),u(te),x(re),i(ce)}else d(null),u([]),x([]),i([])}catch(T){w(T instanceof Error?T.message:"Failed to load Bing data")}finally{v(!1)}}async function B(){if(N.trim()){w(null);try{const T=await Ph(t,N.trim());await Et(n,"bing"),k(""),T.availableSites.length>0&&i(T.availableSites),await Q()}catch(T){w(T instanceof Error?T.message:"Failed to connect")}}}async function z(){try{await Ih(t),await Et(n,"bing"),r(null),i([]),d(null),u([]),x([]),y(null),S(""),w(null)}catch(T){w(T instanceof Error?T.message:"Failed to disconnect")}}async function ne(){if($)try{await Th(t,$),await Et(n,"bing"),await Q()}catch(T){w(T instanceof Error?T.message:"Failed to set site")}}async function F(){if(f.trim())try{const T=await Mh(t,f.trim());await Et(n,"bing"),y(T),u(E=>[T,...E])}catch(T){w(T instanceof Error?T.message:"Inspection failed")}}async function _(T){I(!0),w(null);try{const E=await mo(t,{urls:[T]}),{succeeded:te,failed:re,total:ce}=E.summary;De({title:"Bing submission requested",detail:re===0?`${te} URL submitted to Bing.`:`${te}/${ce} submitted successfully, ${re} failed.`,tone:re===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${T}`,dedupeMode:"replace"})}catch(E){const te=E instanceof Error?E.message:"Submission failed";w(te),De({title:"Bing submission failed",detail:te,tone:"negative",dedupeKey:`bing:indexing:${t}:${T}`,dedupeMode:"replace"})}finally{I(!1)}}async function Z(){I(!0),w(null),De({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const T=await mo(t,{allUnindexed:!0}),{succeeded:E,failed:te,total:re}=T.summary;De({title:"Bing submissions requested",detail:te===0?`${E}/${re} URL${re!==1?"s":""} submitted to Bing.`:`${E}/${re} submitted successfully, ${te} failed.`,tone:te===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(T){const E=T instanceof Error?T.message:"Batch submission failed";w(E),De({title:"Bing submissions failed",detail:E,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{I(!1)}}if(g)return e.jsx(ve,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return le()?e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(je,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(je,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:N,onChange:T=>k(T.target.value),onKeyDown:T=>{T.key==="Enter"&&B()}}),e.jsx(Ye,{size:"sm",disabled:!N.trim(),onClick:Xe(B),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-secondary hover:text-neutral underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),A&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:A})]});if(!a.siteUrl)return e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{tone:"positive",children:"Connected"}),!le()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Xe(z),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?Wt(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:$,onChange:T=>S(T.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(T=>e.jsxs("option",{value:T.url,children:[T.url,T.verified?" (verified)":""]},T.url))]}),!le()&&e.jsx(Ye,{size:"sm",disabled:!$,onClick:Xe(ne),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."})]})]}),A&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:A})]});const L=[{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"}],ee=L.find(T=>T.key===V)??L[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{tone:"positive",children:"Connected"}),!le()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Xe(z),children:"Disconnect"})]})]}),A&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:A}),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?Wt(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:ee.eyebrow}),e.jsx("h3",{children:ee.title})]}),e.jsx("p",{className:"text-xs text-muted",children:c?.lastInspectedAt?`Last inspected ${Wt(c.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:L.map(T=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${V===T.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>G(T.key),children:T.label},T.key))}),V==="coverage"&&c&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ga,{label:"Indexed",value:c.summary.indexed,tone:"positive"}),e.jsx(Ga,{label:"Not in index",value:c.summary.notIndexed+(c.summary.unknown??0),tone:"negative"}),e.jsx(Ga,{label:"Status unknown",value:c.summary.unknown??0,tone:"neutral"}),e.jsx(Ga,{label:"Coverage",value:Ze(c.summary.percentage,Qn.percent),tone:"neutral"})]}),c.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",c.notIndexed.length,")"]}),!le()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:C,onClick:Xe(Z),children:C?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!le()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:c.notIndexed.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.httpCode??"—"}),!le()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:C,onClick:()=>{_(T.url)},children:"Submit"})})]},T.id))})]})})]}),(c.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(c.unknown??[]).length,")"]}),!le()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:C,onClick:Xe(Z),children:C?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!le()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(c.unknown??[]).map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.lastCrawledDate?Wt(T.lastCrawledDate):"—"}),!le()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:C,onClick:()=>{_(T.url)},children:"Submit"})})]},T.id))})]})})]}),c.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",c.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:c.indexed.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.lastCrawledDate?Wt(T.lastCrawledDate):"—"})]},T.id))})]})})]})]}),V==="coverage"&&!c&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),V==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!le()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:f,onChange:T=>b(T.target.value),onKeyDown:T=>{T.key==="Enter"&&F()}}),e.jsx(Ye,{size:"sm",disabled:!f.trim(),onClick:Xe(F),children:"Inspect"})]}),h&&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:h.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:h.inIndex?"text-positive-400":"text-negative-400",children:h.inIndex?"Yes":"No"})," · ","HTTP: ",h.httpCode??"—"," · ","Crawled: ",h.lastCrawledDate??"—"]})]}),m.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:m.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(je,{tone:T.inIndex?"positive":"negative",children:T.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Wt(T.inspectedAt)})]},T.id))})]})})]}),V==="performance"&&e.jsx("div",{className:"mt-4",children:p.length===0?e.jsx("p",{className:"text-xs text-muted",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Oa[bn.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Oa[bn.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Oa[bn.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Oa[bn.Position]})]})}),e.jsx("tbody",{children:p.map((T,E)=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:T.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:T.impressions}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:Ze(T.ctr)}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:T.averagePosition.toFixed(1)})]},E))})]})})})]})]})}function Wb({projectName:t}){const s=hs(),[n,a]=o.useState("google"),[r,l]=o.useState(!0),[i,c]=o.useState("idle"),[d,m]=o.useState(null),u=o.useRef(null),[p,x]=o.useState(null),[h,y]=o.useState(null),[f,b]=o.useState(0);async function N($=!1){$||l(!0),m(null);try{const[S,g]=await Promise.all([s.fetchQuery({...Ai({client:Y,path:{name:t}}),staleTime:Ht}).catch(()=>[]),s.fetchQuery({...ac({client:Y,path:{name:t}}),staleTime:Ht}).catch(()=>null)]),v=S.find(C=>C.connectionType==="gsc")??null;x(v),y(g)}catch(S){m(S instanceof Error?S.message:"Failed to load search engine connections")}finally{l(!1)}}async function k(){if(i!=="idle")return;u.current?.abort();const $=new AbortController;u.current=$;const S=$.signal;c("syncing"),m(null),De({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const g=[],v=[];try{async function C(){if(!p)return;const w=await wh(t);if(!w?.id)return;const V=Date.now()+Il;for(;Date.now()<V;){if(S.aborted||(await new Promise(Q=>setTimeout(Q,Pl)),S.aborted))return;const G=await ti(w.id).catch(()=>null);if(!G)break;if(["completed","failed","cancelled"].includes(G.status)){G.status!=="completed"&&g.push(`Google sync ${G.status}`);return}}v.push("Google sync is still running — search data will appear shortly")}async function I(){if(!h?.connected)return;const w=await Sh(t).catch(()=>null);if(!w?.id){g.push("Bing sweep could not be started");return}const V=Date.now()+Il;for(;Date.now()<V;){if(S.aborted||(await new Promise(Q=>setTimeout(Q,Pl)),S.aborted))return;const G=await ti(w.id).catch(()=>null);if(!G)break;if(["completed","failed","cancelled","partial"].includes(G.status)){G.status==="failed"?g.push("Bing sweep failed"):G.status==="partial"&&v.push("Bing sweep finished with some pages unverified");return}}v.push("Bing sweep is still running — coverage will update shortly")}const A=await Promise.allSettled([C(),I()]);for(const w of A)w.status==="rejected"&&g.push(w.reason instanceof Error?w.reason.message:"Sync failed");if(await Promise.all([Et(s,"gsc"),Et(s,"bing")]),S.aborted)return;if(c("reloading"),await N(!0),b(w=>w+1),g.length>0){const w=`Partial refresh: ${[...g,...v].join("; ")}`;m(w),De({title:"Search coverage partially refreshed",detail:w,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else v.length>0?De({title:"Search coverage refresh incomplete",detail:v.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):De({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(C){if(!S.aborted){const I=C instanceof Error?C.message:"Refresh failed";m(I),De({title:"Search coverage refresh failed",detail:I,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{S.aborted||c("idle")}}return o.useEffect(()=>(N(),()=>{u.current?.abort()}),[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([$,S])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===$,className:`project-subnav-link ${n===$?"project-subnav-link-active":""}`,onClick:()=>a($),children:S},$))}),!le()&&e.jsxs(Ye,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{k()},children:[e.jsx(va,{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(Ex,{projectName:t,refreshNonce:f}),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(Hb,{projectName:t,refreshNonce:f})]})]})}function Tl({label:t,summary:s,displayValue:n,tooltip:a}){const{figure:r,sign:l}=Si(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(Fe,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${fa[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 Yb({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(Bn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:r})]})}function Jb({insights:t,suggestedQueries:s,onManageQueries:n}){const{openEvidence:a}=Ci(),r=n?s.rows:[];if(t.length===0&&r.length===0)return null;const l=x=>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:x.title}),x.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:x.detail}):null]}),e.jsx(je,{tone:x.tone,children:x.actionLabel})]}),x.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 · ",x.affectedPhrases.length," affected ",x.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:x.affectedPhrases.map((h,y)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(ri,{state:h.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:h.query}),h.provider?e.jsx(Nh,{provider:h.provider}):null,!le()&&h.evidenceId?e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(h.evidenceId)},children:"View evidence"}):null]},h.evidenceId||`${x.id}-${y}`))})]}):null]},x.id),i=x=>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:x.query}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:x.reason})]}),n?e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},x.query),c=t.slice(0,1),d=r.slice(0,1),m=t.slice(1),u=r.slice(1),p=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:[c.map(l),d.map(i)]}),p>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[p," more ",p===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[m.map(l),u.map(i)]})]}):null]})}function xv(t){const{projectName:s}=od({from:"/projects/$projectName"}),a=Zl()?.dashboard.projects.find(v=>v.project.name===s||v.project.id===s)?.project.name??null,r=Le({...Em({client:Y}),enabled:!a}),l=a??r.data?.find(v=>v.name===s||v.id===s)?.name??null,i=ec(),c=tc(t.tab,sc(i)),[d,m]=o.useState(null),u=l!==null&&d===l,p=o.useCallback(()=>{l&&m(l)},[l]),{commandCenter:x,isLoading:h,overviewLoading:y,overviewError:f,isError:b,latestVisibilityRevision:N,competitorHistoryRevision:k,refetch:$}=nc(l,{overview:c==="overview"&&u}),S=!a&&r.isLoading||h;return!l&&!a&&r.isSuccess&&!h?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(P,{asChild:!0,children:e.jsx(Ts,{to:"/",children:"Return to overview"})})]})}):!x&&(b||r.isError)?e.jsxs("div",{className:"page-container",role:"alert",children:[e.jsx("p",{children:"Could not load this project."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{Promise.all([r.refetch(),$()])},children:"Retry"})]}):!x||S?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(v=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},v))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(v=>e.jsx("div",{className:"skeleton-text-sm w-full"},v))})]})]}):e.jsx(sv,{model:x,refetch:$,latestVisibilityRevision:N,competitorHistoryRevision:k,overviewLoading:y,overviewError:f,overviewRequested:u,onRequestOverview:p,...t})}function Xb({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=o.useRef(null),l=o.useRef(null),[i,c]=o.useState(null);o.useLayoutEffect(()=>{const u=r.current,p=l.current;if(!u||!p)return;const x=()=>{const y=u.getBoundingClientRect().width;if(!y)return;const f=Number.parseFloat(getComputedStyle(u).columnGap)||0,b=new Map([...p.querySelectorAll("[data-project-tab]")].map(v=>[v.dataset.projectTab,v.getBoundingClientRect().width])),N=v=>b.get(v)??0,k=v=>v.reduce((C,I)=>C+N(I),0)+Math.max(0,v.length-1)*f,$=[...t.map(v=>v.key),...s.length?["more"]:[],...n?[n.key]:[]];let S=t.map(v=>v.key),g=!1;if(k($)>y){const v=t.find(A=>A.key===a),C=v?[v.key]:[];g=!!(n&&k([...C,"more",n.key])>y);const I=["more",...n&&!g?[n.key]:[]];for(const A of t)if(A.key!==v?.key){if(k([...C,A.key,...I])>y)break;C.push(A.key)}S=t.filter(A=>C.includes(A.key)).map(A=>A.key)}c(v=>v?.settingsInMore===g&&v.visibleKeys.join()===S.join()?v:{visibleKeys:S,settingsInMore:g})};if(x(),typeof ResizeObserver>"u")return window.addEventListener("resize",x),()=>window.removeEventListener("resize",x);const h=new ResizeObserver(x);return h.observe(u),h.observe(p),()=>h.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(Bn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),d.map(u=>e.jsx(Ts,{to:u.href,search:p=>({...p,onboarding:void 0}),className:`project-subnav-link ${u.key===a?"project-subnav-link-active project-subnav-current":""}`,"aria-current":u.key===a?"page":void 0,children:e.jsx("span",{className:"project-subnav-label",children:u.label})},u.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(Zb,{items:m,activeTab:a}),n&&!i?.settingsInMore&&e.jsx(Ts,{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 Zb({items:t,activeTab:s}){const[n,a]=o.useState(!1),r=o.useRef(null),l=o.useRef(null),i=o.useRef("first"),c=o.useId(),d=t.map(u=>u.key).join();if(o.useEffect(()=>{a(!1)},[d]),o.useEffect(()=>{if(!n)return;const u=r.current?.querySelectorAll('[role="menuitem"]');(i.current==="last"?u?.[u.length-1]:u?.[0])?.focus()},[n]),o.useEffect(()=>{if(!n)return;const u=x=>{r.current&&!r.current.contains(x.target)&&a(!1)},p=x=>{x.key==="Escape"&&(a(!1),l.current?.focus())};return document.addEventListener("pointerdown",u),document.addEventListener("keydown",p),()=>{document.removeEventListener("pointerdown",u),document.removeEventListener("keydown",p)}},[n]),t.length===0)return null;const m=t.some(u=>u.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",ref:l,className:`project-subnav-link project-subnav-more-trigger ${m?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?c:void 0,onClick:()=>{i.current="first",a(u=>!u)},onKeyDown:u=>{u.key!=="ArrowDown"&&u.key!=="ArrowUp"||(u.preventDefault(),i.current=u.key==="ArrowUp"?"last":"first",a(!0))},children:["More",e.jsx(Bn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:c,"aria-label":"More project sections",onKeyDown:u=>{const p=[...u.currentTarget.querySelectorAll('[role="menuitem"]')],x=p.indexOf(document.activeElement),h=u.key==="Home"?0:u.key==="End"?p.length-1:u.key==="ArrowDown"?(x+1)%p.length:u.key==="ArrowUp"?(x-1+p.length)%p.length:null;h!==null&&(u.preventDefault(),p[h]?.focus())},onBlur:u=>{r.current?.contains(u.relatedTarget)||a(!1)},children:t.map(u=>e.jsx(Ts,{to:u.href,search:p=>({...p,onboarding:void 0}),role:"menuitem",tabIndex:-1,className:`project-subnav-menu-item ${u.key===s?"project-subnav-menu-item-active":""}`,"aria-current":u.key===s?"page":void 0,onClick:()=>a(!1),children:u.label},u.key))}):null]})}const ev=20,tv=5;function sv({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r,overviewLoading:l,overviewError:i,overviewRequested:c,onRequestOverview:d}){const m=ld(),u=hs(),{account:p,canWrite:x}=rn(),[h,y]=o.useState(null),f=o.useRef(null),b=Zl(),N=s.project.name,k=b?.dashboard.projects.some(M=>M.project.name===N)??!1,$=cd({strict:!1}),S=_m($),g=up(S),v=Le({...Um({client:Y,path:{name:N}}),enabled:!le()&&!!N&&(x||t==="portfolio"||t==="overview"||t==="settings"||g),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),C=b?b.dashboard.settings.providerStatuses.filter(M=>M.state==="ready").map(M=>co(M.name)):void 0,I=v.data?.answerVisibilityProviderReady,A=C,w=s.project.providers.map(co),V=A?.some(M=>w.length===0||w.includes(M))===!0,G=w.length===0||w.includes(Bm),Q=Le({...Vm({client:Y}),enabled:!le()&&x&&I===void 0&&G&&!V,staleTime:6e4,retry:!1}),B=G?Q.isSuccess?typeof Q.data.browserVersion=="string":Q.isError?!1:void 0:!1,z=I??zm({projectProviders:w,configuredApiProviders:A,cdpConfigured:B}),ne=o.useMemo(()=>sc(ec()),[]),F=tc(t,ne),_=o.useMemo(()=>s.competitors.map(M=>M.domain),[s.competitors]),Z=o.useMemo(()=>Object.fromEntries(s.competitors.map(M=>[M.domain,M.aliases??[]])),[s.competitors]),L=o.useMemo(()=>Object.fromEntries(s.competitors.map(M=>[M.domain,M.autoAliases??[]])),[s.competitors]),ee=o.useMemo(()=>Object.fromEntries(s.competitors.map(M=>[M.domain,[...M.aliases??[],...M.autoAliases??[]]])),[s.competitors]),[T,E]=o.useState(!1),[te,re]=o.useState(!1),ce=Qm(),Ne=o.useCallback((M,ye)=>{m({to:".",search:fe=>Hm(fe,M),replace:ye?.replace===!0})},[m]),X=$.queryWorkspace==="research"||F==="discovery"&&$.queryWorkspace===void 0?"research":"tracked",ue=uc(X,dc(p?.role,p?.role==="viewer"?Wl():null)),pe=Le({...Ii({client:Y,path:{name:N}}),enabled:!le()&&(F==="queries"||F==="discovery")&&ue==="tracked"}),J=$.manageQueries===!0,me=o.useCallback(()=>{m({to:".",replace:!0,search:M=>({...M,siteHealthRunId:void 0})})},[m]),[K,he]=o.useState(J),[qe,Re]=o.useState(""),[ie,ge]=o.useState(!1),[we,_e]=o.useState(null),[Ee,O]=o.useState("30d"),[D,H]=o.useState(void 0),[Me,Qe]=o.useState(""),[Ge,et]=o.useState(!1),[xe,jt]=o.useState(null),[ze,Je]=o.useState(!1),Ot=Wm($),[dt,st]=o.useState(void 0),[ht,kt]=o.useState(void 0),Mt=o.useCallback(M=>{st(M.search),M.sort&&kt(M.sort),m({to:".",search:ye=>({...ye,...Ym(M)}),replace:!1})},[m]),[He,R]=o.useState(!1),$e=s?.project.displayName||s?.project.name||N,Te=Jm(),Ue=Le({...uo({client:Y,path:{name:N}}),enabled:F==="portfolio"&&!!N,staleTime:0,refetchOnMount:"always"}),ut=Le({...Xm({client:Y,path:{name:N}}),enabled:!le()&&!!N&&(x||ms()||F==="portfolio"||F==="overview"||F==="settings"),staleTime:0,refetchOnMount:"always"}),Be=ut.data?.active??null,yt=ut.data!==void 0,se=new Set(Be&&Number(Be.plan.schemaVersion)===2?Be.plan.groups?.map(M=>M.stableKey)??[]:[]),Ie={...Ot.scope==="group"&&!!Ot.groupKey&&yt&&!se.has(Ot.groupKey)?{scope:"all",queryClass:Ot.queryClass}:Ot,...dt?{search:dt}:{}},be=Be===null?null:Number(Be.plan.schemaVersion),$t=Be?.revision??0,Yt=yt?`${N}:${$t}`:null,Jt=o.useRef(null);o.useEffect(()=>{const M=Jt.current;Yt!==null&&(Jt.current=Yt),Zm(M,Yt)&&(Mt({scope:"all",queryClass:"all"}),R(!1))},[Yt,Mt]);const Ft={client:Y,path:{name:N},query:{scope:Ie.scope,...Ie.groupKey?{groupKey:Ie.groupKey}:{},queryClass:Ie.queryClass,...Ie.search?{search:Ie.search}:{},...ht?{sort:ht}:{},limit:50}},mt=Ml({...eh(Ft),enabled:!1,initialPageParam:Ft,getNextPageParam:(M,ye)=>{if(!M.properties.nextCursor)return;const fe=ye[0]?.measurement.displayedRunId;return{path:Ft.path,query:{...Ft.query,cursor:M.properties.nextCursor,...fe?{runId:fe}:{}}}},placeholderData:wi,staleTime:0,refetchOnMount:"always"}),Zt=mt.data?.pages[0]?.measurement.displayedRunId,ot=Le({...th({client:Y,path:{name:N},query:{revision:$t,...Zt?{runId:Zt}:{}}}),enabled:F==="overview"&&!!N&&Be!==null&&be===1,staleTime:0,refetchOnMount:"always"}),fs=ut.data!==void 0,ps=Ue.data!==void 0,Ks=ut.isPending&&!fs,bt=ut.isError&&!fs,_s=Ue.isPending&&!ps,Lt=Ue.isError&&!ps,ss=ot.data!==void 0,Vt=kb({activePlanSchemaVersion:v.data?.activeSchemaVersion??be,hasDraft:v.data?.draft!==null&&v.data?.draft!==void 0}),pt=Vt.surface==="simple-overview",$s=ms()&&Be?.plan.schemaVersion===2?Ab(Be.plan):null,Rt=v.data===void 0&&ut.data===void 0&&(ut.isLoading||v.isLoading);o.useEffect(()=>{F==="overview"&&pt&&!Rt&&d()},[Rt,pt,d,F]);const Ls=mp({tab:F,surface:Rt?"unresolved":Vt.surface,embedded:le(),scoped:g,queryWorkspace:ue,tracking:pe.isError?{state:"error"}:pe.data?{state:"ready",mode:pe.data.mode,scopeUnavailable:mc(pe.data,S)}:{state:"pending"}}),Xt=Mc(N,S,{enabled:Ls.kind==="report-picker"}),Pt=F==="overview"&&pt&&!Rt,Gt=nc(N,{evidence:Pt}),nt=Gt.commandCenter?.visibilityEvidence??s.visibilityEvidence,xs=o.useMemo(()=>{const M=new Map(nt.map(fe=>[Kn(fe.query),fe.queryClass??null])),ye=sh(nh(s.project));return fe=>{const ft=M.get(Kn(fe));return ft!==void 0?ft:ye?.classify(fe)??null}},[nt,s.project]),ys=o.useMemo(()=>[...new Set([...nt.map(M=>M.query),...s.movementComparison.addedQueries,...s.movementComparison.removedQueries])],[nt,s.movementComparison]),U=o.useMemo(()=>s.visibilitySweeps.map(M=>M.createdAt),[s.visibilitySweeps]),oe=x&&!le()&&!cs()&&F!=="overview",ke=Le({...uo({client:Y,path:{name:N}}),enabled:oe,staleTime:Ri,refetchOnWindowFocus:"always"}),ae=be===2&&S.measurementScope==="group"?S.measurementScopeKey:void 0,Pe=be===2&&S.measurementScope==="project",Ke=o.useMemo(()=>{if(!(Be?.plan.schemaVersion!==2||!ae))return Be.plan.groups.find(M=>M.stableKey===ae)},[Be,ae]),gt={client:Y,path:{name:N},query:{window:Ee,queryClass:be===2&&S.queryClass!=="unknown"?S.queryClass:"non-brand",...ae?{groupKey:ae}:{},...Pe?{scope:"all-markets"}:{}}},vt=F==="overview"&&!S.marketKey&&!!N&&(pt||yt)&&!Rt&&(pt||(S.measurementScope==="project"||be===2&&S.measurementScope==="group")&&S.queryClass!=="unknown"&&(be===2||S.queryClass!=="branded")),[Us,q]=o.useState(null);o.useEffect(()=>{vt||q(null)},[vt]),o.useEffect(()=>{q(null)},[N]);const Ae=Us===N,at=vt&&Ae,Nt=Le({...ah(gt),enabled:at,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});rh(N,JSON.stringify([r,s.competitors.map(M=>`${M.domain}=${[...M.aliases??[],...M.autoAliases??[]].join("|")}`).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,$t,v.data?.draft?.etag??null]),at);const es=Nt.isError?Nt.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,Oe=o.useMemo(()=>s.competitors.map(M=>({domain:M.domain,label:M.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:M.citationCount,answeredResults:M.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),St=o.useMemo(()=>{if(Be?.plan.schemaVersion!==2)return Oe;const M=ae?Ke?.competitors??[]:Be.plan.groups.flatMap(fe=>fe.competitors),ye=new Map;for(const fe of M){const ft=fe.domain.trim().toLowerCase();!ft||ye.has(ft)||ye.set(ft,{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 Oe){const ft=fe.domain.trim().toLowerCase();!ft||ye.has(ft)||ye.set(ft,fe)}return[...ye.values()]},[Be,ae,Oe,Ke]),Bs=be===2?St:Oe,Wn=Dt({...ih({client:Y}),meta:{skipGlobalErrorToast:!0}}),ns=v.data!==void 0?"success":v.isError?"error":"pending",Yn=o.useMemo(()=>{const M=mt.data?.pages;return M?!Oh(M):!1},[mt.data]),It=o.useMemo(()=>{const M=mt.data?.pages,ye=M?.[0],fe=M?.at(-1);if(!(!ye||!fe||Yn))return{...ye,properties:{...ye.properties,items:M.flatMap(ft=>ft.properties.items),nextCursor:fe.properties.nextCursor}}},[Yn,mt.data]),bs=o.useMemo(()=>{if(Be)return Be.plan.schemaVersion===1?ot.data?qb(Be,ot.data):void 0:It?Fh({overview:It,activePlan:Be,sort:ht,report:ot.data,reportState:It.measurement.displayedRunId===void 0?"ready":ot.isFetching&&ot.data===void 0?"loading":ot.isError&&ot.data===void 0?"error":ot.data?"ready":"loading"}):void 0},[Be,ot.data,ot.isError,ot.isFetching,It]),Jn=be===2?Yn?"error":mt.isPending?"loading":mt.isError&&bs===void 0?"error":"ready":ot.isPending&&!ss?"loading":ot.isError&&!ss?"error":"ready",Vs=(s?.recentRuns??[]).some(M=>M.kind===Gs["answer-visibility"]&&(M.status===Is.running||M.status===Is.queued)),Xn=s.queryCounts.total>0,Ia=o.useMemo(()=>(s?.project.locations??[]).map(M=>M.label),[s?.project.locations]),on=o.useMemo(()=>new Set(nt.map(M=>M.location??"")),[nt]),Zn=on.has(""),Sn=o.useMemo(()=>[...new Set(nt.map(M=>M.query))].sort((M,ye)=>M.localeCompare(ye)),[nt]),zs=Sn.length>0||s.queryCounts.total>0||(ke.data?.length??0)>0||Be!==null,Ma=x&&!zs&&(ut.data===void 0&&ut.isPending||ke.isLoading||Pt&&Gt.evidenceLoading),ln=x&&(v.isError&&!v.isFetching||oe&&ke.isError&&!ke.isFetching),kn=x&&!ln&&(Ma||z===void 0||v.isFetching),cn=!kn&&!ln&&zs&&z===!0,ea=x&&!kn&&!cn,vs=!le()&&F==="overview"&&ea&&!zs,ta=Le({...oh({client:Y,path:{name:N},query:{limit:ev}}),enabled:vs&&!!N,retry:!1}),sa=ta.isSuccess&&ta.data.scans.some(M=>M.status==="completed"||M.status==="partial"),$a=vs&&ta.isSuccess&&!sa,La=vs&&sa,Qs=Le({...Xl({client:Y,path:{name:N}}),enabled:!le()&&!cs()&&!!N,retry:!1}).data?.find(M=>M.kind===Gs["answer-visibility"]),na=Qs?.enabled&&Qs.nextRunAt?lh(Qs.nextRunAt,Qs.timezone):null,aa=na?`Next AI sweep ${na}`:null,br=o.useMemo(()=>{const M=[...on].filter(Boolean);return M.length>1?M:Ia},[on,Ia]);o.useEffect(()=>{if(!Pt||D===void 0||D===""||!N){jt(null),Je(!1);return}Je(!0),ch(N,D,20).then(M=>{jt(M),Je(!1)}).catch(()=>{jt(null),Je(!1)})},[D,N,Pt]);const An=o.useMemo(()=>{if(!xe)return null;const M=new Map;for(const ye of xe){for(const[fe,ft]of Object.entries(ye.providerRuns??{}))M.set(`${ye.query}::${fe}`,ft.map(ws=>({runId:ws.runId,citationState:ws.citationState,createdAt:ws.createdAt,answerMentioned:ws.answerMentioned,visibilityState:ws.visibilityState,visibilityTransition:ws.visibilityTransition,mentionState:ws.mentionState,mentionTransition:ws.mentionTransition})));(!ye.providerRuns||Object.keys(ye.providerRuns).length===0)&&M.set(`${ye.query}::`,ye.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 M},[xe]),qa=o.useMemo(()=>{const M=D!==void 0?nt.filter(ye=>D===""?!ye.location:ye.location===D):nt;return An?M.map(ye=>{const fe=An.get(`${ye.query}::${ye.provider}`)??An.get(`${ye.query}::`);return fe?{...ye,runHistory:fe}:ye}):M},[nt,D,An]);async function Ea(){if(!(h!==N||!x||le()||cs()||Te.isPending||Vs||!cn))try{await Te.mutateAsync({projectName:N,projectLabel:$e,sourceAction:"project-run"}),y(null)}catch{}}function j(){m({to:"/setup",search:{experience:"legacy",setupProject:N}})}function W(){m({to:"/projects/$projectName/technical-aeo",params:{projectName:N}})}async function de(){re(!0);try{await jh(N),De({title:"Project deleted",detail:`${$e} was removed.`,tone:"positive",dedupeKey:`project:delete:${N}`,dedupeMode:"drop"}),await m({to:"/"})}catch(M){console.error("Failed to delete project:",M)}finally{re(!1)}}async function Se(){const M=qe.split(`
7
+ `).map(ye=>ye.trim()).filter(Boolean);if(M.length!==0){ge(!0);try{await ph(N,M),Re("")}finally{ge(!1)}}}async function rt(M){_e(M);try{await hh(N,[M])}catch(ye){De({title:"Could not remove query",detail:ye instanceof Error?ye.message:`Failed to remove "${M}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{_e(null)}}async function tt(M){const ye=M.trim();if(!ye)return!1;try{return await uh(N,[ye]),!0}catch(fe){return De({title:"Could not add competitor",detail:fe instanceof Error?fe.message:`Failed to add ${ye}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function xt(M){const ye=s.competitors.find(fe=>fe.domain===M);if(!ye)return De({title:"Could not remove competitor",detail:`Could not find ${M} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await mh(N,ye.id),!0}catch(fe){return De({title:"Could not remove competitor",detail:fe instanceof Error?fe.message:`Failed to remove ${ye.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function qt(M){const ye=M.trim();if(!ye||!ae||be!==2||!x||le()||Wn.isPending)return!1;try{const fe=await Wn.mutateAsync({client:Y,path:{name:N},headers:{"Idempotency-Key":zb()},body:{expectedActiveRevision:$t,groupKey:ae,domain:ye}});return Promise.allSettled([v.refetch()]),De({title:fe.draftCreated?"Competitor added to a market draft":"Market competitor updated",detail:`Publish the Advanced Measurement draft before ${ye} is used in future market runs.`,tone:"positive",dedupeKey:`competitor:market-pin:${ae}:${ye}`,dedupeMode:"replace"}),!0}catch(fe){return De({title:"Could not add market competitor",detail:fe instanceof Error?fe.message:`Failed to add ${ye} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function it(M,ye){const fe=await bh(M,ye);return u.setQueryData(vh({client:Y,path:{name:M}}),fe),Qb(u,fe),fe}const Ce=`/projects/${encodeURIComponent(s.project.name)}`,js=[{key:"overview",label:"AI Visibility",href:Ce},{key:"search-console",label:"Search Engines",href:`${Ce}/search-console`},{key:"activity",label:"Activity",href:`${Ce}/activity`},{key:"technical-aeo",label:"Site Health",href:`${Ce}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${Ce}/conversions`},{key:"local",label:"Local Presence",href:`${Ce}/local`},{key:"queries",label:"Queries",href:`${Ce}/queries`},{key:"backlinks",label:"Backlinks",href:`${Ce}/backlinks`}],dn=[{key:"history",label:"Change History",href:`${Ce}/history`}],Rn=js.filter(M=>Ar(M.key,ne)),Ns=dn.filter(M=>Ar(M.key,ne)),vr=Ar("settings",ne)?{key:"settings",label:"Settings",href:`${Ce}/settings`}:null;function ad(M){const ye=pt?M:e.jsx(Og,{projectName:N,selection:S,showUnmeasuredFallback:!Be&&!Xn&&S.measurementScope==="project"&&S.queryClass==="all"&&!S.provider&&!S.model&&!S.location&&!S.from&&!S.to&&!S.revision&&!S.measurementRunId&&!S.queryKey&&!S.marketKey,onSelectionChange:Ne,onManageQueries:le()?void 0:()=>{m({to:"/projects/$projectName/queries",params:{projectName:N},search:ft=>({...ft,queryWorkspace:"tracked",trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:le()?void 0:({id:ft,label:ws})=>e.jsx(Ts,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:N,targetKey:ft},search:xh,"aria-label":`Property details for ${ws}`,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:M});if(le())return ye;let fe=gh(S,pt?"simple":"advanced",typeof $.sentimentEvaluationDefinitionId=="string"?$.sentimentEvaluationDefinitionId:void 0);return pt&&(fe.location=D===""?"none":D,fe=fh(fe,qa,Me)),e.jsx(yh,{hasSourceEvidence:!pt||!!(fe.runId||fe.runIds?.length),evidenceReady:!pt||!(Gt.isLoading||Gt.evidenceLoading||Gt.evidenceError),waitForResolvedRun:!pt,projectName:N,runOptions:s.visibilitySweeps.slice(0,tv).map(ft=>({id:ft.id,label:Wt(ft.finishedAt??ft.createdAt)})),selection:fe,children:ye})}function rd(){switch(Ls.kind){case"report-picker":{if(Xt.error)return zl(Ql(Xt.error))?e.jsx("p",{className:"text-[13px] text-secondary",children:Fa.savedScopeUnavailable}):null;const M=Xt.data;if(!M)return e.jsx("div",{className:"skeleton-text h-11 w-56",role:"status","aria-label":"Loading measurement scope"});if(M.selection.availability.state!=="available"||M.scopeOptions.length<=1)return null;const ye=ai(M.scopeOptions,S)??M.selection.scope;return e.jsx(ho,{labelVisibility:"sr-only",options:M.scopeOptions,selected:ye,marketKey:S.marketKey,onSelect:(fe,ft)=>Ne({measurementScope:fe.kind,measurementScopeKey:fe.kind==="project"?void 0:fe.id,measurementMarketKey:ft})})}case"tracking-picker":{const M=pe.data?.scopeOptions??[],ye=ai(M,S);return ye?e.jsx(ho,{labelVisibility:"sr-only",options:M,selected:ye,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:Fa.savedScopeUnavailable});case"project-wide":return e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[13px] text-secondary",children:Fa.projectWide}),e.jsx(Fe,{text:Fa.projectWideHelp})]});case"none":return null}}const Ji=F==="overview"&&!pt&&(S.from||S.to)?`${S.from?.slice(0,10)??"First measurement"} to ${S.to?.slice(0,10)??"Latest measurement"}`:null,Xi=rd(),Zi=vt?e.jsx(Rp,{window:Ee,landscape:Nt.data,pinnedFallback:Bs,competitorAliases:Z,competitorAutoAliases:L,canWrite:x,isEmbed:le(),onWindowChange:O,onPin:ae&&x&&!le()?qt:!Pe&&x&&!le()?tt:void 0,onUnpin:ae||Pe||!x||le()?void 0:xt,onAddCompetitor:ae&&x&&!le()?qt:!Pe&&x&&!le()?tt:void 0,error:es,onRetry:at?()=>{Nt.refetch()}:void 0,isLoading:at&&Nt.isPending&&Nt.data===void 0,scopeLabel:ae?`${Ke?.label??ae} group`:Pe?"All markets":"Project-wide"}):null,jr=le()?null:e.jsx(e.Fragment,{children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>he(!K),children:K?"Done":"Manage queries"})}),eo=!le()&&K?e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[Sn.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:Sn.map(M=>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:M,children:M}),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 ${M}`,title:`Stop tracking "${M}"`,disabled:we!==null,onClick:()=>{rt(M)},children:we===M?"Removing…":"Remove"})]},M))}):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:qe,onChange:M=>Re(M.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[qe.split(`
8
+ `).filter(M=>M.trim()).length," to add"]}),e.jsx(Ye,{type:"button",size:"sm",disabled:!qe.trim()||ie,onClick:Xe(Se),children:ie?"Adding...":"Add queries"})]})]}):null;return e.jsxs("div",{className:"page-container",children:[le()?e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain," · ",s.contextLabel]})]}),e.jsx("div",{className:cs()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:Ji!==null?e.jsx("p",{className:"text-sm text-muted",children:Ji}):null})]}):e.jsxs("div",{className:"project-context-row",children:[e.jsx("h1",{className:"project-context-title md:sr-only",children:s.project.displayName||s.project.name}),Xi!==null?e.jsx("div",{className:"project-context-scope",children:Xi}):null,s.project.canonicalDomain?e.jsx("span",{className:"project-context-domain",children:s.project.canonicalDomain}):null,$s!==null?e.jsxs("span",{className:"project-mode-tag",children:[e.jsx("span",{className:"project-mode-tag-label",children:"Advanced"}),e.jsx("span",{className:"project-mode-tag-detail",children:$s})]}):null,e.jsx("div",{className:"project-context-actions","data-project-actions":!0,children:cs()?e.jsx(dh,{projectName:N,running:Vs,portfolio:!pt}):e.jsxs(e.Fragment,{children:[aa?e.jsx("p",{className:"text-sm text-secondary",children:aa}):null,$a?e.jsx(Ye,{type:"button",onClick:W,children:"Map site"}):La?e.jsx(Ye,{type:"button",onClick:W,children:"View Page Health"}):null,e.jsx(Ye,{type:"button",variant:"outline",disabled:Te.isPending||Vs||kn,onClick:ln?()=>{Promise.all([v.refetch(),...oe?[ke.refetch()]:[]])}:ea?j:M=>{f.current=M.currentTarget,y(N)},children:Te.isPending?"Starting…":Vs?"AI sweep running…":kn?"Checking AI readiness…":ln?"Retry AI readiness":ea?"Set up AI Visibility":"Run AI sweep"})]})})]}),!le()&&!cs()&&e.jsx(Vb,{open:h===N,projectLabel:$e,onOpenChange:M=>y(M?N:null),onConfirm:Xe(Ea),onClosed:()=>f.current?.focus(),disabled:Te.isPending||Vs||!cn}),e.jsx(Xb,{items:Rn,overflowItems:Ns,settingsItem:vr,activeTab:F}),F==="portfolio"&&!le()?e.jsx(ob,{projectName:N,canEdit:x,queries:Ue.data??[],isQueryLoading:_s,isQueryError:Lt,onRetryQueries:()=>{Ue.refetch()},publishedPlan:Be,onCreateQueries:async M=>(await ce.mutateAsync({projectName:N,queries:[...M]}),(await Ue.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{m({to:"/projects/$projectName",params:{projectName:N},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([v.refetch(),ut.refetch()]).finally(()=>{m({to:"/projects/$projectName",params:{projectName:N}})})}},N):F==="overview"?Rt||pt&&!k&&(!c||l)?e.jsxs("div",{role:"status","aria-live":"polite",children:[e.jsx("span",{className:"sr-only",children:"Loading project overview"}),e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-hidden":"true"})]}):pt&&i?e.jsxs("div",{role:"alert",className:"page-section-divider",children:[e.jsx("p",{children:"Could not load AI visibility."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[bt?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(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{ut.refetch()},children:"Retry setup check"})]}):null,ad(e.jsx(Rb,{mode:Vt,canEdit:x&&!le()&&!Ks&&!bt,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(tf,{projectName:s.project.name,competitorDomains:_,competitorAliases:ee,analyticsRevision:a,queryTexts:ys,classifyQuery:xs,sweepTimes:U})}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"av-card-head",children:[e.jsx("h2",{className:"av-card-title",children:"Where competitors are winning"}),Xn?e.jsx("p",{className:"av-card-meta",children:"Latest sweep"}):null]}),Xn?e.jsxs("div",{className:"competitive-summary",children:[e.jsx(fp,{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(Tl,{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(Tl,{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(pg,{projectName:s.project.name,classify:xs,hasCompetitors:_.length>0,providerScores:s.providerScores})}),e.jsxs(Yb,{id:"evidence-section",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${D===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":D===void 0,onClick:()=>{H(void 0)},children:"All locations"}),s.project.locations.map(M=>e.jsx("button",{className:`filter-chip ${D===M.label?"filter-chip-active":""}`,type:"button","aria-pressed":D===M.label,onClick:()=>{H(M.label),et(!1)},children:M.label},M.label)),Zn&&e.jsx("button",{className:`filter-chip ${D===""?"filter-chip-active":""}`,type:"button","aria-pressed":D==="",onClick:()=>{H(""),et(!1)},children:"No location"}),br.length>1&&D===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${Ge?"filter-chip-active":""}`,type:"button","aria-pressed":Ge,onClick:()=>et(M=>!M),title:"Side-by-side location comparison",children:"Compare"})]}),Gt.evidenceLoading||Gt.evidenceError?e.jsxs(e.Fragment,{children:[jr&&e.jsx(wc,{actions:jr}),eo,Gt.evidenceLoading?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading query evidence…"}):e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load query evidence."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{Gt.refetch()},children:"Retry"})]})]}):e.jsx(ox,{evidence:qa,compareLocations:Ge,providerSelection:Me,onProviderSelectionChange:Qe,addedQueries:s.movementComparison.addedQueries,actions:jr,actionPanel:eo})]}),!le()&&e.jsx("div",{className:"page-section-divider",children:e.jsx(gg,{runs:s.recentRuns,collapsed:!0})})]}),report:bs,reportState:Jn,onOpenSetup:le()?void 0:()=>{m({to:"/projects/$projectName/portfolio",params:{projectName:N}})},onRetryReport:()=>{be===2?Promise.all([mt.refetch(),ot.refetch()]):ot.refetch()},onViewChange:M=>{Mt({scope:M.scope,...M.groupKey?{groupKey:M.groupKey}:{},queryClass:M.queryClass,...M.search?.trim()?{search:M.search.trim()}:{}})},onLoadMore:M=>{M===It?.properties.nextCursor&&mt.fetchNextPage()},onPropertyExpand:()=>{He&&ot.isError&&ot.refetch(),R(!0)},onRetryEvidence:()=>{ot.refetch()},isViewLoading:mt.isPlaceholderData,isLoadingMore:mt.isFetchingNextPage,isLoadMoreError:mt.isFetchNextPageError,viewSearch:Ie.search??""},`${N}:${$t}`)),!pt&&S.measurementScope==="project"?e.jsxs("details",{className:"visibility-disclosure",onToggle:M=>{M.currentTarget.open&&d()},children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Project signals"})}),!c||l?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading project signals…"}):i?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load project signals."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsx(Jb,{insights:s.insights,suggestedQueries:s.suggestedQueries,onManageQueries:le()?void 0:()=>{m({to:"/projects/$projectName/queries",params:{projectName:N},search:M=>({...M,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]},N):null,Zi!==null?e.jsxs("details",{className:`visibility-disclosure${pt?" page-section-divider":""}`,open:Ae,onToggle:M=>q(M.currentTarget.open?N:null),children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Competitor history"})}),e.jsx("div",{className:"visibility-disclosure-panel",children:Zi})]}):null]}):F==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(Eb,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(M,ye)=>{await it(M,ye)}}),e.jsx(Ob,{project:s.project,onSave:async M=>{await it(s.project.name,M)}}),e.jsx(Gb,{project:s.project,onSave:async M=>{await it(s.project.name,{siteAuditMaxPages:M})}},s.project.id),x&&!le()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Advanced measurement"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Measure individual properties, locations, or site sections with separate query sets."}),ns==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):ns==="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(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{v.refetch()},children:"Retry"})]}):e.jsx(P,{type:"button",variant:"outline",onClick:()=>{m({to:"/projects/$projectName/portfolio",params:{projectName:N}})},children:nd(Vt.setupAction)})]}):null,e.jsx(_b,{projectName:s.project.name}),e.jsx(Bb,{projectName:s.project.name}),x&&!le()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-negative-400",children:"Delete project"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Permanently deletes this project and all its queries, competitors, runs, and snapshots."}),T?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(P,{type:"button",variant:"destructive",disabled:te,onClick:Xe(de),children:te?"Deleting...":"Yes, delete project"}),e.jsx(P,{type:"button",variant:"outline",disabled:te,onClick:()=>E(!1),children:"Cancel"})]})]}):e.jsxs(Ye,{type:"button",variant:"outline",onClick:()=>E(!0),children:[e.jsx(cc,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):F==="queries"||F==="discovery"?e.jsx(hf,{projectName:N,queryWorkspace:X,onQueryWorkspaceChange:M=>Ne({queryWorkspace:M,trackingQueryId:void 0}),researchMode:$.researchMode==="test"?"test":"find",onResearchModeChange:M=>Ne({researchMode:M}),selection:S,onSelectionChange:Ne,trackingQueryId:typeof $.trackingQueryId=="string"?$.trackingQueryId:void 0,onTrackingQueryIdChange:M=>Ne({trackingQueryId:M})}):F==="technical-aeo"?e.jsx(Eh,{projectName:s.project.name,projectId:s.project.id,initialRunId:$.siteHealthRunId,onReleaseInitialRun:me}):F==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(wy,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(cy,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):F==="history"?e.jsx(Ff,{projectName:s.project.name}):F==="activity"?e.jsx(Nx,{projectName:s.project.name}):F==="backlinks"?e.jsx(og,{projectName:s.project.name}):F==="local"?e.jsx(Ox,{projectName:s.project.name,projectId:s.project.id}):F==="search-console"?e.jsx(Wb,{projectName:s.project.name}):null]})}export{xv as ProjectPage,Xb as ProjectSubnav,Vb as ProjectSweepConfirmation,Qb as patchProjectDashboardCache};