@canonry/canonry 4.172.1 → 4.172.3

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 (31) hide show
  1. package/assets/agent-workspace/skills/aero/references/reporting.md +8 -4
  2. package/assets/agent-workspace/skills/canonry/references/aeo-analysis.md +1 -1
  3. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +4 -3
  4. package/assets/assets/{AuditHistoryPanel-BO_TSFPx.js → AuditHistoryPanel-DF8utxHN.js} +1 -1
  5. package/assets/assets/{BacklinksPage-CNrzKbiR.js → BacklinksPage-Hz5fjTP-.js} +1 -1
  6. package/assets/assets/{HistoryPage-CvzLzfj3.js → HistoryPage-EeNWcnRk.js} +1 -1
  7. package/assets/assets/{MeasurementPropertyPage-CUdAqft3.js → MeasurementPropertyPage-CWvVMiIo.js} +1 -1
  8. package/assets/assets/ProjectPage-CBVwd4DJ.js +9 -0
  9. package/assets/assets/{RunRow-BLZsQTiY.js → RunRow-CLwmqMWg.js} +1 -1
  10. package/assets/assets/{RunsPage-CTuTDUcn.js → RunsPage-Cxc9xDm9.js} +1 -1
  11. package/assets/assets/{SettingsPage-BY-nM5uj.js → SettingsPage-gg7QM6am.js} +1 -1
  12. package/assets/assets/{SiteHealthSection-br9-ha8G.js → SiteHealthSection-DhpNThBa.js} +3 -3
  13. package/assets/assets/{TrafficPage-BgX1QlXy.js → TrafficPage-BkDwv0uO.js} +1 -1
  14. package/assets/assets/{TrafficSourceDetailPage-D5bsBc6A.js → TrafficSourceDetailPage-gyh7Kxb3.js} +1 -1
  15. package/assets/assets/{extract-error-message-BywQFP69.js → extract-error-message-DVQ46FzX.js} +1 -1
  16. package/assets/assets/{index-BpHZirJJ.js → index-ClNW_gZV.js} +27 -27
  17. package/assets/assets/index-D1mXm81Z.css +1 -0
  18. package/assets/assets/{react-sigma_core.esm.min-Do4rkEBs.js → react-sigma_core.esm.min-BhFLGF9e.js} +1 -1
  19. package/assets/index.html +2 -2
  20. package/dist/{chunk-5MRE2TXR.js → chunk-BZDNTUCZ.js} +8 -5
  21. package/dist/{chunk-IAX4WRAR.js → chunk-OHSUOEVB.js} +4 -4
  22. package/dist/{chunk-7L4453BU.js → chunk-WFVK3XC7.js} +2 -2
  23. package/dist/{chunk-X63CLHYM.js → chunk-WGN2VT7L.js} +4797 -4680
  24. package/dist/{chunk-3XN226N6.js → chunk-XEWBDO5L.js} +767 -247
  25. package/dist/cli.js +71 -14
  26. package/dist/index.js +4 -4
  27. package/dist/{intelligence-service-FSHZXSGK.js → intelligence-service-PPYG6NJP.js} +2 -2
  28. package/dist/mcp.js +3 -3
  29. package/package.json +11 -11
  30. package/assets/assets/ProjectPage-xbRWsne7.js +0 -9
  31. package/assets/assets/index-BsQGKWA6.css +0 -1
@@ -0,0 +1,9 @@
1
+ import{j as e,r as o,L as Xt,n as bs,u as Re,o as Ft,B as mr,C as So,h as Co,k as ko,D as Ao}from"./vendor-tanstack-Dock0eH1.js";import{T as de,t as Po,a as Io,u as hr,C as Ro,P as zs,B as A,h as $o,b as To,c as Lo,d as pe,i as ne,e as ht,f as Te,I as Ke,g as Xs,j as Mo,k as V,l as Do,m as Eo,n as qo,o as Go,p as xr,q as Oo,r as Fo,S as As,s as _o,v as Bo,w as Cs,x as Tt,y as Uo,z as oi,A as pr,G as vt,D as Ea,E as Vo,F as zo,H as Ko,J as Qo,K as li,L as Ce,M as gr,N as Ho,O as sa,Q as Wo,R as Yo,U as Xo,V as Jo,W as Zo,X as el,Y as tl,Z as sl,_ as nl,$ as al,a0 as il,a1 as rl,a2 as ol,a3 as ll,a4 as cl,a5 as fr,a6 as Ts,a7 as dl,a8 as br,a9 as Fn,aa as ul,ab as Qe,ac as ml,ad as hl,ae as xl,af as _n,ag as pl,ah as gl,ai as fl,aj as Ks,ak as bl,al as vl,am as yl,an as vr,ao as Ca,ap as jl,aq as yr,ar as Nl,as as qa,at as wl,au as Sl,av as Cl,aw as jr,ax as kl,ay as Al,az as Pl,aA as rn,aB as Ps,aC as Il,aD as Rl,aE as $l,aF as Tl,aG as Nr,aH as Ll,aI as Ml,aJ as Dl,aK as El,aL as ql,aM as wr,aN as Gl,aO as Ol,aP as Fl,aQ as _l,aR as Bl,aS as Ul,aT as Vl,aU as zl,aV as Kl,aW as Ql,aX as Hl,aY as Wl,aZ as Yl,a_ as Xl,a$ as Jl,b0 as Zl,b1 as ec,b2 as us,b3 as nt,b4 as tc,b5 as sc,b6 as nc,b7 as ac,b8 as ic,b9 as rc,ba as oc,bb as lc,bc as cc,bd as dc,be as uc,bf as mc,bg as hc,bh as xc,bi as pc,bj as gc,bk as fc,bl as bc,bm as vc,bn as yc,bo as jc,bp as Nc,bq as wc,br as Sc,bs as Cc,bt as kc,bu as Ac,bv as Pc,bw as Ic,bx as Rc,by as $c,bz as Tc,bA as Lc,bB as Mc,bC as Dc,bD as Ec,bE as qc,bF as Gc,bG as na,bH as Oc,bI as Fc,bJ as ci,bK as _c,bL as Bc,bM as Uc,bN as Vc,bO as zc,bP as Kc,bQ as Qc,bR as Hc,bS as Wc,bT as Yc,bU as Xc,bV as Jc,bW as Sr,bX as Zc,bY as ed,bZ as td,b_ as sd,b$ as nd,c0 as ad,c1 as id,c2 as di,c3 as rd,c4 as aa,c5 as od,c6 as ld,c7 as cd,c8 as dd,c9 as ud,ca as md,cb as hd,cc as xd,cd as Cr,ce as kr,cf as pd,cg as gd,ch as fd,ci as bd,cj as vd,ck as wn,cl as yd,cm as jd,cn as Nd,co as ui,cp as wd}from"./index-ClNW_gZV.js";import{R as Sd}from"./RunRow-CLwmqMWg.js";import{u as Bn,D as on,a as _s,b as Cd,M as qn,c as ss,S as kd}from"./SiteHealthSection-DhpNThBa.js";import{e as Ad,q as Un,U as Pd,r as Id,L as Rd,s as Ar,i as $d,P as Vn,D as Pr,t as Td,u as Ld,E as Md,C as zn,v as Dd}from"./vendor-lucide-nYKv-BB7.js";import{f as Kn,C as Ls,a as Yt,b as Is,c as Bs,d as Bt,e as yt,g as Rs,M as Ed,h as Ir,i as Rr,o as fs,j as $s,p as qd}from"./ChartPrimitives-BoYe2M-i.js";import{u as Gd,t as Od,e as Fd,a as ut}from"./extract-error-message-DVQ46FzX.js";import{R as dn,C as un,X as mn,Y as hn,T as xn,L as $r,A as Os,a as Tr,b as _d,d as Lr,e as Bd}from"./vendor-recharts-D8rt5lKn.js";import{A as Ud}from"./AuditHistoryPanel-DF8utxHN.js";import{a as Vd,b as zd}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-4UOaVWza.js";import"./vendor-markdown-Bn7fRwrx.js";import"./vendor-yaml-GWJz5H2G.js";function Gn(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function Kd(t,s,n=800){const a=[];if(!/^\d{4}-\d{2}-\d{2}$/.test(t)||!/^\d{4}-\d{2}-\d{2}$/.test(s))return a;for(let i=t;i<=s&&(a.push(i),!(a.length>=n));i=Qd(i,1));return a}function Qd(t,s){if(!Number.isFinite(s))return t;const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n?.[1]||!n[2]||!n[3])return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+Math.trunc(s)));if(Number.isNaN(a.getTime()))return t;const i=a.getUTCFullYear(),r=String(a.getUTCMonth()+1).padStart(2,"0"),l=String(a.getUTCDate()).padStart(2,"0");return`${i}-${r}-${l}`}function Hd(t,s){if(!Number.isFinite(t)||!Number.isFinite(s)||s<=0)return null;const n=(t-s)/s;return Number.isFinite(n)?n:null}function Wd(t,s){const n=Hd(t,s);return n===null?null:Math.round(n*100)}function ia(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Gn(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Gn(t.prior)} ${s})`:`Flat ${n} (${Gn(t.prior)} ${s})`}const Mr=30;function mi(t){return Math.round(t*10)/10}function Yd(t){return t.prior>=Mr&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${mi(t.deltaAbs)} vs ${mi(t.prior)}`}function Xd(t,s,n){return t.prior>=Mr&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Gn(Math.round(t.deltaAbs))} ${s} ${n}`}const Jd=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Dr(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Er(t){return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function qr(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Dr).map(Er).filter(Boolean)):new Set}function Gr(t,s){const n=Dr(t).map(Er).filter(Boolean).filter(a=>!Jd.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Zd(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function eu(t,s){const n=qr(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const r of s){if(r.category!=="content"){i.push(r);continue}const l=Gr(Zd(r),n);!l||a.has(l)||(a.add(l),i.push(r))}return i}function tu(t){const s=qr(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const r=Gr(i.query,s);return!r||a.has(r)?!1:(a.add(r),!0)})}const Or={queryClass:"all"},su=["all","non-brand","branded"];function nu(t){return typeof t=="string"&&su.includes(t)}function au(t){const s=nu(t.class)?t.class:Or.queryClass,n=t.scope;if(typeof n!="string"||n==="all"||n.length===0)return{scope:"all",queryClass:s};const a=n.startsWith("group:")?n.slice(6):"";return a?{scope:"group",groupKey:a,queryClass:s}:{scope:"all",queryClass:s}}function iu(t,s){return s===null||t===null?!1:t!==s}function ru(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===Or.queryClass?void 0:t.queryClass}}function ka({state:t,label:s}){return e.jsx(de,{tone:Io(t),children:s??Po(t)})}function hi({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},i={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},r=n.length-1,l=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),m=new Date(n[r].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=n.map((h,x)=>{const d=new Date(h.createdAt).toLocaleDateString();return`${x===r?"Latest run, ":""}${d}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${c}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:l}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,x)=>{const d=!!(h.model&&x>0&&n[x-1]?.model&&n[x-1].model!==h.model),j=x===r;return e.jsx("span",{className:`h-2.5 w-2.5 ${i[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${d?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${j?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,d?"model changed":null,j?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[m," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function Aa(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const r=s.get(i.createdAt);r?r.states.push(i.citationState):s.set(i.createdAt,{states:[i.citationState],runId:i.runId})}return[...s.entries()].sort(([a],[i])=>a.localeCompare(i)).map(([a,{states:i,runId:r}])=>({runId:r,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const ou=320;function lu(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function xi(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 pi(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 gi(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const i=t[t.length-1].citationState,r=t[t.length-2].citationState;if(r!=="cited"&&i==="cited")return`Newly ${n}`;if(r==="cited"&&i!=="cited")return"Lost since last run";let l=0;for(let m=t.length-1;m>=0&&t[m].citationState===i;m--)l++;return i==="cited"?l<=1?`${a} in latest run`:`${a} for ${l} runs`:l<=1?`Not ${n} in latest run`:`Not ${n} across ${l} runs`}function cu(t,s){return t.map(n=>Fr(n,s))}function Fr(t,s){return s==="citations"?t:{...t,citationState:xi(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:xi(n,s)}))}}function fi(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 i=t[t.length-1].citationState,r=t.length>=2?t[t.length-2].citationState:null,l=i==="cited"||i==="emerging",m=r==="cited"||r==="emerging";return i==="lost"||r!==null&&m&&!l?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||r!==null&&!m&&l?{key:s,label:`New ${n}`,tone:"positive"}:r===null&&l?{key:s,label:`First ${n}`,tone:"positive"}:l?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function du(t){const s=Aa(cu(t,"mentions")),n=Aa(t);return[fi(s,"mentions"),fi(n,"citations")]}function uu({signal:t}){const s=t.tone==="positive"?"border-positive-500/25 bg-positive-500/10 text-positive":t.tone==="negative"?"border-negative-500/25 bg-negative-500/10 text-negative":t.tone==="pending"?"border-caution-500/20 bg-caution-500/10 text-caution":"border-mono-700/60 bg-bg-elevated/70 text-secondary";return e.jsx("span",{className:`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium leading-none ${s}`,children:t.label})}function bi({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:du(t).map(s=>e.jsx(uu,{signal:s},s.key))})}function mu({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=hr(),[i,r]=o.useState(new Set),[l,m]=o.useState("mentions"),[c,h]=o.useState(n),x=o.useMemo(()=>{const _=new Map;for(const B of t){const y=B.query,p=s?B.location??null:null,w=s?JSON.stringify([y,p]):y,C=_.get(w)??{key:w,phrase:y,location:p,items:[],rawItems:[]};C.items.push(Fr(B,l)),C.rawItems.push(B),_.set(w,C)}return[..._.values()]},[t,l,s]),d=Bn({rows:x,getSearchText:lu}),j=d.rows.map(_=>_.key),S=j.length>0&&j.every(_=>i.has(_)),b=_=>{r(B=>{const y=new Set(B);return y.has(_)?y.delete(_):y.add(_),y})},v=l==="mentions"?"mentioned":"cited",g=l==="mentions"?"Mention History":"Citation History",R=l==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":l==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":l==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:l==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{r(_=>{const B=new Set(_);for(const y of j)S?B.delete(y):B.add(y);return B})},children:S?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),x.length>0?e.jsx(on,{value:d.query,onChange:d.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"mb-3 max-w-md"}):null,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",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:g}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:d.rows.map(({key:_,phrase:B,location:y,items:p,rawItems:w})=>{const C=i.has(_),Y=p.map(T=>T.citationState),K=Y.includes("cited")?"cited":Y.includes("emerging")?"emerging":Y.includes("lost")?"lost":Y.every(T=>T==="pending")?"pending":"not-cited",I=Aa(p),L=p.filter(T=>T.citationState===Ro.cited||T.citationState==="emerging").length,U=gi(I,l);return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>b(_),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),b(_))},tabIndex:0,role:"button","aria-expanded":C,children:[e.jsx("td",{children:e.jsx(Ad,{size:14,className:`transition-transform duration-150 text-muted ${C?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:B}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:y??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:p.map(T=>e.jsx(zs,{provider:T.provider},T.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ka,{state:K,label:pi(K,l)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${L} of ${p.length} engines ${R}`,children:[L,"/",p.length]})]})}),e.jsx("td",{children:e.jsx(hi,{history:I})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:U}),e.jsx(bi,{items:w})]}),e.jsx("td",{})]}),C&&p.map((T,H)=>e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(zs,{provider:T.provider})}),e.jsx("td",{children:e.jsx(ka,{state:T.citationState,label:pi(T.citationState,l)})}),e.jsx("td",{children:e.jsx(hi,{history:T.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:gi(T.runHistory,l)}),e.jsx(bi,{items:[w[H]??T]})]}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",size:"sm",type:"button",onClick:fe=>{fe.stopPropagation(),a(T.id)},children:"View"})})]}),c==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(pu,{item:T,onViewFull:()=>a(T.id)})})]})]},T.id))]},_)})})]})}),d.totalRows===0&&d.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(_s,{page:d.page,pageSize:d.pageSize,visibleRows:d.rows.length,totalRows:d.totalRows,onPageChange:d.setPage,itemLabel:d.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",v==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function hu(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(i=>{const r=To(i);return r.length>=4?[r]:[]}),...t.recommendedCompetitors??[]].filter(i=>i.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function vi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function xu(t,s){if(t.length<=s)return{body:t,truncated:!1};const n=t.lastIndexOf(" ",s);return{body:`${t.slice(0,n>s-40?n:s).trimEnd()}…`,truncated:!0}}function pu({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:i}=xu(t.answerSnippet,ou),r=hu(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-neutral",children:$o(a,r)}),(t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(l=>e.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[11px] ${vi(t,l)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[l,vi(t,l)?" · competitor source":""]},`c-${l}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors in answer:"}),t.mentionedCompetitorDomains.slice(0,4).map(l=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:l},`co-${l}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),i&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:l=>{l.stopPropagation(),s()},children:"View full answer →"})]})}function gu({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const i=s!=null,r=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),r&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>{const m=a!=null&&a.toLowerCase()===l.domain.toLowerCase(),c=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",m?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:c,onClick:i?()=>s(l.domain):void 0,title:i?`Filter answers to queries where ${l.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:l.domain}),e.jsx("td",{children:e.jsx(de,{tone:Lo(l.pressureLabel),children:l.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:l.totalQueries>0?`${l.citationCount} / ${l.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:l.citedQueries.length>0?l.citedQueries.join(", "):"Not cited"}),r&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"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","aria-label":`Remove competitor ${l.domain}`,title:`Remove ${l.domain}`,onClick:h=>{h.stopPropagation(),n(l.domain)},children:"Remove"})})]},l.id)})})]})})}function Sn({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})]})}const fu=6,Qs="__other__",Us="_socialTotal";function bu(t,s=fu){const n=new Map;for(const x of t)n.set(x.source,(n.get(x.source)??0)+x.sessions);const a=[...n.entries()].sort((x,d)=>d[1]!==x[1]?d[1]-x[1]:x[0].localeCompare(d[0])),i=a.slice(0,s),r=new Set(i.map(([x])=>x)),l=Math.max(0,a.length-s),m=new Map;for(const x of t){let d=m.get(x.date);d||(d={date:x.date,[Us]:0},m.set(x.date,d));const j=r.has(x.source)?x.source:Qs;d[j]=(d[j]??0)+x.sessions,d[Us]=(d[Us]??0)+x.sessions}const c=[...m.values()].sort((x,d)=>String(x.date).localeCompare(String(d.date))),h=i.map(([x])=>x);return l>0&&h.push(Qs),{data:c,sources:h,otherCount:l}}function Vs(t){return t.replace(/\+/g," ")}function _r(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const yi="_totalSessions",ji="_organicSessions";function vu(t,s){const n=new Map;for(const l of s)n.set(l.date,{[yi]:l.sessions,[ji]:l.organicSessions});for(const l of t.days){let m=n.get(l.date);m||(m={[yi]:0,[ji]:0},n.set(l.date,m));for(const c of l.bySource)m[c.source]=(m[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([l],[m])=>l.localeCompare(m)).map(([l,m])=>({date:l,...m})),i=a.map(l=>l.date),r=i.length>0?{start:i[0],end:i[i.length-1]}:null;return{data:a,sources:t.sources,dateRange:r}}const yu=["7d","30d","90d","all"],xs=yt,Pa=Bt.textDim,Br=Bt.textFaint,Js=25;function ju(t){return Cd(t.landingPage)}const Nu=25,ra={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Cn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Ur(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 wu({projectName:t}){const{data:s,isLoading:n,isError:a}=Gd(t);if(n)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const i=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."," ",!ne()&&e.jsx(Xt,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),i.length===0?e.jsx(pe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ne()&&e.jsxs(e.Fragment,{children:[e.jsx(Xt,{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(pe,{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:i.map(r=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:r.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(de,{tone:Od(r.status),children:r.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:r.lastSyncedAt?Ur(r.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ne()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Xt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:r.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},r.id))})]})})]})}function Su({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(wu,{projectName:t}),e.jsx(Cu,{projectName:t})]})}function Cu({projectName:t}){const s=bs(),[n,a]=o.useState(null),[i,r]=o.useState(null),[l,m]=o.useState(!0),[c,h]=o.useState(!1),[x,d]=o.useState(!1),[j,S]=o.useState(null),[b,v]=o.useState(null),[g,R]=o.useState("sessions"),[_,B]=o.useState("desc"),[y,p]=o.useState("sessions"),[w,C]=o.useState("desc"),[Y,K]=o.useState("sessions"),[I,L]=o.useState("desc"),[U,T]=o.useState("sessions"),[H,fe]=o.useState("desc"),[xe,Q]=o.useState(ra),[ie,oe]=o.useState([]),[z,q]=o.useState([]),[N,se]=o.useState(!1),[ue,re]=o.useState("30d");async function le(F){m(!0),S(null);try{const je=await s.fetchQuery({...Mo({client:V,path:{name:t}}),staleTime:Xs});if(F.current)return;if(a(je),!je.connected){r(null),Q(ra),oe([]),q([]),m(!1);return}const me=ue==="all"?void 0:ue,[ve,jt,Lt,it]=await Promise.all([s.fetchQuery({...Do({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Xs}).then(Ct=>Ct),s.fetchQuery({...Eo({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Xs}).catch(()=>ra),s.fetchQuery({...qo({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Xs}).catch(()=>[]),s.fetchQuery({...Go({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Xs}).catch(()=>[])]);if(F.current)return;r(ve),Q(jt),oe(Lt),q(it),m(!1)}catch(je){if(F.current)return;S(je instanceof Error?je.message:"Failed to load GA4 data"),m(!1)}}o.useEffect(()=>{const F={current:!1};return le(F),()=>{F.current=!0}},[t,ue,s]);async function X(){h(!0),S(null),v(null);try{const F=await xr(t);v(`Synced ${F.rowCount.toLocaleString()} page rows, ${F.aiReferralCount.toLocaleString()} AI and ${F.socialReferralCount.toLocaleString()} social referral rows (${F.days} days)`),await ht(s,"ga"),await le({current:!1})}catch(F){S(F instanceof Error?F.message:"Sync failed")}finally{h(!1)}}async function D(){d(!0),S(null),v(null);try{await Oo(t),await ht(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),r(null),v("GA4 disconnected")}catch(F){S(F instanceof Error?F.message:"Disconnect failed")}finally{d(!1)}}function Z(F){g===F?B(je=>je==="desc"?"asc":"desc"):(R(F),B("desc"))}function he(F){y===F?C(je=>je==="desc"?"asc":"desc"):(p(F),C("desc"))}function $e(F){Y===F?L(je=>je==="desc"?"asc":"desc"):(K(F),L("desc"))}const st=o.useMemo(()=>i?.topPages?[...i.topPages].sort((F,je)=>{const me=F[g],ve=je[g];return typeof me=="string"&&typeof ve=="string"?_==="asc"?me.localeCompare(ve):ve.localeCompare(me):_==="asc"?me-ve:ve-me}):[],[i?.topPages,g,_]),lt=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((F,je)=>{const me=F[y],ve=je[y];return typeof me=="string"&&typeof ve=="string"?w==="asc"?me.localeCompare(ve):ve.localeCompare(me):w==="asc"?me-ve:ve-me}):[],[i?.aiReferrals,y,w]),Fe=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((F,je)=>{const me=F[U],ve=je[U];return typeof me=="string"&&typeof ve=="string"?H==="asc"?me.localeCompare(ve):ve.localeCompare(me):H==="asc"?me-ve:ve-me}):[],[i?.aiReferralLandingPages,U,H]),ee=Bn({rows:Fe,getSearchText:ju,pageSize:Nu}),Be=ee.totalRows>0?`${ee.totalRows.toLocaleString()} ${ee.hasQuery?ee.totalRows===1?"match":"matches":ee.totalRows===1?"row":"rows"}`:ee.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Ve(F){ee.setPage(1),U===F?fe(je=>je==="desc"?"asc":"desc"):(T(F),fe("desc"))}const ke=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((F,je)=>{const me=F[Y],ve=je[Y];return typeof me=="string"&&typeof ve=="string"?I==="asc"?me.localeCompare(ve):ve.localeCompare(me):I==="asc"?me-ve:ve-me}):[],[i?.socialReferrals,Y,I]),{socialChartData:Je,socialChartSources:Ae,socialOtherCount:we}=o.useMemo(()=>{const F=bu(z);return{socialChartData:F.data,socialChartSources:F.sources,socialOtherCount:F.otherCount}},[z]),{chartData:O,chartSources:$,dateRange:M}=o.useMemo(()=>{const F=vu(xe,ie);return{chartData:F.data,chartSources:F.sources,dateRange:F.dateRange}},[xe,ie]);if(l&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return ne()?e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(ku,{projectName:t,onConnected:()=>{(async()=>(await ht(s,"ga"),await le({current:!1})))()}});const ye=i?.organicSharePctDisplay??"0%",De=i?.channelBreakdown?.organic.sharePctDisplay??ye,te=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,Ge=i?.aiSessionsDeduped??0,He=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,Ze=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Pe=i?.paidAiSessionsBySession??0,Oe=i?.paidAiSharePctBySessionDisplay??"0%",dt=i?new Set(i.aiReferrals.map(F=>F.source.toLowerCase())).size:0,ze=lt[0]??null,et=i?.totalDirectSessions??0,Ie=i?.directSharePctDisplay??"0%",wt=i?.channelBreakdown?.direct.sessions??et,xt=i?.channelBreakdown?.direct.sharePctDisplay??Ie,Le=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Me=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",ct=i?.socialSessions??0,_e=i?.socialSharePctDisplay??"0%",Gt=i?.channelBreakdown?.social.sessions??ct,St=i?.channelBreakdown?.social.sharePctDisplay??_e,pt=i?new Set(i.socialReferrals.map(F=>F.source.toLowerCase())).size:0,at=ke[0]??null;return e.jsxs(e.Fragment,{children:[j&&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:j}),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:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:n.clientEmail})]})]})]}),!ne()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:c,onClick:Te(X),children:[e.jsx(Un,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),c?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Te(D),children:[e.jsx(Pd,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsxs("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(Ke,{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.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:yu.map(F=>e.jsx("button",{type:"button","aria-pressed":ue===F,className:`segmented-option ${ue===F?"segmented-option-active":""}`,onClick:()=>re(F),children:F==="all"?"All":F},F))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(oa,{value:Cn(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(oa,{value:Cn(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${ye} of total`,tone:"positive"}),e.jsx(oa,{value:i.totalUsers===null?"—":Cn(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."}),!ne()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:c,onClick:Te(X),children:[e.jsx(Un,{className:`w-3.5 h-3.5 mr-1.5 ${c?"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(Ke,{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."})]})]}),M&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(M.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(M.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),O.length>0&&e.jsxs(pe,{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:$.length>0?"AI vs. total sessions":"All sessions (baseline)"}),$.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),$.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(dn,{width:"100%",height:"100%",children:e.jsxs(un,{data:O,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(mn,{dataKey:"date",tick:Yt,tickLine:!1,axisLine:{stroke:Ls},tickFormatter:Kn}),e.jsx(hn,{tick:Yt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(xn,{...Bs,labelFormatter:Is,formatter:(F,je)=>{const me=typeof F=="number"?F.toLocaleString():String(F??0),ve=String(je??"");return ve==="_totalSessions"?[me,"Total Sessions"]:ve==="_organicSessions"?[me,"Organic Sessions"]:[me,ve]}}),e.jsx($r,{wrapperStyle:{fontSize:11,color:Bt.text},formatter:F=>F==="_totalSessions"?"Total Sessions":F==="_organicSessions"?"Organic Sessions":F}),e.jsx(Os,{type:"monotone",dataKey:"_totalSessions",stroke:Bt.textFaint,fill:Bt.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),$.map((F,je)=>e.jsx(Os,{type:"monotone",dataKey:F,stackId:"ai",stroke:xs[je%xs.length],fill:xs[je%xs.length],fillOpacity:.4,strokeWidth:1.5},F))]})})})]}),e.jsxs(pe,{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:"Channel breakdown"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Vt,{label:"Organic",value:De,hint:`${te.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(Vt,{label:"Social",value:St,hint:`${Gt.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(Vt,{label:"Direct",value:xt,hint:`${wt.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(Vt,{label:"Known AI referrers (lower bound)",value:Ze,hint:Pe>0?`${He.toLocaleString()} sessions · ${Pe.toLocaleString()} paid`:`${He.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(Vt,{label:"Other channels",value:Me,hint:`${Le.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."})]}),ze&&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:ze.source})," via ",ze.medium,", accounting for ",ze.sessions.toLocaleString()," sessions.",Pe>0&&e.jsxs("span",{children:[" Paid AI: ",Pe.toLocaleString()," sessions (",Oe,")."]})]})]}),e.jsxs(pe,{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:"Known AI referrers by source"})]}),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(Dt,{label:"Source",sortKey:"source",current:y,dir:w,onSort:he,align:"left"}),e.jsx(Dt,{label:"Medium",sortKey:"medium",current:y,dir:w,onSort:he,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(Dt,{label:"Sessions",sortKey:"sessions",current:y,dir:w,onSort:he,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:lt.map(F=>e.jsx(Pu,{referral:F,totalSessions:Ge},`${F.source}:${F.medium}:${F.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(pe,{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:"Known AI referrers by landing page"})]}),e.jsx("p",{className:"text-xs text-muted",children:Be})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(on,{value:ee.query,onChange:ee.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),ee.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(Dt,{label:"Landing Page",sortKey:"landingPage",current:U,dir:H,onSort:Ve,align:"left"}),e.jsx(Dt,{label:"Source",sortKey:"source",current:U,dir:H,onSort:Ve,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Dt,{label:"Sessions",sortKey:"sessions",current:U,dir:H,onSort:Ve,align:"right"})]})}),e.jsx("tbody",{children:ee.rows.map(F=>e.jsx(Iu,{row:F},`${F.landingPage}:${F.source}:${F.medium}:${F.sourceDimension}`))})]})}),e.jsx(_s,{page:ee.page,pageSize:ee.pageSize,visibleRows:ee.rows.length,totalRows:ee.totalRows,onPageChange:ee.setPage,itemLabel:ee.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:()=>ee.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 landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),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(Ke,{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."})]})]}),Je.length>0&&e.jsxs(pe,{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:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions over time"})]}),we>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ae.length-1," sources · ",we," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(dn,{width:"100%",height:"100%",children:e.jsxs(un,{data:Je,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(mn,{dataKey:"date",tick:Yt,tickLine:!1,axisLine:{stroke:Ls},tickFormatter:Kn}),e.jsx(hn,{tick:Yt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(xn,{...Bs,labelFormatter:Is,formatter:(F,je)=>{const me=typeof F=="number"?F.toLocaleString():String(F??0),ve=String(je??"");if(ve===Us)return[me,"Total Social"];if(ve===Qs){const jt=`Other (${we} source${we===1?"":"s"})`;return[me,jt]}return[me,Vs(ve)]}}),e.jsx(Os,{type:"monotone",dataKey:Us,stroke:Br,fill:Bt.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ae.map((F,je)=>{const ve=F===Qs?Pa:xs[je%xs.length];return e.jsx(Os,{type:"monotone",dataKey:F,stackId:"social",stroke:ve,fill:ve,fillOpacity:.4,strokeWidth:1.5},F)})]})})}),e.jsx($u,{sources:Ae,otherCount:we})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(pe,{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:"Social media visits"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Vt,{label:"Social Sessions",value:Cn(ct),hint:`${ct.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Vt,{label:"Share of Traffic",value:_e,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Vt,{label:"Platforms",value:String(pt),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."})]}),at&&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:`${at.source} via ${at.medium}`,children:_r(Vs(at.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:at.medium,children:["via ",Vs(at.medium)," · ",at.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(Vt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Vt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Vt,{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.jsxs(pe,{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:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?ke.length>Js&&!N?`Top ${Js} of ${ke.length}`:`${ke.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(Dt,{label:"Source",sortKey:"source",current:Y,dir:I,onSort:$e,align:"left"}),e.jsx(Dt,{label:"Medium",sortKey:"medium",current:Y,dir:I,onSort:$e,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Dt,{label:"Sessions",sortKey:"sessions",current:Y,dir:I,onSort:$e,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Dt,{label:"Users",sortKey:"users",current:Y,dir:I,onSort:$e,align:"right"})]})}),e.jsx("tbody",{children:(N?ke:ke.slice(0,Js)).map(F=>e.jsx(Ru,{referral:F,totalSessions:ct},`${F.source}:${F.medium}:${F.channelGroup}`))})]})}),ke.length>Js&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>se(F=>!F),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:N?`Show top ${Js}`:`Show all ${ke.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(Ke,{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("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(Dt,{label:"Landing Page",sortKey:"landingPage",current:g,dir:_,onSort:Z,align:"left"}),e.jsx(Dt,{label:"Sessions",sortKey:"sessions",current:g,dir:_,onSort:Z,align:"right"}),e.jsx(Dt,{label:"Organic",sortKey:"organicSessions",current:g,dir:_,onSort:Z,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:st.map(F=>e.jsx(Au,{page:F},F.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${Ur(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function ku({projectName:t,onConnected:s}){const[n,a]=o.useState(""),[i,r]=o.useState(null),[l,m]=o.useState(null),[c,h]=o.useState(!1),[x,d]=o.useState(null),j=o.useRef(null),S=o.useCallback(v=>{const g=v.target.files?.[0];if(!g)return;d(null),r(g.name);const R=new FileReader;R.onload=()=>{const _=R.result;try{const B=JSON.parse(_);if(!B.client_email||!B.private_key){d("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),m(null);return}m(_)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),m(null)}},R.onerror=()=>{d("Failed to read file."),m(null)},R.readAsText(g)},[]);async function b(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!l){d("Please upload a service account key file.");return}h(!0);try{await Fo(t,{propertyId:n.trim(),keyJson:l});try{await xr(t)}catch{}s()}catch(v){d(v instanceof Error?v.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(pe,{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."}),x&&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:x}),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:v=>a(v.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:j,type:"file",accept:".json,application/json",onChange:S,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>j.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(Id,{className:"w-4 h-4 shrink-0"}),i?e.jsx("span",{className:"text-strong truncate",children:i}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(A,{variant:"default",size:"sm",disabled:c||!n.trim()||!l,onClick:Te(b),children:c?"Connecting & syncing…":"Connect GA4"})]})}function Dt({label:t,sortKey:s,current:n,dir:a,onSort:i,align:r}){const l=n===s;return e.jsx("th",{className:`py-1 ${r==="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:()=>i(s),"aria-label":`Sort by ${t}${l?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,l&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Vr={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function oa({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 ${Vr[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Vt({value:t,label:s,hint:n,tone:a,tooltip:i}){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,i&&e.jsx(Ke,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Vr[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Au({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";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.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[s,"%"]})]})}const zr={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Kr={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 Pu({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=zr[t.sourceDimension]??t.sourceDimension,i=Kr[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:i,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function Iu({row:t}){const s=zr[t.sourceDimension]??t.sourceDimension,n=Kr[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(qn,{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 Ru({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",i=Vs(t.source),r=Vs(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:i}),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:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function $u({sources:t,otherCount:s}){const n=[{key:Us,color:Br,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===Qs)n.push({key:Qs,color:Pa,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const r=Vs(i);n.push({key:i,color:xs[a%xs.length]??Pa,label:_r(r,32),tooltip:r})}}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 Tu(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 Lu=["7d","30d","90d","all"],kn=500,Ni=[{key:"clicks",label:"Clicks",color:yt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:yt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Rs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:yt[2],inverted:!0,format:t=>t.toFixed(1)}],ms=25,Mu="canonry:google-oauth-complete",Du=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function Eu(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const i=t.change[s];if(i===null||!Number.isFinite(i)){const c=t.prior[s],h=t.trailing[s];return c!==null&&h!==null&&c<=0&&h>0?`new in the last ${a}d`:c===null||c<=0?`no prior ${a}d to compare`:h===null?`no value in the last ${a}d`:"comparison unavailable"}if(i===0)return`→ no change vs prior ${a}d`;const r=Math.abs(i*100),l=r<.1?"<0.1%":`${Du.format(r)}%`;return`${(n?i<0:i>0)?"↑":"↓"} ${l} vs prior ${a}d`}function wi(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Si(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 Ci(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function qu({projectName:t,refreshNonce:s}){const n=bs(),[a,i]=o.useState(!1),[r,l]=o.useState([]),[m,c]=o.useState([]),[h,x]=o.useState([]),[d,j]=o.useState(null),[S,b]=o.useState([]),[v,g]=o.useState([]),[R,_]=o.useState(null),[B,y]=o.useState(""),[p,w]=o.useState(""),[C,Y]=o.useState("30"),[K,I]=o.useState(!1),[L,U]=o.useState("30d"),[T,H]=o.useState(["clicks","impressions"]),[fe,xe]=o.useState(!0),[Q,ie]=o.useState(null),[oe,z]=o.useState(0),[q,N]=o.useState({startDate:"",endDate:"",query:"",page:""}),[se,ue]=o.useState(0),[re,le]=o.useState(!1),[X,D]=o.useState(0),[Z,he]=o.useState(!1),[$e,st]=o.useState(""),[lt,Fe]=o.useState(!0),[ee,Be]=o.useState(!1),[Ve,ke]=o.useState(!1),[Je,Ae]=o.useState(!1),[we,O]=o.useState(!1),[$,M]=o.useState(!1),[ye,De]=o.useState(!1),[te,Ge]=o.useState(null),[He,Ze]=o.useState(!1),[Pe,Oe]=o.useState(!1),[dt,ze]=o.useState(null),[et,Ie]=o.useState(null),[wt,xt]=o.useState([]),[Le,Me]=o.useState(new Set),[ct,_e]=o.useState({}),[Gt,St]=o.useState(new Set),[pt,at]=o.useState(""),[F,je]=o.useState(null),[me,ve]=o.useState(""),[jt,Lt]=o.useState(!1),[it,Ct]=o.useState(!1),[zt,Kt]=o.useState(!1),[kt,Qt]=o.useState(!1),[Xe,vs]=o.useState("indexed"),[Nt,ys]=o.useState(null),Ht=!!(q.query.trim()||q.page.trim()||Nt),rs=Nt!==null,Jt=o.useMemo(()=>{if(!Nt)return h;const{key:u,dir:E}=Nt;return[...h].sort((ae,ce)=>{const qe=u===As.CTR?Number.isFinite(ae.ctr)?ae.ctr:0:ae[u],Ue=u===As.CTR?Number.isFinite(ce.ctr)?ce.ctr:0:ce[u];return E==="asc"?qe-Ue:Ue-qe})},[h,Nt]),tt=Bn({rows:Jt,pageSize:ss}),os=Z?tt.rows:Jt,At=Bn({rows:(dt??[]).filter(u=>u.path.toLowerCase().includes(pt.trim().toLowerCase())),pageSize:ss}),[gt,Zt]=o.useState([]),[rt,Ut]=o.useState(null),[k,be]=o.useState(1),Ne=o.useMemo(()=>{if(gt.length<2)return null;const u=gt[gt.length-1],E=gt[gt.length-2];return{indexed:u.indexed-E.indexed,notIndexed:u.notIndexed-E.notIndexed}},[gt]);o.useEffect(()=>{be(1)},[te,Xe,rt]);const P=o.useMemo(()=>rt?(te?.reasonGroups??[]).find(u=>u.reason===rt):void 0,[te,rt]),W=o.useMemo(()=>te?Xe==="indexed"?te.indexed:Xe==="deindexed"?te.deindexed:Xe==="notIndexed"?rt?P?.urls??[]:(te.reasonGroups??[]).length===0?te.notIndexed:[]:[]:[],[te,Xe,rt,P]),f=Math.max(1,Math.ceil(W.length/ms)),G=Math.min(Math.max(1,k),f),J=(G-1)*ms,Se=o.useMemo(()=>te?.indexed.slice(J,J+ms)??[],[te,J]),ft=o.useMemo(()=>te?.notIndexed.slice(J,J+ms)??[],[te,J]),ot=o.useMemo(()=>te?.deindexed.slice(J,J+ms)??[],[te,J]),Pt=o.useMemo(()=>(P?.urls??[]).slice(J,J+ms),[P,J]),[$t,ls]=o.useState(!1),[Ha,Ee]=o.useState(null),[es,yn]=o.useState(null),[Wa,ts]=o.useState(null);function xo(u,E){const ae=Fd(u),ce=Tu(ae);ce?(yn(ce),Ee(null)):(yn(null),Ee(ae.message||E))}const Mt=r.find(u=>u.connectionType==="gsc"),js=(Mt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),Yn=wt.length>0?wt:(dt??[]).map(u=>u.path),Ya=Yn.filter(u=>dt?.some(E=>E.path===u&&E.isSitemapsIndex)).length,po=Ya===1?"Resubmit sitemap index":Ya>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",go=h.length>0||S.length>0||v.length>0,Xn=_o(),Jn=Bo();async function Xa(u,E=!1){if(!u){c([]),y("");return}ke(!0);try{const{sites:ae}=await n.fetchQuery({...tl({client:V,path:{name:t}}),staleTime:E?0:vt});c(ae),y(u.propertyId??ae[0]?.siteUrl??""),yn(null)}catch(ae){c([]),xo(ae,"Failed to load Search Console properties")}finally{ke(!1)}}async function Ws(u){O(!0);const E=u??se;try{const ae=Ht?kn:ss,ce=Ht?0:E,qe={limit:String(ae)};q.startDate&&(qe.startDate=q.startDate),q.endDate&&(qe.endDate=q.endDate),q.query&&(qe.query=q.query),q.page&&(qe.page=q.page),ce>0&&(qe.offset=String(ce)),L&&L!=="all"&&!q.startDate&&(qe.window=L);const Ue=await n.fetchQuery({...zo({client:V,path:{name:t},query:qe}),staleTime:vt}),We=Ue.rows;Ht?(le(!1),x(We),D(We.length),he(!0)):(le(ce+We.length<Ue.totalMatching),x(We),D(0),he(!1))}catch(ae){x([]),le(!1),D(0),Ee(ae instanceof Error?ae.message:"Failed to load GSC performance data")}finally{O(!1)}}async function Zn(){try{const u={};q.startDate&&(u.startDate=q.startDate),q.endDate&&(u.endDate=q.endDate),L&&L!=="all"&&!q.startDate&&(u.window=L);const E=await n.fetchQuery({...Vo({client:V,path:{name:t},query:u}),staleTime:vt});j(E)}catch{j(null)}}async function jn(u=!1){M(!0);try{const E=$e.trim()||void 0,ae={limit:"20"};E&&(ae.url=E);const[ce,qe]=await Promise.all([n.fetchQuery({...Zo({client:V,path:{name:t},query:ae}),staleTime:u?0:vt}),n.fetchQuery({...el({client:V,path:{name:t}}),staleTime:u?0:vt})]);b(ce),g(qe)}catch(E){b([]),g([]),Ee(E instanceof Error?E.message:"Failed to load GSC inspection history")}finally{M(!1)}}async function Ja(u=!1){Ze(!0);try{const[E,ae]=await Promise.all([n.fetchQuery({...gr({client:V,path:{name:t}}),staleTime:u?0:vt}),n.fetchQuery({...Ho({client:V,path:{name:t}}),staleTime:u?0:vt}).catch(()=>[])]);Ge(E),Zt(ae)}catch(E){Ge(null),Zt([]),Ee(E instanceof Error?E.message:"Failed to load coverage data")}finally{Ze(!1)}}async function Za(u){ls(!0),Ee(null);try{const E=await li(t,{urls:u}),{succeeded:ae,failed:ce,total:qe}=E.summary;Ce({title:"Indexing requested",detail:ce===0?`${ae} URL${ae!==1?"s":""} submitted for indexing.`:`${ae}/${qe} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(E){Ee(E instanceof Error?E.message:"Failed to request indexing")}finally{ls(!1)}}async function fo(){ls(!0),Ee(null);try{const u=await li(t,{urls:[],allUnindexed:!0}),{succeeded:E,failed:ae,total:ce}=u.summary;Ce({title:"Indexing requested",detail:ae===0?`${E} unindexed URL${E!==1?"s":""} submitted for indexing.`:`${E}/${ce} submitted successfully, ${ae} failed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(u){Ee(u instanceof Error?u.message:"Failed to request indexing")}finally{ls(!1)}}async function ea(){Oe(!0),Ee(null);try{const u=await sa(t);n.setQueryData(Wo({client:V,path:{name:t}}),u),ze(u.sitemaps),Ie(u.summary),xt(u.preferredSubmissionUrls),Me(new Set),_e({}),u.sitemaps.length===0&&ts("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(u){Ee(u instanceof Error?u.message:"Failed to list sitemaps")}finally{Oe(!1)}}async function bo(u){const E=Le.has(u);if(Me(ae=>{const ce=new Set(ae);return E?ce.delete(u):ce.add(u),ce}),!(E||ct[u])){St(ae=>new Set(ae).add(u));try{const ae=await sa(t,u);_e(ce=>({...ce,[u]:ae.sitemaps}))}catch(ae){Ee(ae instanceof Error?ae.message:"Failed to load sitemap files")}finally{St(ae=>{const ce=new Set(ae);return ce.delete(u),ce})}}}async function Ms(u){if(!js||u.length===0)return;const E=[...new Set(u)];Ct(!0),Ee(null),je({completed:0,total:E.length});let ae=0,ce=0,qe=0,Ue=null;try{for(let bt=0;bt<E.length;bt+=50){const Ye=E.slice(bt,bt+50);try{const ge=await Yo(t,Ye);ae+=ge.summary.accepted,ce+=ge.summary.failed,qe+=Ye.length,je({completed:qe,total:E.length})}catch(ge){qe+=Ye.length;const cs=Ye.length,Ys=E.length-qe,Nn=ge instanceof Error?ge.message:"The batch request failed",ds=`${ae} accepted, ${ce} failed, ${cs} unconfirmed, ${Ys} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Ue=`Sitemap submission stopped after a batch request failed. ${ds} ${Nn}`,Ee(Ue),Ce({title:"Sitemap resubmission partially completed",detail:ds,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const We=E.length;Ce({title:ce===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ce===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ae}/${We} sitemap submissions; ${ce} failed. Indexing is not guaranteed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),ve("")}catch(We){Ee(We instanceof Error?We.message:"Failed to submit sitemap to Google")}finally{Ct(!1),je(null),await ea(),Ue&&Ee(Ue)}}async function vo(){Ct(!0);const u=dt??[];try{const E=u.filter(ce=>ce.isSitemapsIndex),ae=[];for(let ce=0;ce<E.length;ce+=4)(await Promise.all(E.slice(ce,ce+4).map(async Ue=>{const We=ct[Ue.path];if(We)return We;const bt=await sa(t,Ue.path);return _e(Ye=>({...Ye,[Ue.path]:bt.sitemaps})),bt.sitemaps}))).forEach((Ue,We)=>{ae.push(...Ue.length>0?Ue.map(bt=>bt.path):[E[ce+We].path])});await Ms([...u.filter(ce=>!ce.isSitemapsIndex).map(ce=>ce.path),...ae])}catch(E){Ee(E instanceof Error?E.message:"Failed to load sitemap files"),Ct(!1)}}async function ei(u){Lt(!0),Ee(null);try{await Xo(t,"gsc",u),await ht(n,"google"),l(E=>E.map(ae=>ae.connectionType==="gsc"?{...ae,sitemapUrl:u}:ae)),Ce({title:"Default sitemap updated",detail:u,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(E){Ee(E instanceof Error?E.message:"Failed to set the default sitemap")}finally{Lt(!1)}}async function ti(u){try{await Jn.mutateAsync({projectName:t,projectLabel:t,opts:u?{sitemapUrl:u}:void 0})}catch{}}async function si(){Fe(!0),Ee(null);try{const[u,E]=await Promise.all([pr().catch(()=>null),n.fetchQuery({...Ea({client:V,path:{name:t}}),staleTime:vt}).catch(()=>[])]);i(!!u?.google?.configured),l(E);const ae=E.find(ce=>ce.connectionType==="gsc");await Promise.all([Xa(ae),Ws(),Zn(),jn(),Ja(),ae?.propertyId?ea():Promise.resolve()])}finally{Fe(!1)}}o.useEffect(()=>{si()},[t,s]),o.useEffect(()=>{ue(0),ie(null),N(u=>u.startDate||u.endDate?{...u,startDate:"",endDate:""}:u),z(u=>u+1),Zn()},[L]);const ni=o.useRef(!1);o.useEffect(()=>{if(!ni.current){ni.current=!0;return}ue(0),tt.setPage(1),Ws(0)},[oe]);function ta(u){const E=Q===u?null:u;ie(E),N(ae=>({...ae,startDate:E??"",endDate:E??""})),z(ae=>ae+1)}const ai=o.useRef(!1);o.useEffect(()=>{if(!ai.current){ai.current=!0;return}ue(0),Ws(0)},[rs]);async function ii(){if(!a){Ee("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Be(!0),Ee(null),ts(null);try{let u=function(ge){if(ge.source!==ce||ge.origin!==qe||!ge.data||typeof ge.data!="object")return;const cs=ge.data;cs.type!==Mu||cs.connectionType!=="gsc"||Ye(!0)};const{authUrl:E,redirectUri:ae}=await Qo(t,"gsc");if(!E.startsWith("https://accounts.google.com/")){Ee("Unexpected OAuth redirect URL. Please try again.");return}const ce=window.open(E,"_blank","width=600,height=700");if(!ce){window.location.assign(E);return}const qe=ae?new URL(ae).origin:window.location.origin;let Ue=!1,We=null;const bt=()=>{We!==null&&window.clearInterval(We),window.removeEventListener("message",u)},Ye=async ge=>{if(!Ue){Ue=!0,bt(),ts(ge?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await ht(n,"google"),await si()}finally{ts(null)}}};window.addEventListener("message",u),ts("Finish the Google consent flow in the popup. This page will refresh automatically."),We=window.setInterval(()=>{ce.closed&&Ye(!1)},1e3)}catch(u){Ee(u instanceof Error?u.message:"Failed to start OAuth flow")}finally{Be(!1)}}async function yo(){Ee(null),ts(null);try{await Ko(t,"gsc"),await ht(n,"google"),l(u=>u.filter(E=>E.connectionType!=="gsc")),c([]),y("")}catch(u){Ee(u instanceof Error?u.message:"Failed to disconnect")}}async function jo(){if(B){Ae(!0),Ee(null);try{await sl(t,"gsc",B),await ht(n,"google"),l(u=>u.map(E=>E.connectionType==="gsc"?{...E,propertyId:B}:E)),Ce({title:"GSC property updated",detail:`${t} is now linked to ${B}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(u){Ee(u instanceof Error?u.message:"Failed to save GSC property")}finally{Ae(!1)}}}async function No(){Ee(null),ts(null);try{await Xn.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(C,10)||void 0,full:K||void 0}}),await ht(n,"gsc")}catch{}}async function ri(){if(p.trim()){De(!0),Ee(null),ts(null);try{const u=await Jo(t,p.trim());await ht(n,"gsc"),_(u),w(""),await jn()}catch(u){Ee(u instanceof Error?u.message:"Failed to inspect URL")}finally{De(!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"})]})}),es&&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:es.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:es.message}),(Cs(es.enableUrl)||Cs(es.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Cs(es.enableUrl)&&e.jsx("a",{href:Cs(es.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 ↗"}),Cs(es.indexingApiUrl)&&e.jsx("a",{href:Cs(es.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:()=>yn(null),children:"×"})]})}),Ha&&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:[Ha,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Ee(null),children:"×"})]}),Wa&&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:[Wa,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>ts(null),children:"×"})]}),lt?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Mt?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:Mt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",te?.lastInspectedAt?Tt(te.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Te(yo),children:"Disconnect"})]}):e.jsxs(pe,{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(de,{tone:a?"caution":"negative",children:a?"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:a?"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:[a?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ee,onClick:Te(ii),children:ee?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Xt,{to:"/settings",children:"Open Settings"})}),!a&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),(Mt||go)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(pe,{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(Ke,{text:`Tile percentages compare the trailing half of the selected window with the prior equal-length half. 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 ${kn.toLocaleString()} matching rows while the table shows ${ss} per page.`})]}),d?.window?.startDate&&d.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[d.window.startDate," to ",d.window.endDate,(d.window.daysSinceLatestData??0)>0&&` · latest data ${d.window.daysSinceLatestData} day${d.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"segmented",role:"group","aria-label":"Performance time period",children:Lu.map(u=>e.jsx("button",{type:"button","aria-pressed":L===u,className:`segmented-option ${L===u?"segmented-option-active":""}`,onClick:()=>{U(u),ue(0),tt.setPage(1)},children:u==="all"?"All":u},u))}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:we,onClick:()=>{ue(0),tt.setPage(1),Ws(0),Zn()},children:we?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const{totals:u,daily:E,trends:ae,periodComparison:ce}=d,Ue=Ni.filter(ge=>T.includes(ge.key)).map(ge=>({dataKey:ge.key,label:ge.label,color:ge.color,axisId:ge.key,inverted:ge.inverted,formatValue:ge.format,trend:fe?ae?.[ge.key]??null:null})),We=ge=>u[ge]??null,bt=new Map(E.map(ge=>[ge.date,ge])),Ye=E.length===0?[]:Kd(E[0].date,E[E.length-1].date).map(ge=>bt.get(ge)??{date:ge});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Ni.map(ge=>{const cs=T.includes(ge.key),Ys=We(ge.key),Nn=Ys===null;return e.jsxs("button",{type:"button","aria-pressed":cs,disabled:Nn,className:`rounded-md border px-3 py-2 text-left transition-colors ${cs?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Nn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{H(ds=>ds.includes(ge.key)?ds.length===1?ds:ds.filter(wo=>wo!==ge.key):[...ds,ge.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:cs?ge.color:"transparent",border:`1px solid ${ge.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ge.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Ys===null?"—":ge.format(Ys)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Eu(ce,ge.key,ge.inverted)})]},ge.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:fe,onChange:ge=>xe(ge.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(Ed,{data:Ye,xKey:"date",series:Ue,xTickFormatter:Kn,labelFormatter:Is,onSelectX:ta,selectedX:Q})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:E.map(ge=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":Q===ge.date,onClick:()=>ta(ge.date),children:[Is(ge.date),": ",ge.clicks," clicks, ",ge.impressions," impressions"]},ge.date))}),Q&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Is(Q)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>ta(Q),children:["Show all ",u.days," days"]})]}),u.position!==null&&(u.positionDays??u.days)<u.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",u.positionDays," of ",u.days," days. The rest have no property-level position recorded."]}),(u.position===null||u.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:q.startDate,onChange:u=>N(E=>({...E,startDate:u.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:q.endDate,onChange:u=>N(E=>({...E,endDate:u.target.value}))}),e.jsx(on,{value:q.query,onChange:u=>N(E=>({...E,query:u})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(on,{value:q.page,onChange:u=>N(E=>({...E,page:u})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),h.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(As).map(u=>e.jsx("th",{className:"text-right","aria-sort":Nt?.key===u?Nt.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:()=>{tt.setPage(1),ys(E=>E?.key===u?E.dir==="desc"?{key:u,dir:"asc"}:null:{key:u,dir:"desc"})},children:[Uo[u],Nt?.key===u?Nt.dir==="desc"?" ↓":" ↑":""]})},u))]})}),e.jsx("tbody",{children:os.map((u,E)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:u.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:u.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(qn,{value:u.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:u.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:u.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(u.ctr)?u.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:u.position.toFixed(1)})]},`${u.date}:${u.query}:${u.page}:${E}`))})]})}),e.jsx(_s,{page:Z?tt.page:Math.floor(se/ss)+1,pageSize:ss,visibleRows:os.length,totalRows:Z?X:void 0,hasNextPage:Z?void 0:re,disabled:we,itemLabel:Z?"matches":"rows",onPageChange:u=>{if(Z){tt.setPage(u);return}const E=(u-1)*ss;ue(E),Ws(E)}}),Z&&X>=kn?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",kn.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(pe,{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(Ke,{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:[te&&te.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:$t,onClick:()=>{fo()},children:$t?"Requesting…":`Request indexing (${te.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:He,onClick:()=>{Ja(!0)},children:He?"Loading…":"Reload saved coverage"})]})]}),te&&te.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const u=te.summary.indexed+te.summary.notIndexed,E=u>0?te.summary.indexed/u:0,ae=u>0?te.summary.notIndexed/u:0,ce=54,qe=2*Math.PI*ce,Ue=qe*(1-E),We=qe*ae,bt=qe*E;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:Bt.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:Rs.positiveDeep,strokeWidth:"14",strokeDasharray:qe,strokeDashoffset:Ue,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),te.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:Bt.textFaint,strokeWidth:"14",strokeDasharray:`${We} ${qe-We}`,strokeDashoffset:-bt,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.jsxs("span",{className:"text-3xl font-bold tabular-nums text-primary",children:[(E*100).toFixed(0),"%"]}),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:te.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:te.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(te.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(te.reasonGroups??[]).length," ",(te.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),te.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:te.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(u=>{const E=u==="indexed"?te.indexed.length:u==="notIndexed"?te.notIndexed.length:te.deindexed.length,ae=u==="indexed"?"Indexed":u==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":Xe===u,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${Xe===u?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{vs(u),Ut(null)},children:[ae," (",E,")"]},u)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Xe==="indexed"&&te.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:Se.map(u=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:u.url}),e.jsx("td",{className:"text-secondary",children:u.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:u.crawlTime?u.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:u.isMobileFriendly===!0?"Yes":u.isMobileFriendly===!1?"No":"—"})]},u.id))})]}),Xe==="notIndexed"&&!rt&&(te.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:(te.reasonGroups??[]).map(u=>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:()=>Ut(u.reason),onKeyDown:E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),Ut(u.reason))},tabIndex:0,role:"button","aria-label":`View ${u.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:u.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:u.count})]},u.reason))})]}),Xe==="notIndexed"&&!rt&&(te.reasonGroups??[]).length===0&&te.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:ft.map(u=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:u.url}),e.jsx("td",{className:"text-secondary",children:u.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:u.coverageState??"Unknown"})]},u.id))})]}),Xe==="notIndexed"&&rt&&(()=>{const u=(te.reasonGroups??[]).find(E=>E.reason===rt);return u?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:()=>Ut(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:u.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[u.count," affected page",u.count!==1?"s":""]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:$t,onClick:()=>{Za(u.urls.map(E=>E.url))},children:$t?"Requesting…":`Request indexing (${u.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:Pt.map(E=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:E.url}),e.jsx("td",{className:"text-secondary",children:E.crawlTime?E.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:$t,onClick:()=>{Za([E.url])},title:"Request indexing",children:"Index"})})]},E.id))})]})]}):null})(),Xe==="deindexed"&&te.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:ot.map((u,E)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:u.url}),e.jsx("td",{className:"text-secondary",children:u.previousState}),e.jsx("td",{className:"text-secondary",children:u.currentState}),e.jsx("td",{className:"text-secondary",children:u.transitionDate.split("T")[0]})]},`${u.url}-${E}`))})]}),(Xe==="indexed"&&te.indexed.length===0||Xe==="notIndexed"&&!rt&&te.notIndexed.length===0||Xe==="deindexed"&&te.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(_s,{page:G,pageSize:ms,visibleRows:Math.min(ms,W.length-J),totalRows:W.length,onPageChange:be,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":kt,onClick:()=>Qt(u=>!u),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:kt?"Hide snapshots":gt.length>0?`View ${gt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",te.summary.indexed.toLocaleString()," indexed, ",te.summary.notIndexed.toLocaleString()," not indexed.",Ne&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",Ne.indexed>=0?"+":"",Ne.indexed.toLocaleString()," indexed, ",Ne.notIndexed>=0?"+":"",Ne.notIndexed.toLocaleString()," not indexed."]})]}),kt&&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(u=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:u.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:u.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:u.notIndexed.toLocaleString()})]},u.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:He?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(pe,{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(Ke,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Pe||!Mt?.propertyId,onClick:()=>{ea()},children:Pe?"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:me,onChange:u=>ve(u.target.value),onKeyDown:u=>u.key==="Enter"&&void Ms([me.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!js||it||!me.trim(),onClick:()=>{Ms([me.trim()])},children:it?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!js||it||Yn.length===0,onClick:()=>{Ms(Yn)},children:it?"Resubmitting…":po}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!js||it||!dt?.length,onClick:()=>{vo()},children:"Resubmit all files"}),et&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",et.indexes," index",et.indexes===1?"":"es",", ",et.files," file",et.files===1?"":"s"]}),F&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",F.completed,"/",F.total]})]}),!js&&Mt&&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:Te(ii),children:"Reconnect"})]}),dt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:dt.length>0?e.jsxs(e.Fragment,{children:[e.jsx(on,{value:pt,onChange:u=>{at(u),At.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:At.rows.flatMap(u=>{const E=wi(u),ae=Si(u),ce=Ci(u),qe=ct[u.path]??[],Ue=Le.has(u.path),We=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(qn,{value:u.path})}),e.jsx("td",{className:"text-secondary",children:u.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":Ue,"aria-label":`${Ue?"Collapse":"Expand"} files in ${u.path}`,onClick:()=>{bo(u.path)},children:Gt.has(u.path)?"Loading…":`${Ue?"▾":"▸"} Index${ct[u.path]?` (${qe.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ce}),e.jsx("td",{className:"text-secondary",children:u.lastSubmitted?u.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:u.lastDownloaded?u.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:E.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ae||"—"}),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:!js||it,onClick:()=>{Ms([u.path])},children:u.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Mt?.sitemapUrl===u.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:()=>{ei(u.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Jn.isPending,onClick:()=>{ti(u.path)},children:"Inspect URLs"})]})})]},u.path),bt=u.isSitemapsIndex&&Ue?qe.map(Ye=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(qn,{value:Ye.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Ci(Ye)}),e.jsx("td",{className:"text-secondary",children:Ye.lastSubmitted?Ye.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:Ye.lastDownloaded?Ye.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:wi(Ye).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Si(Ye)||"—"}),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:!js||it,onClick:()=>{Ms([Ye.path])},children:"Resubmit"}),Mt?.sitemapUrl===Ye.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:()=>{ei(Ye.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Jn.isPending,onClick:()=>{ti(Ye.path)},children:"Inspect URLs"})]})})]},`${u.path}:${Ye.path}`)):[];return[We,...bt]})})]}),e.jsx(_s,{page:At.page,pageSize:ss,visibleRows:At.rows.length,totalRows:At.totalRows,onPageChange:At.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(pe,{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:p,onChange:u=>w(u.target.value),onKeyDown:u=>u.key==="Enter"&&void ri()}),e.jsx(A,{type:"button",size:"sm",disabled:ye||!Mt?.propertyId||!p.trim(),onClick:Te(ri),children:ye?"Inspecting…":"Inspect URL"})]}),R&&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:R.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:R.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:oi(R.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:Tt(R.crawlTime)})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:$,onClick:()=>{jn(!0)},children:$?"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:$e,onChange:u=>st(u.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:$,onClick:()=>{jn(!0)},children:"Apply filter"})]}),S.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:S.map(u=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:u.url}),e.jsx("td",{className:"text-neutral",children:u.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:u.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:u.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:oi(u.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Tt(u.inspectedAt)})]},u.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(pe,{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"})]})}),v.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:v.map(u=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:u.url}),e.jsx("td",{className:"text-secondary",children:u.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:u.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Tt(u.transitionDate)})]},`${u.url}:${u.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Mt&&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:()=>Kt(u=>!u),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 ${zt?"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"})]})}),zt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(pe,{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(Ke,{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:B,disabled:Ve||m.length===0,onChange:u=>y(u.target.value),children:m.length===0?e.jsx("option",{value:"",children:Ve?"Loading properties…":"No properties available"}):m.map(u=>e.jsxs("option",{value:u.siteUrl,children:[u.siteUrl," · ",u.permissionLevel]},u.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:Ve,onClick:()=>{Xa(Mt,!0)},children:Ve?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!B||Je,onClick:Te(jo),children:Je?"Saving…":"Save property"})]})]})]}),e.jsxs(pe,{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:C,onChange:u=>Y(u.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:K,onChange:u=>I(u.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:Xn.isPending||!Mt.propertyId,onClick:Te(No),children:Xn.isPending?"Queueing…":"Queue sync"}),!Mt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Gu=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Ou({projectName:t,projectId:s}){const n=bs(),[a,i]=o.useState(null),[r,l]=o.useState(null),[m,c]=o.useState(!1),h=Re(Ea({client:V,path:{name:t}})),x=h.data?.find(D=>D.connectionType==="gbp"),d=!!x,j=a?{locationName:a}:void 0,S=Re({...nl({client:V,path:{name:t}}),enabled:d}),b=Re({...al({client:V,path:{name:t},query:j}),enabled:d}),v=Re({...il({client:V,path:{name:t},query:j}),enabled:d}),g=Re({...rl({client:V,path:{name:t},query:j}),enabled:d}),R=Re({...ol({client:V,path:{name:t},query:j}),enabled:d}),_=Re({...ll({client:V,path:{name:t},query:j}),enabled:d}),B=Re({queryKey:["gbp-section-insights",t],queryFn:()=>cl(t),enabled:d});function y(){ht(n,"gbp")}const p=Ft({...dl(),onSuccess:D=>{fr({id:D.runId,projectId:s,kind:Ts["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Ce({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),w=o.useSyncExternalStore(br,Fn,Fn),C=Object.values(w.runs).some(D=>D.kind===Ts["gbp-sync"]&&D.projectId===s),Y=p.isPending||C,K=Ft({...ul(),onSuccess:()=>y()});if(o.useEffect(()=>{if(!a||!S.data)return;const D=S.data.locations.filter(Z=>Z.selected);(D.length<=1||!D.some(Z=>Z.locationName===a))&&i(null)},[a,S.data]),o.useEffect(()=>{if(!r||!S.data)return;(a?[a]:S.data.locations.filter(Z=>Z.selected).map(Z=>Z.locationName)).includes(r)||l(null)},[r,S.data,a]),h.isLoading)return null;if(!x){const D=[{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(pe,{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:D.map((Z,he)=>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:he+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:Z.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:Z.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:Z.note})]})]},Z.title))})]})})}const I=b.data,L=S.data?.locations??[],U=L.filter(D=>D.selected),T=v.data?.keywords??[],H=g.data?.lodging??[],fe=R.data?.placeActions??[],xe=_.data?.places??[],Q=L.length>0?L[0].accountName:x.domain,ie=a?L.find(D=>D.locationName===a)?.displayName??null:null,oe=a?L.filter(D=>D.locationName===a):U,z=new Set(oe.map(D=>D.locationName)),q=H.filter(D=>z.has(D.locationName)),N=fe.filter(D=>z.has(D.locationName)),se=xe.filter(D=>z.has(D.locationName)),ue=new Set(U.map(D=>D.locationName)),re=a?T:T.filter(D=>ue.has(D.locationName)),le=!a&&U.length>1,X=(B.data??[]).filter(D=>!D.dismissed&&Gu.has(D.type)&&(!ie||D.query===ie||D.query===a||D.title.startsWith(ie)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(pe,{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(Ke,{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(de,{tone:"positive",children:"Connected"}),!ne()&&e.jsx(Qe,{type:"button",variant:"outline",size:"sm",disabled:Y,onClick:()=>p.mutate({client:V,path:{name:t},body:{}}),children:Y?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[Q?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:Q})," · "]}):null,S.data?`${S.data.totalSelected} of ${S.data.totalDiscovered} locations tracked`:"Loading locations…"]}),U.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:D=>i(D.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"}),U.map(D=>e.jsx("option",{value:D.locationName,children:D.displayName},D.id))]})]}),U.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:[X.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),X.map(D=>e.jsx("div",{className:["insight-card",Ju(D.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:[D.title,D.recommendation?.reason&&e.jsx(Ke,{text:D.recommendation.reason})]})},D.id))]}),I&&e.jsx(sm,{performance:I.performance,freshness:I.freshness,timeseries:I.timeseries}),I?.profileCompleteness&&e.jsx(Fu,{summary:I.profileCompleteness}),oe.length>0&&e.jsx(_u,{locations:oe,lodging:q,places:se,placeActions:N,expandedLocation:r,onToggleExpanded:D=>{l(Z=>Z===D?null:D)}}),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"}),v.data&&v.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[v.data.thresholdedPct,"% 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(D=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:D.keyword}),le&&e.jsx("td",{className:"text-muted",children:L.find(Z=>Z.locationName===D.locationName)?.displayName??D.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:D.valueCount!==null?D.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",D.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[D.periodStart,"–",D.periodEnd]})]},`${D.locationName}:${D.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>c(D=>!D),"aria-expanded":m,children:[e.jsx("span",{"aria-hidden":"true",children:m?"▾":"▸"})," Manage locations (",L.length,")"]}),m&&e.jsx("div",{className:"mt-3",children:L.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"}),!ne()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:L.map(D=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:D.displayName}),e.jsx("td",{className:"text-muted",children:D.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(de,{tone:D.selected?"positive":"neutral",children:D.selected?"Tracked":"Not tracked"})}),!ne()&&e.jsx("td",{className:"text-right",children:e.jsx(Qe,{type:"button",variant:"outline",size:"sm",disabled:K.isPending,onClick:()=>K.mutate({client:V,path:{name:t,locationName:D.locationName},body:{selected:!D.selected}}),children:D.selected?"Untrack":"Track"})})]},D.id))})]})})]})]})})}function Fu({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Zs(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Zs(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Zs(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Zs(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Zs(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(Ke,{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 ${Xu(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function _u({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:i,onToggleExpanded:r}){const l=new Map(s.map(h=>[h.locationName,h])),m=new Map(n.map(h=>[h.locationName,h])),c=new Map;for(const h of a){const x=c.get(h.locationName)??[];x.push(h),c.set(h.locationName,x)}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(Ke,{text:ne()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const x=l.get(h.locationName)??null,d=m.get(h.locationName)??null,j=c.get(h.locationName)??[],S=i===h.locationName;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(de,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(de,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Qr(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Uu,{location:h})}),e.jsx("td",{children:e.jsx(Vu,{lodging:x})}),e.jsx("td",{children:e.jsx(Ku,{place:d,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(Hu,{actions:j})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>r(h.locationName),children:S?"Hide":"Details"})})]}),S&&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(Yu,{location:h,lodging:x,place:d,placeActions:j})})})]},h.id)})})]})})]})}function Bu(t){return[{label:"Description",tone:ks(t.description)?"positive":"neutral",value:ks(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:ks(t.primaryPhone)?"positive":"neutral",value:ks(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:ks(t.websiteUri)?"positive":"neutral",value:ks(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 Uu({location:t}){const s=Bu(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(de,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Vu({lodging:t}){return e.jsx(Ga,{...zu(t)})}function zu(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 Ku({place:t,mapsUri:s}){return e.jsx(Ga,{...Qu(t,s)})}function Qu(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 Hu({actions:t}){return e.jsx(Ga,{...Wu(t)})}function Wu(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 Ga({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(de,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Yu({location:t,lodging:s,place:n,placeActions:a}){const i=s?em(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(la,{title:"Owner profile · Business Information",children:[e.jsx(It,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(It,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(It,{label:"Description",value:ks(t.description)?t.description:"Not returned"}),e.jsx(It,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(It,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(It,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(It,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(It,{label:"Open status",value:Qr(t.openStatus)}),e.jsx(It,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(la,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(It,{label:"Last checked",value:ki(s.syncedAt)}),e.jsx(It,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(It,{label:"Populated groups",value:i.length>0?i.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(la,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(It,{label:"Places tier",value:n.tier}),e.jsx(It,{label:"Last checked",value:ki(n.syncedAt)}),e.jsx(It,{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(r=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Qn(r.placeActionType),r.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Qn(r.providerType),r.uri?` · ${Zu(r.uri)}`:""]})]},r.placeActionLinkName))})})]})]})}function la({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 It({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 Zs(t,s,n){return t===s?"positive":t===0?n:"caution"}function Xu(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Ju(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function ks(t){return typeof t=="string"&&t.trim().length>0}function Qr(t){return t?Qn(t):"Not returned"}function Qn(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Zu(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function ki(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function em(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&tm(n)).map(([s])=>Qn(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function tm(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function sm({performance:t,freshness:s,timeseries:n}){const a=t.totals,i=ml.filter(b=>(a[b]??0)>0),r=hl.filter(b=>(a[b]??0)>0),l=Object.keys(a).filter(b=>(a[b]??0)>0&&xl(b)==="other").sort((b,v)=>(a[v]??0)-(a[b]??0)),m=Object.keys(a).filter(b=>(a[b]??0)===0).sort(),c=n.map(b=>{const v={date:b.date};for(const[g,R]of Object.entries(b.metrics))v[g]=R;return v}),h=n.find(b=>b.pending)?.date,x=n.length>0?n[n.length-1].date:void 0,d=c.length>0,j=s.dataThroughDate?`Data through ${Is(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,S=[...i,...l];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"}),j&&e.jsx("span",{className:"text-[11px] text-muted",children:j})]}),!d||i.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(Ai,{data:c,metrics:i,kind:"line",firstPending:h,lastDate:x}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:S.map(b=>e.jsxs("span",{className:"text-sm text-secondary",children:[_n(b)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[b]??0).toLocaleString()})]},b))})]})]}),d&&r.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Ai,{data:c,metrics:r,kind:"area",firstPending:h,lastDate:x})]}),m.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",m.map(b=>_n(b)).join(", ")]})]})}function Ai({data:t,metrics:s,kind:n,firstPending:a,lastDate:i}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(dn,{width:"100%",height:"100%",children:e.jsxs(un,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Tr,{stroke:Ir,vertical:!1}),e.jsx(mn,{dataKey:"date",tick:Yt,tickLine:!1,axisLine:{stroke:Ls},tickFormatter:Kn,minTickGap:24}),e.jsx(hn,{tick:Yt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(xn,{...Bs,labelFormatter:Is,formatter:(r,l)=>[typeof r=="number"?r.toLocaleString():String(r??0),_n(String(l??""))]}),e.jsx($r,{wrapperStyle:{fontSize:11,color:Bt.text},formatter:r=>_n(r)}),a&&i&&e.jsx(_d,{x1:a,x2:i,fill:Bt.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:Bt.textDim,fontSize:10}}),s.map((r,l)=>n==="line"?e.jsx(Lr,{type:"monotone",dataKey:r,stroke:yt[l%yt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},r):e.jsx(Os,{type:"monotone",dataKey:r,stackId:"reach",stroke:yt[l%yt.length],fill:yt[l%yt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},r))]})})})}function nm(t){return Rr(fs(String(t)))}function am(t){return $s(fs(String(t)))}function ca({children:t,label:s="More info",placement:n="top",className:a}){const i=o.useId(),[r,l]=o.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":r?i: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:()=>l(!0),onMouseLeave:()=>l(!1),onFocus:()=>l(!0),onBlur:()=>l(!1),children:e.jsx(Td,{className:"h-3.5 w-3.5","aria-hidden":!0})}),r&&e.jsx("span",{id:i,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 An=ss;function Ds(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function da(t){return t.toLocaleString()}function im(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function rm(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 om(t){const s=t.filter(n=>n.kind===Ts["backlink-extract"]&&!vr(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function lm(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 i=Math.floor(a/60),r=a%60;return r===0?`${i}m`:`${i}m ${r}s`}function cm({projectName:t}){const[s,n]=o.useState(null),[a,i]=o.useState(null),[r,l]=o.useState([]),[m,c]=o.useState(null),[h,x]=o.useState(null),[d,j]=o.useState(null),[S,b]=o.useState(Date.now()),[v,g]=o.useState(0),[R,_]=o.useState(!0),[B,y]=o.useState(!1),[p,w]=o.useState(null),C=o.useCallback(async()=>{_(!0),w(null);try{const[Q,ie,oe,z,q]=await Promise.all([pl().catch(()=>null),gl(t,{excludeCrawlers:!0}).catch(()=>null),fl(t,{limit:An,offset:v,excludeCrawlers:!0}).catch(se=>{if(se instanceof Ks&&se.code==="NOT_FOUND")return null;throw se}),bl(t).catch(()=>[]),vl(t).catch(()=>[])]);c(Q),n(ie),i(oe),l(z);const N=om(q);x(N)}catch(Q){w(Q instanceof Error?Q.message:"Failed to load backlinks")}finally{_(!1)}},[t,v]);o.useEffect(()=>{C()},[C]),o.useEffect(()=>{if(!h)return;const Q=h.id;let ie=!1;const oe=async()=>{try{const q=await Ca(Q);if(ie)return;vr(q.status)?(x(null),j(q),await C()):x(N=>N?.id===q.id?{...N,...q}:N)}catch{}},z=window.setInterval(()=>{oe()},3e3);return()=>{ie=!0,window.clearInterval(z)}},[h,C]),o.useEffect(()=>{if(!h)return;const Q=window.setInterval(()=>b(Date.now()),1e3);return()=>window.clearInterval(Q)},[h]),o.useEffect(()=>{if(!d||d.status==="failed")return;const Q=window.setTimeout(()=>j(null),1e4);return()=>window.clearTimeout(Q)},[d]);async function Y(){y(!0),w(null);try{const Q=await jl(t);x(Q)}catch(Q){Q instanceof Ks&&Q.code==="MISSING_DEPENDENCY"?w("DuckDB is not installed. Visit the Backlinks admin page to install it."):w(Q instanceof Error?Q.message:"Failed to trigger extract")}finally{y(!1)}}const K=o.useMemo(()=>r.slice().sort((Q,ie)=>Q.queriedAt.localeCompare(ie.queriedAt)).map(Q=>({date:Q.queriedAt,linkingDomains:Q.totalLinkingDomains})),[r]),I=a?.rows??[],L=a?.total??0,U=s?.excludedLinkingDomains??0,T=Math.floor(v/An)+1;return o.useEffect(()=>{v>0&&v>=L&&g(0)},[v,L]),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"})]})}),p&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:p})}),h&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Rd,{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(de,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[lm(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",S]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),d&&!h&&e.jsx(pe,{className:`surface-card p-4 mb-4 ${d.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[d.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(Ar,{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 ${d.status==="failed"?"text-negative":"text-positive"}`,children:d.status==="failed"?"Extract failed":"Extract complete"}),d.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:yl(d.error)}):d.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),H()]});function H(){return R?e.jsx(pe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):fe()}function fe(){const Q=s!==null&&s.totalLinkingDomains>0,ie=d?.status==="failed",oe=s!==null&&s.totalLinkingDomains===0&&!ie,z=m?.status==="ready",q=m?.status==="failed",N=m&&(m.status==="downloading"||m.status==="querying"||m.status==="queued");return Q?xe(e.jsxs(e.Fragment,{children:[!ne()&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:B||h!==null,onClick:Te(Y),children:[e.jsx(Pr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":B?"Queuing…":"Re-run extract"]}),e.jsx(ca,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ne()&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Ds("/backlinks"),children:"Open admin"})})]})):e.jsx(pe,{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($d,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!m&&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."}),!ne()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ds("/backlinks"),children:"Set up backlinks"})})})]}),N&&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 (",m.status,m.phaseDetail?` — ${m.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!ne()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Ds("/backlinks"),children:"View sync status"})})})]}),q&&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:m.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!ne()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ds("/backlinks"),children:"Go to Backlinks admin"})})})]}),z&&!N&&!oe&&!ie&&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:m.release})," is ready. Run an extract for this project."]}),!ne()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:B||h!==null,onClick:Te(Y),children:[e.jsx(Vn,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":B?"Queuing…":"Run extract"]}),e.jsx(ca,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),ie&&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."}),!ne()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ds("/backlinks"),children:"Go to Backlinks admin"})})})]}),oe&&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 ",s.targetDomain,". Try a newer release or re-run this extract."]}),!ne()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ds("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:B||h!==null,onClick:Te(Y),children:[e.jsx(Vn,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":B?"Queuing…":"Re-run extract"]}),e.jsxs(ca,{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:s.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 xe(Q){if(!s)return null;const ie="Linking hosts",oe="linking hosts",z="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:da(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",oe]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:da(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",oe," 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:im(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",oe," 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"})," · ",z," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",rm(s.queriedAt),U>0&&e.jsxs(e.Fragment,{children:[" · ",U," excluded domain",U===1?"":"s"]})]}),K.length>=2&&e.jsxs(pe,{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(dn,{width:"100%",height:"100%",children:e.jsxs(un,{data:K,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:yt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:yt[0],stopOpacity:0})]})}),e.jsx(mn,{dataKey:"date",tick:Yt,stroke:Ls,tickFormatter:nm}),e.jsx(hn,{tick:Yt,stroke:Ls,allowDecimals:!1}),e.jsx(xn,{contentStyle:Bs.contentStyle,labelStyle:Bs.labelStyle,itemStyle:Bs.itemStyle,labelFormatter:am}),e.jsx(Os,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:yt[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(pe,{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:ie})]})}),e.jsxs("tbody",{children:[I.map(q=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:q.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:da(q.numHosts)})]},q.linkingDomain)),I.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:U>0&&L===0?`Every referring domain in this ${z} was a crawler/proxy host (${U} hidden).`:`No referring domains in this ${z}.`})})]})]})}),e.jsx(_s,{page:T,pageSize:An,visibleRows:I.length,totalRows:L,onPageChange:q=>g((q-1)*An)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:Q})]})}}function dm({projectName:t}){const s=Re({...Nl({client:V,path:{name:t}}),staleTime:yr}),n=s.data??null,a=s.error;if(s.isLoading&&!n)return null;if(a)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:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-negative-400",children:qa(a)})]});if(!n)return null;if(n.status==="no-data")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:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:i,providersMentioning:r,providersConfigured:l}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",i," of ",l," engines",e.jsx(Ke,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",r," of ",l," engine answers",e.jsx(Ke,{text:"An engine is ‘mentioning’ when our brand or domain appears inside the prose of the answer text — independent of whether it’s in the citation list. Models often name-drop from training without citing a fresh page."})]})]}),n.summary.latestRunAt&&e.jsxs("p",{className:"supporting-copy",children:["Latest run ",new Date(n.summary.latestRunAt).toLocaleString()]})]}),e.jsx(um,{data:n}),e.jsx(mm,{data:n}),n.competitorGaps.length>0&&e.jsx(gm,{data:n})]})}function um({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:i,queriesInvisible:r}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Pn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Pn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Pn,{label:"Mentioned only",value:`${i} / ${s}`,helper:"Named in answer, no source link",tone:i>0?"caution":"neutral"}),e.jsx(Pn,{label:"Invisible",value:`${r} / ${s}`,helper:"No engine cites or mentions",tone:r>0?"negative":"neutral"})]})}function Pn({label:t,value:s,helper:n,tone:a}){const i=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="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 ${i}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function mm({data:t}){const s=o.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const i of a.providers)n.add(i.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(hm,{}),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:"Query"}),s.map(n=>e.jsx("th",{className:"text-center",children:e.jsx(zs,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const i=n.providers.find(r=>r.provider===a);return e.jsx("td",{className:"text-center",children:i==null?e.jsx(Ld,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(xm,{provider:i})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function hm(){return e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-3 text-[11px] text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Fs,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Fs,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Fs,{active:!1,tone:"cited"}),e.jsx(Fs,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function xm({provider:t}){const s=pm(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Fs,{active:t.cited,tone:"cited"}),e.jsx(Fs,{active:t.mentioned,tone:"mentioned"})]})}function pm(t){return t.cited&&t.mentioned?"Cited in sources and mentioned in answer":t.cited?"Cited in sources, not mentioned in answer":t.mentioned?"Mentioned in answer, not in sources":"Not cited and not mentioned"}function Fs({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-strong bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-positive-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-info-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function gm({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-strong mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(Ke,{text:"Queries where the project is not cited but a configured competitor is. Each row maps to one (query, engine) pair — the same query may surface for multiple engines."}),e.jsxs("span",{className:"text-[10px] font-normal uppercase tracking-wide text-muted",children:[t.competitorGaps.length," ",t.competitorGaps.length===1?"gap":"gaps"]})]}),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:"Query"}),e.jsx("th",{children:"Engine"}),e.jsx("th",{children:"Competitors cited"})]})}),e.jsx("tbody",{children:t.competitorGaps.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.query}),e.jsx("td",{children:e.jsx(zs,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const bn="__cited__",vn="__mentioned__",_t="__mentionShare__";function Hr(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:fs(n),end:fs(a),sweepCount:s.sweepCount??1}}function Hn(t){const s=Hr(t);if(!s)return"Sweep date unavailable";const n=$s(s.start),a=$s(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function fm(t){const s=Hr(t);return s?Rr(s.start):""}function Hs(t){return t.trim().toLowerCase()}function Ia(t){return Math.round(t*1e3)/10}function Ra(t){return t.byProvider??{}}function bm(t,s,n){const a=t.buckets.length>0,i=t.buckets.length===1;if(n==="overall"){const c=s==="cited"?bn:vn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(d=>({date:d.startDate,[c]:Ia(d[h])})),series:[c],hasData:a,singleBucket:i}}const r=s==="mentioned"?"mentionRate":"citationRate",l=[...new Set(t.buckets.flatMap(c=>Object.keys(Ra(c))))].sort();return{rows:t.buckets.map(c=>{const h={date:c.startDate},x=Ra(c);for(const d of l){const j=x[d];h[d]=j?Ia(j[r]):null}return h}),series:l,hasData:a,singleBucket:i}}function Wr(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function vm(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function ym(t){return t.servedModelAttribution??{}}function jm(t){return t.modelServiceMismatch??{}}function Nm(t){return t.modelPointerChanges??{}}function wm(t){return t.length>0?t.join(", "):null}function Pi(t,s){const n=Hs(s);return Object.entries(t).find(([a])=>Hs(a)===n)?.[1]}function ns(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return`Mixed: ${t.models.join(", ")}${t.includesUnknown?" + unknown":""}`}}function Sm(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!Pi(Ra(a),s))continue;const i=Wr(a);return i?Pi(i,s)??null:null}return null}function Cm(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const i of a.events){const r=s.get(i.bucketStartDate)??[];r.push({provider:n,event:i}),s.set(i.bucketStartDate,r)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((i,r)=>i.provider.localeCompare(r.provider)||i.event.observedAt.localeCompare(r.event.observedAt))}))}function km(t){const s={},n=[];for(const[a,i]of Object.entries(t)){const r=i.events.filter(l=>!l.fromPreWindowAnchor);for(const l of i.events)l.fromPreWindowAnchor&&n.push({provider:a,event:l});r.length>0&&(s[a]={...i,events:r})}return{buckets:Cm(s),beforeWindow:n.sort((a,i)=>a.event.observedAt.localeCompare(i.event.observedAt)||a.provider.localeCompare(i.provider))}}function Am(t){let s=0,n=0;for(const a of Object.values(t))s+=a.events.length,n+=a.eventTotal??a.events.length;return{shown:s,total:n}}function Pm(t){const s=[];for(const[n,a]of Object.entries(t)){const i=a.eventTotal??a.events.length;i>a.events.length&&s.push({provider:n,shown:a.events.length,total:i})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Im(t){const s=t.buckets.map(a=>{const i=a.mentionShare;return{date:a.startDate,[_t]:i?.rate==null?null:Ia(i.rate)}}),n=s.map(a=>a[_t]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[_t],hasData:n.length>0,singleBucket:n.length===1}}function Rm(t,s,n){return s==="mentionShare"?Im(t):bm(t,s,n)}function Ii(t,s){for(let n=t.length-1;n>=0;n--){const a=t[n][s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Ri(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function $i(t){return t>0?`+${t}`:`${t}`}function $m(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${$i(n.delta)} on ${Ri(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${$i(s.delta)} on ${Ri(s.date)})`}const Tm=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Lm=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Mm=[{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:"On non-brand queries, the share of answer-text brand mentions for you and tracked competitors that were you. Pooled only when query classification is unavailable."}],Oa=yt[2],Dm="var(--chart-tooltip-bg)",Em={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function is(t){const s=Hs(t);return Em[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ps(t){return Math.round(t*10)/10}function qm(t){return t===bn||t===vn||t===_t}function Yr(t){return t===bn?"Cited":t===vn?"Mentioned":t===_t?"Mention share":is(t)}function sn(t,s){return t===bn?Rs.positive:t===vn?yt[1]:t===_t?Oa:qd(Hs(t),s)}function Gm(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Om(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
2
+ `)}function pn(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function On(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${pn(s)}`:"Mention share":"Mentioned"}function gn(t){return t==="cited"?"citationRate":"mentionRate"}function Xr(t,s){return s==="cited"?t.cited:t.mentionedCount}function Jr(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 Zr(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function $a(t){const s=Wr(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[i])=>Hs(a).localeCompare(Hs(i))).map(([a,i])=>`${is(a)}: ${ns(i)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function Fm(t){return t.some(({event:s})=>s.to.status==="mixed")?Rs.caution:t.some(({event:s})=>s.to.status==="unknown")?Rs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?yt[4]:Rs.positive}function _m(t,s,n){const a=Zr(t,s);return a?Hn(a):$s(fs(n))}function Bm({partition:t,available:s,counts:n,truncated:a,incompleteHistory:i,served:r,mismatch:l,buckets:m}){const c=o.useId(),h=Object.entries(r).sort(([d],[j])=>d.localeCompare(j)),x=t.buckets.length>0||t.beforeWindow.length>0;return e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":c,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:c,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),s?x?e.jsxs(e.Fragment,{children:[t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:d,events:j})=>j.map(({provider:S,event:b})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:_m(m,d,b.observedAt)}),e.jsxs("span",{children:[is(S),": ",ns(b.from)," → ",ns(b.to)]})]},`${S}-${b.observedAt}-${b.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:d,event:j})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",$s(fs(j.observedAt))]}),e.jsxs("span",{children:[is(d),": ",ns(j.from)," → ",ns(j.to),j.anchorObservedAt?` (last seen ${ns(j.from)} on ${$s(fs(j.anchorObservedAt))})`:""]})]},`before-${d}-${j.observedAt}`))})]}),a.map(d=>e.jsxs("p",{className:"trend-model-evidence-note",children:[is(d.provider),": showing the most recent ",d.shown," of ",d.total," changes."]},`truncated-${d.provider}`)),i.map(d=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",is(d)," change."]},`incomplete-${d}`))]}):e.jsx("p",{className:"trend-model-evidence-empty",children:"No model evidence changes in this window."}):e.jsx("p",{className:"trend-model-evidence-empty",children:"Attribution unavailable from this API version."}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:h.map(([d,j])=>{const S=wm(j.latestServedModelIds),b=l[d];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:$s(fs(j.latestObservation.observedAt))}),e.jsxs("span",{children:[is(d),": ",S??ns(j.latestObservation.state),b?` — not the ${ns(b.configured)} you selected`:""]})]},`served-${d}`)})})]})]})}function Ti(t){return t===null?"no data":`${t}%`}function ua(t){return t==null?"undefined":`${ps(t*100)}%`}function Um({active:t,label:s,payload:n,metric:a,mode:i,buckets:r}){if(!t)return null;const l=Zr(r,s);if(!l)return null;if(a==="mentionShare"){const c=l.mentionShare.projectMentionSnapshots,h=l.mentionShare.competitorMentionSnapshots,x=c+h,d=l.mentionShare.rate==null?null:ps(l.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Hn(l)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:Oa},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",pn(l.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:Ti(d)})]}),x>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",c," / ",x," brand mentions. Competitors ",h,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:$a(l)})]})}const m=i==="byProvider"?(n??[]).filter(c=>c.dataKey!==void 0):[{dataKey:a==="cited"?bn:vn,value:ps(l[gn(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Hn(l)}),m.map((c,h)=>{const x=String(c.dataKey??c.name??""),d=i==="byProvider"?Jr(l,x,a):null,j=d?.count??Xr(l,a),S=d?.total??l.total,b=typeof c.value=="number"?c.value:ps(d?d.rate*100:l[gn(a)]*100),v=c.color??sn(x,h);return e.jsxs("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:Yr(x)}),e.jsx("span",{className:"trend-tooltip-value",children:Ti(b)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[j," / ",S," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${x}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:$a(l)})]})}function Vm({buckets:t,metric:s,mode:n,series:a}){const i=t[t.length-1]?.mentionShare.scope;return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[On(s,i)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(r=>{let l;if(s==="mentionShare"){const m=r.mentionShare.projectMentionSnapshots,c=r.mentionShare.competitorMentionSnapshots,h=m+c,x=pn(r.mentionShare.scope);l=h>0?`${ua(r.mentionShare.rate)} mention share for ${x}, ${m} of ${h} brand mentions were you`:`mention share undefined for ${x}, no project or competitor brand mentions`}else n==="byProvider"?l=a.map(m=>{const c=Jr(r,m,s);return c?`${is(m)} ${ua(c.rate)} ${On(s).toLowerCase()}, ${c.count} of ${c.total} snapshots`:`${is(m)} no data`}).join("; "):l=`${ua(r[gn(s)])} ${On(s).toLowerCase()}, ${Xr(r,s)} of ${r.total} snapshots`;return l+=`; ${$a(r)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Hn(r)}),e.jsx("td",{children:l})]},r.startDate)})})]})}function ma({options:t,value:s,onChange:n,ariaLabel:a,className:i}){const r=o.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${i??""}`,children:t.map(l=>{const m=s===l.value,c=l.description?`${r}-${l.value}-description`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":m,"aria-describedby":c,className:`segmented-option ${m?"segmented-option-active":""}`,onClick:()=>n(l.value),children:l.label}),l.description&&e.jsx("span",{id:c,className:"sr-only",children:l.description})]},l.value)})})}function zm({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,i]=o.useState("all"),[r,l]=o.useState("mentioned"),[m,c]=o.useState("byProvider"),h=o.useMemo(()=>Om(s),[s]),x=Re({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>wl(t,a),staleTime:yr}),d=x.data??null,j=x.error,S=r==="mentionShare"?"overall":m,b=o.useMemo(()=>d?Rm(d,r,S):null,[d,r,S]),v=d?vm(d):null,g=o.useMemo(()=>km(v??{}),[v]),R=o.useMemo(()=>Am(v??{}),[v]),_=o.useMemo(()=>Pm(v??{}),[v]),B=o.useMemo(()=>Object.entries(v??{}).filter(([,q])=>q.anchorUnavailable).map(([q])=>q).sort(),[v]),y=o.useMemo(()=>d?ym(d):{},[d]),p=o.useMemo(()=>d?jm(d):{},[d]),w=o.useMemo(()=>d?Sl(Nm(d)):null,[d]),C=r!=="mentionShare"&&S==="byProvider",Y=d?.buckets??[],K=Y[Y.length-1]?.mentionShare.scope??d?.mentionShareScope??"pooled",I=On(r,K),L=r==="cited"?Rs.positive:r==="mentionShare"?Oa:yt[1],U=C?Bt.textDim:L,T=o.useMemo(()=>{const q=new Map(Y.map(N=>[N.startDate,fm(N)]));return N=>q.get(String(N))??""},[Y]),H=r==="mentionShare"?b?Ii(b.rows,_t):null:Y.length>0?ps(Y[Y.length-1][gn(r)]*100):null,fe=r==="mentionShare"?b?Gm(b.rows,_t):null:Y.length>0?ps(Y[0][gn(r)]*100):null,xe=r==="mentionShare"?b?.rows.filter(q=>typeof q[_t]=="number").length??0:Y.length,Q=H!==null&&fe!==null&&xe>1?ps(H-fe):null,ie=s.length,oe=e.jsxs(e.Fragment,{children:[w?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:w.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(Ke,{text:"Three separate signals over sweep buckets: answer text mentions, source citations, and your answer-text mention share against tracked competitors. Mentioned and Cited use all query-provider snapshots. Mention share uses non-brand queries when classification is available; pooled means the project has no usable brand identity for a split."})]})]}),H!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:U},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:I}),C&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[H,"%"]}),Q!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${Q>0?"text-positive-400":Q<0?"text-negative-400":"text-muted"}`,children:[Q>0?"+":"",Q.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(ma,{options:Mm,value:r,onChange:l,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),r!=="mentionShare"&&e.jsx(ma,{options:Lm,value:m,onChange:c,ariaLabel:"Series"}),e.jsx(ma,{options:Tm,value:a,onChange:i,ariaLabel:"Time window",className:"sm:ml-auto"})]}),w?.kind==="no-known-change"&&e.jsxs("p",{className:"mt-3 text-[11px] leading-snug text-muted",children:[w.text,e.jsx(Ke,{text:w.detail})]})]});let z;if(j)z=e.jsx("p",{className:"text-sm text-negative-400",children:qa(j)});else if(x.isLoading&&!d)z=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(r==="mentionShare"&&ie===0)z=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!d||!b)z=null;else{const{rows:q,series:N,hasData:se,singleBucket:ue}=b,re=$m(d.queryChanges);if(!se)z=e.jsx("p",{className:"text-sm text-secondary",children:r==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${pn(K)} in this window yet.`:"Run a sweep to start tracking citations and mentions over time."});else if(C&&N.length===0)z=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 le=`${I} rate across ${q.length} ${q.length===1?"sweep":"sweeps"}. Latest ${H}%${Q!==null?`, ${Q>=0?"up":"down"} ${Math.abs(Q).toFixed(1)} points over the period`:""}.`;z=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:le}),e.jsx(Vm,{buckets:Y,metric:r,mode:S,series:N}),C&&N.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:N.map((X,D)=>{const Z=Ii(q,X),he=Sm(Y,X),$e=v===null?"Attribution unavailable":he?ns(he):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:sn(X,D)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:Yr(X)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),$e]})]}),Z!==null&&e.jsxs("span",{className:"trend-legend-value",children:[Z,"%"]})]},X)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${I} trend chart over ${q.length} ${q.length===1?"bucket":"buckets"}`,children:e.jsx(dn,{width:"100%",height:"100%",children:e.jsxs(un,{data:q,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Tr,{stroke:Ir,vertical:!1}),e.jsx(mn,{dataKey:"date",tick:Yt,tickLine:!1,axisLine:{stroke:Ls},tickFormatter:T,minTickGap:24}),e.jsx(hn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:X=>`${X}%`,tick:Yt,tickLine:!1,axisLine:!1,width:40}),e.jsx(xn,{cursor:{stroke:Ls,strokeWidth:1},content:e.jsx(Um,{metric:r,mode:S,buckets:Y})}),g.buckets.map(({bucketStartDate:X,events:D})=>e.jsx(Bd,{x:X,stroke:Fm(D),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${X}`)),N.map((X,D)=>e.jsx(Lr,{type:"monotone",dataKey:X,name:X,stroke:sn(X,D),strokeDasharray:X===_t?"5 4":void 0,strokeWidth:qm(X)?2.5:2,dot:X===_t?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:sn(X,D),strokeWidth:1.5}:{r:2.5,fill:sn(X,D),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Dm},connectNulls:X!==_t,isAnimationActive:!1},X))]})})}),e.jsx(Bm,{partition:g,available:v!==null,counts:R,truncated:_,incompleteHistory:B,served:y,mismatch:p,buckets:Y}),ue&&e.jsx("p",{className:"visibility-trend-note",children:r==="mentionShare"?`Only one ${pn(K)} mention-share point so far. The trend line fills in after another sweep with brand mentions.`:"Only one sweep so far. The trend line fills in after the next run."}),re&&e.jsx("p",{className:"visibility-trend-note",children:re})]})}}return e.jsxs("section",{className:"visibility-trend",children:[oe,z]})}const Li=new Set([rn.queued,rn.running]);function Km({projectName:t}){const s=bs(),[n,a]=o.useState(""),[i,r]=o.useState(""),[l,m]=o.useState(""),[c,h]=o.useState("__default__"),[x,d]=o.useState(null),j=Re({...Cl({client:V,path:{name:t}}),staleTime:6e4}),S=Re({...jr({client:V}),staleTime:6e4}),b=Re({...kl({client:V,path:{name:t},query:{limit:20}}),refetchInterval:I=>I.state.data?.runs.some(L=>Li.has(L.status))?3e3:!1}),v=b.data?.runs??[];o.useEffect(()=>{!x&&v[0]&&d(v[0].id)},[v,x]);const g=v.find(I=>I.id===x)??null,R=Re({...Al({client:V,path:{name:t,runId:x??""}}),enabled:!!x,refetchInterval:g&&Li.has(g.status)?3e3:!1}),_=R.data??null,B=o.useMemo(()=>Wm(n),[n]),y=j.data?.locations??[],p=o.useMemo(()=>{const I=new Map((S.data?.providerCatalog??[]).map(L=>[L.name,L]));return(S.data?.providers??[]).filter(L=>L.configured&&I.get(L.name)?.mode==="api").map(L=>({...L,catalog:I.get(L.name)}))},[S.data]),w=!S.isLoading&&p.length===0,C=p.find(I=>I.name===i)??null;o.useEffect(()=>{i&&!C&&(r(""),m(""))},[i,C]);const Y=Ft({...Pl(),onSuccess:async I=>{d(I.id),a(""),m(""),await Zm(s),Ce({title:"Research batch saved",detail:`${I.totalQueries} quer${I.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${I.id}`,dedupeMode:"replace"})},onError:I=>{Ce({title:"Could not start research",detail:I instanceof Error?I.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function K(){if(B.length===0||B.length>50||w||Y.isPending||ne())return;const I=c==="__default__"?void 0:c==="__none__"?null:y.find(L=>L.label===c)??void 0;Y.mutate({client:V,path:{name:t},body:{queries:B,...i?{provider:i}:{},...i&&l.trim()?{model:l.trim()}:{},...I!==void 0?{location:I}:{}}})}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.85fr)_minmax(360px,1.15fr)]",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"New batch"}),e.jsx("h3",{children:"Research queries"}),e.jsx("p",{className:"mt-1 max-w-xl text-sm leading-6 text-muted",children:"Run specific queries against one API model and keep the answers as a separate research record."})]})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"research-queries",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Queries"}),e.jsx("textarea",{id:"research-queries",className:"mt-1 min-h-36 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:`one query per line
3
+ e.g. What is the best way to choose an AEO platform?`,value:n,onChange:I=>a(I.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${B.length>50?"text-negative":"text-faint"}`,children:[B.length," ",B.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block",htmlFor:"research-provider",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"API provider"}),e.jsxs("select",{id:"research-provider",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:i,onChange:I=>{r(I.target.value),m("")},children:[e.jsx("option",{value:"",children:"Project default"}),p.map(I=>e.jsx("option",{value:I.name,children:I.displayName??I.name},I.name))]})]}),e.jsxs("label",{className:"block",htmlFor:"research-location",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"research-location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:c,onChange:I=>h(I.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),y.map(I=>e.jsx("option",{value:I.label,children:I.label},I.label))]})]})]}),e.jsxs("label",{className:"block",htmlFor:"research-model",children:[e.jsxs("span",{className:"text-xs font-medium text-secondary",children:["Exact model ",e.jsx("span",{className:"font-normal text-muted",children:"(optional)"})]}),e.jsx("input",{id:"research-model",list:"research-known-models",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 disabled:cursor-not-allowed disabled:opacity-50",placeholder:C?`Default: ${C.model??C.defaultModel??C.catalog.defaultModel}`:"Choose a provider to select an exact model",value:l,disabled:!C,onChange:I=>m(I.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(C?.catalog.knownModels??[]).map(I=>e.jsx("option",{value:I.id,children:I.displayName},I.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!ne()&&e.jsxs(Qe,{type:"button",size:"sm",disabled:B.length===0||B.length>50||w||Y.isPending,onClick:K,children:[e.jsx(Vn,{size:14}),Y.isPending?"Starting research…":`Run ${B.length||""} research ${B.length===1?"query":"queries"}`]}),e.jsx("p",{className:"text-xs leading-5 text-muted",children:"Saved to research history. Nothing is added to tracked queries."})]}),w&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."})]})]}),e.jsxs(pe,{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:"Saved research batches"})]}),b.isFetching&&e.jsx(de,{tone:"neutral",children:"Loading"})]}),v.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:"No research batches yet. Add one or more queries to begin."}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:v.map(I=>e.jsxs("tr",{className:x===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:()=>d(I.id),children:Ym(I.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:I.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:I.requestedModel??I.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:I.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[I.completedQueries+I.failedQueries,"/",I.totalQueries]}),e.jsx("td",{children:e.jsx(de,{tone:eo(I.status),children:I.status})})]},I.id))})]})})]})]}),e.jsx(Qm,{detail:_,isLoading:R.isFetching})]})}function Qm({detail:t,isLoading:s}){const[n,a]=o.useState(null);o.useEffect(()=>{a(t?.queries[0]?.id??null)},[t?.id]);const i=t?.queries.find(r=>r.id===n)??t?.queries[0]??null;return e.jsxs(pe,{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:"Results"}),e.jsx("h3",{children:t?`Research run ${Xm(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(de,{tone:eo(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(r=>e.jsxs("tr",{className:i?.id===r.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(r.id),children:r.query})}),e.jsx("td",{children:e.jsx(de,{tone:Jm(r.status),children:r.status})}),e.jsx("td",{children:e.jsx(de,{tone:r.answerMentioned===!0?"positive":r.answerMentioned===!1?"neutral":r.status===Ps.failed?"negative":"caution",children:r.answerMentioned===null?r.status===Ps.failed?"Unavailable":"Pending":r.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(de,{tone:r.citationState==="cited"?"positive":r.citationState==="not-cited"?"neutral":r.status===Ps.failed?"negative":"caution",children:r.citationState===null?r.status===Ps.failed?"Unavailable":"Pending":r.citationState==="cited"?"Cited":"Not cited"})})]},r.id))})]})}),e.jsx(Hm,{query:i,isLoading:s})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved batch to inspect each answer and its source links."})]})}function Hm({query:t,isLoading:s}){return t?e.jsxs("div",{className:"space-y-4 border-t border-default pt-4 xl:border-t-0 xl:border-l xl:pl-4 xl:pt-0",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})]}),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("p",{className:"mt-1 whitespace-pre-wrap text-sm leading-6 text-secondary",children:t.answerText})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===Ps.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(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n},n))})]}),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(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n.replace(/^www\./,"")},n))})]}),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-1",children:t.groundingSources.map((n,a)=>{const i=Cs(n.uri),r=n.title||n.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:r}):e.jsx("span",{className:"truncate text-secondary",children:r}),i&&e.jsx(Md,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${n.uri}-${a}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function Wm(t){const s=new Set;return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>{const a=n.toLocaleLowerCase();return!n||s.has(a)?!1:(s.add(a),!0)})}function Ym(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 Xm(t){return t.length>8?t.slice(0,8):t}function eo(t){return t===rn.completed?"positive":t===rn.partial?"caution":t===rn.failed?"negative":"neutral"}function Jm(t){return t===Ps.completed?"positive":t===Ps.failed?"negative":"neutral"}async function Zm(t){await ht(t,"researchRuns")}const Ta=new Set(["queued","seeding","probing"]);function eh({projectName:t}){const[s,n]=o.useState("find");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:"Query discovery"}),e.jsx("h2",{children:"Discover or research queries"})]})}),e.jsxs("div",{className:"inline-flex rounded-md border border-default bg-surface p-1",role:"tablist","aria-label":"Query discovery workflow",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":s==="find",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="find"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("find"),children:"Find queries"}),e.jsx("button",{type:"button",role:"tab","aria-selected":s==="research",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="research"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("research"),children:"Research queries"})]}),e.jsx("div",{className:"mt-4",children:s==="find"?e.jsx(th,{projectName:t}):e.jsx(Km,{projectName:t})})]})}function th({projectName:t}){const s=bs(),[n,a]=o.useState(null),[i,r]=o.useState(""),[l,m]=o.useState("100"),c=Re({...Il({client:V,path:{name:t},query:{limit:"10"}}),refetchInterval:p=>p.state.data?.some(C=>Ta.has(C.status))?3e3:!1}),h=c.data??[];o.useEffect(()=>{!n&&h[0]&&a(h[0].id)},[n,h]);const x=h.find(p=>p.id===n)??null,d=Re({...Rl({client:V,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:x&&Ta.has(x.status)?3e3:!1}),j=d.data??null,S=Re({...$l({client:V,path:{name:t,id:n??""}}),enabled:!!(n&&x?.status==="completed")}),b=Ft({mutationFn:()=>{const p={},w=i.trim();w&&(p.icpDescription=w);const C=Number.parseInt(l,10);return Number.isFinite(C)&&C>0&&(p.maxProbes=C),Tl(t,p)},onSuccess:async p=>{a(p.sessionId),r(""),await Di(s,t,p.sessionId),Ce({title:"Discovery started",detail:`Run ${ha(p.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${p.sessionId}`,dedupeMode:"replace"})},onError:p=>{Ce({title:"Discovery failed to start",detail:p instanceof Error?p.message:"Could not start discovery.",tone:"negative"})}}),v=Ft({mutationFn:p=>{if(!n)throw new Error("Select a completed discovery session first.");return Ll(t,n,p)},onSuccess:async p=>{await Di(s,t,p.sessionId),s.invalidateQueries({queryKey:Nr({client:V})}),s.invalidateQueries({predicate:w=>Array.isArray(w.queryKey)&&w.queryKey[0]==="projects"&&w.queryKey.length>1}),Ce({title:"Queries added",detail:ih(p),tone:"positive",dedupeKey:`discovery:promote:${p.sessionId}`,dedupeMode:"replace"})},onError:p=>{Ce({title:"Could not add queries",detail:p instanceof Error?p.message:"Could not add queries from this run.",tone:"negative"})}}),g=j??x,R=S.data??null,_=(R?.queriesByBucket.cited.length??0)+(R?.queriesByBucket.aspirational.length??0),B=o.useMemo(()=>(j?.probes??[]).slice(0,30),[j?.probes]);async function y(){try{const p=await c.refetch();if(p.error)throw p.error;const w=p.data?.length??0;Ce({title:"Discovery sessions refreshed",detail:`${w} recent session${w===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(p){Ce({title:"Discovery refresh failed",detail:p instanceof Error?p.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:ne()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:c.isFetching,onClick:()=>{y()},children:[e.jsx(Un,{className:`size-3.5 ${c.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(pe,{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(de,{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:i,onChange:p=>r(p.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:l,onChange:p=>m(p.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."})]}),!ne()&&e.jsxs(Qe,{type:"button",size:"sm",disabled:b.isPending,onClick:()=>b.mutate(),children:[e.jsx(Vn,{size:14}),b.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(pe,{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"})]}),c.isFetching&&e.jsx(de,{tone:"neutral",children:"Loading"})]}),h.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:h.map(p=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===p.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(p.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:ha(p.id)}),e.jsx(de,{tone:Mi(p.status),children:p.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",p.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",p.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",p.wastedCount??0]})]})]},p.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pe,{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:g?ha(g.id):"No run selected"})]}),g&&e.jsx(de,{tone:Mi(g.status),children:g.status})]}),g?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(hs,{label:"Questions tested",value:g.probeCount??0}),e.jsx(hs,{label:"Cited queries",value:g.citedCount??0,tone:"positive"}),e.jsx(hs,{label:"Worth tracking",value:g.aspirationalCount??0,tone:"caution"}),e.jsx(hs,{label:"Skip",value:g.wastedCount??0,tone:"negative"})]}),g.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:g.error}),g.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:g.warning}),g.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:g.icpDescription})]}),g.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:g.competitorMap.slice(0,8).map(p=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[p.domain," ",e.jsx("span",{className:"text-muted",children:p.hits})]},p.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),g?.status==="completed"&&e.jsxs(pe,{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 2"}),e.jsx("h3",{children:"Choose queries to track"})]}),!ne()&&e.jsxs(Qe,{type:"button",size:"sm",disabled:v.isPending||_===0,onClick:()=>v.mutate(void 0),children:[e.jsx(Ar,{size:14}),v.isPending?"Adding…":"Add recommended queries"]})]}),S.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):R?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(hs,{label:"Queries to add",value:_,tone:"positive"}),e.jsx(hs,{label:"Cited queries",value:R.queriesByBucket.cited.length,tone:"positive"}),e.jsx(hs,{label:"Worth tracking",value:R.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(hs,{label:"Skip",value:R.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Adds Cited queries and Worth tracking queries, plus recurring competitor sites. Skip items remain available for review only."}),R.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-secondary",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:R.suggestedCompetitors.map(p=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[p.domain," ",e.jsx("span",{className:"text-muted",children:p.hits})]},p.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(pe,{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"})]}),d.isFetching&&e.jsx(de,{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("tbody",{children:B.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:p.query}),e.jsx("td",{children:e.jsx(de,{tone:sh(p.bucket),children:ah(p.bucket)})}),e.jsx("td",{className:"text-secondary",children:p.citedDomains.length>0?p.citedDomains.slice(0,3).join(", "):"-"})]},p.id))})]})})]})]})]})]})}function hs({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 Mi(t){return t==="completed"?"positive":t==="failed"?"negative":Ta.has(t)?"caution":"neutral"}function sh(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const nh={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function ah(t){return t?nh[t]:"Not classified"}function ha(t){return t.length>8?t.slice(0,8):t}function ih(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,a=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${a>0?`; ${a} already tracked`:""}.`}async function Di(t,s,n){await Promise.all([ht(t,"discovery"),t.invalidateQueries({queryKey:Ml({client:V})})])}function Ei(t){return`${(t*100).toFixed(1)}%`}function rh({projectName:t}){const[s,n]=o.useState("changes"),[a,i]=o.useState(null),[r,l]=o.useState(null),m=Re({...Dl({client:V,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=Re({...El({client:V,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(c.data??[]).filter(g=>(g.status==="completed"||g.status==="partial")&&g.trigger!=="probe").reverse(),x=r??h[0]?.id??"",d=a??h.find(g=>g.id!==x)?.id??"",j=!!(d&&x&&d!==x),S=Re({...ql({client:V,path:{name:t},query:{run1:d,run2:x}}),enabled:s==="compare"&&j}),b=m.data??[],v=S.data?.diff.filter(g=>g.changed||g.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(([g,R])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===g,className:`filter-chip ${s===g?"filter-chip-active":""}`,onClick:()=>n(g),children:R},g))}),s==="changes"?e.jsx(Ud,{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."})]}),m.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!m.isLoading&&b.length===0?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:"Complete an answer visibility sweep to create the first snapshot."})]}):null,b.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:b.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(g.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[g.mentionedPairs,"/",g.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Ei(g.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[g.citedPairs,"/",g.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Ei(g.overallCitedRate)})]},g.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:d,onChange:g=>i(g.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(g=>e.jsx("option",{value:g.id,children:new Date(g.createdAt).toLocaleString()},g.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:x,onChange:g=>l(g.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(g=>e.jsx("option",{value:g.id,children:new Date(g.createdAt).toLocaleString()},g.id))})]})]}),c.isLoading||S.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!c.isLoading&&h.length<2?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:"Run another answer visibility sweep before comparing historical evidence."})]}):null,S.data&&v.length===0?e.jsxs(pe,{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,v.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:v.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:g.query??"Archived query"}),e.jsx("td",{children:e.jsxs(de,{tone:g.changed?"caution":"neutral",children:[g.run1State??"none"," → ",g.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(de,{tone:g.visibilityChanged?"caution":"neutral",children:[g.run1MentionState??"none"," → ",g.run2MentionState??"none"]})})]},g.queryId??g.query??"unknown"))})]})}):null]}):null]})}const qi={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},oh={contract:null,assessment:null,googleAds:qi,gtm:qi,snapshots:[]};function lh(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":uh(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function ch(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 dh(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"&&mh(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 uh(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function mh(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function hh(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 xh(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 ph(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 Ns(t){return t.length<=12?t:`…${t.slice(-10)}`}function gh(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 fh(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 xa={"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 Gi(t){return t.outcome==="pass"?{label:xa[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:xa[t.code],tone:"negative",outcome:"Fail"}:{label:xa[t.code],tone:"caution",outcome:"Unknown"}}function bh(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function vh(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 yh(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function Oi({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:i}){const r=hh(s.state),l=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(de,{tone:r.tone,children:r.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}),l?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:l}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Tt(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(Qe,{type:"button",variant:"outline",size:"sm",disabled:i,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}function jh({workspace:t=oh,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:i=[],selectedContractId:r=null,onSelectContract:l,contractError:m=null,onRetryContracts:c,onRetryEvidence:h,onChangeGoogleAdsSelection:x,onChangeGtmSelection:d,onAddContract:j}){const S=lh(t),b=ch(S),v=dh(t),g=t.assessment?.findings??[],R=g.filter(y=>y.outcome!=="pass"),_=g.filter(y=>y.outcome==="pass"),B=R.some(y=>y.outcome==="fail")?"negative":"caution";return 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(de,{tone:b.tone,children:b.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Tt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:b.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(y=>e.jsxs("li",{className:"break-words",children:[yh(y)," ",y.kind,", captured ",Tt(y.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",y.id,")"]})]},y.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?v.id==="review-findings"||v.id==="review-runtime-verification"||v.id==="retry-connection-status"||v.id==="select-contract"||v.id==="retry-integrity"||v.id==="waiting-for-integrity"?e.jsx(A,{type:"button",disabled:n||v.id==="waiting-for-integrity",onClick:()=>s(v.id),children:n?"Working…":v.label}):e.jsx(Qe,{type:"button",disabled:n,onClick:()=>s(v.id),children:n?"Working…":v.label}):v.id==="review-findings"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):S==="runtime-unverified"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:v.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")})]}),i.length>0&&j?e.jsx(Qe,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:j,children:"Add conversion"}):null]}),i.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:r??"",onChange:y=>l?.(y.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),i.map(y=>e.jsx("option",{value:y.id,children:y.name},y.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:gh(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:fh(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:Ns(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:Ns(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:Ns(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:Ns(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."}),m?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:m}),c?e.jsx(A,{type:"button",variant:"outline",onClick:c,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),R.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(de,{tone:B,children:[R.length," ",R.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:R.map(y=>{const p=Gi(y);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:p.label}),e.jsx(de,{tone:p.tone,children:p.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",y.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",y.code]}),y.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",y.evidenceIds.join(", ")]}):null]},`${y.code}:${y.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(Ke,{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(y=>{const p=xh(y.key,S);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 ${p==="positive"?"bg-positive-fill":p==="caution"?"bg-caution-fill":p==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:y.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:y.detail}),e.jsx(de,{tone:p,children:ph(y.key,S)})]},y.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:[Oi({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:x}:{},actionPending:n}),Oi({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:d}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&h?e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:h,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:y.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:y.kind}),e.jsx("td",{className:"text-secondary",children:Tt(y.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:Ns(y.id)})]},y.id))})]})})]}):null,_.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[_.length," ",_.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:_.map(y=>{const p=Gi(y);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:p.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",y.code]}),y.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",y.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(de,{tone:p.tone,children:p.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:y.subject})]},`${y.code}:${y.subject}`)})})]})})]}):null,S==="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 ",bh(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:Ns(t.contract.gtm.tagId)})," fires with ",vh(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:Ns(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const Es=3e4,Fi={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Et="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",qt="text-sm font-medium text-secondary";function _i(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:ut(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function In(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function Nh(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 i=t.connection.selection.customerId;return i?{state:"stale",selection:`Selected customer ${i}`,...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 wh(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:a.workspaceId?"Selected account, container, and draft workspace":"Selected account and container",...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 Sh(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:In(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:In(t.triggerIds),variableIds:In(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:In(t.productionHosts)}}}function Bi(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 Rn(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 $n(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Tn({id:t,label:s,value:n,onChange:a,children:i,disabled:r=!1}){return e.jsxs("label",{htmlFor:t,className:qt,children:[s,e.jsx("select",{id:t,className:Et,value:n,onChange:l=>a(l.target.value),disabled:r,children:i})]})}function qs({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:i=>n(i.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function Ch({projectId:t,projectName:s}){const n=wr(),[a,i]=o.useState(null),[r,l]=o.useState(null),[m,c]=o.useState(!1),[h,x]=o.useState(""),[d,j]=o.useState(null),[S,b]=o.useState(!1),[v,g]=o.useState(!1),[R,_]=o.useState(""),[B,y]=o.useState(""),[p,w]=o.useState(""),[C,Y]=o.useState(""),[K,I]=o.useState(""),[L,U]=o.useState(!1),[T,H]=o.useState(Fi),[fe,xe]=o.useState(null),Q=o.useRef(null),ie=Re({...Gl({client:V,path:{name:s}}),staleTime:Es}),oe=Re({...Ol({client:V,path:{name:s}}),staleTime:Es}),z=Re({...Fl({client:V,path:{name:s}}),staleTime:Es}),q=Re({..._l({client:V,path:{name:s},query:{limit:5}}),staleTime:Es}),N=Re({...Bl({client:V,path:{name:s},query:{limit:5}}),staleTime:Es}),se=z.data??[],re=(fe?se.find(f=>f.id===fe)??null:null)??(se.length===1?se[0]??null:null),le=se.length>1&&!re,X=Re({...Ul({client:V,path:{name:s,contractId:re?.id??""}}),enabled:!!re,staleTime:Es}),D=Re({...Vl({client:V,path:{name:s}}),enabled:d==="google-ads"&&ie.data?.connected===!0,staleTime:0}),Z=Re({...zl({client:V,path:{name:s}}),enabled:d==="gtm"&&oe.data?.connected===!0,staleTime:0}),he=Re({...Kl({client:V,path:{name:s,accountId:p}}),enabled:d==="gtm"&&!!p,staleTime:0}),$e=Re({...Ql({client:V,path:{name:s,accountId:p,containerId:C}}),enabled:d==="gtm"&&!!p&&!!C,staleTime:0}),st=Ft(Hl({client:V})),lt=Ft(Wl({client:V})),Fe=Ft(Yl({client:V})),ee=Ft(Xl({client:V})),Be=Ft(Jl({client:V})),Ve=Ft(Zl({client:V})),ke=Ft(ec({client:V}));o.useEffect(()=>{if(d!=="google-ads"||S||!ie.isSuccess)return;const f=ie.data.connection?.selection;_(f?.customerId??""),y(f?.loginCustomerId??""),b(!0)},[S,ie.data,ie.isSuccess,d]),o.useEffect(()=>{if(d!=="gtm"||v||!oe.isSuccess)return;const f=oe.data.selection;w(f?.accountId??""),Y(f?.containerId??""),I(f?.workspaceId??""),g(!0)},[v,oe.data,oe.isSuccess,d]),o.useEffect(()=>{!fe||!z.data||z.data.some(f=>f.id===fe)||xe(null)},[z.data,fe]);const Je=o.useMemo(()=>{const f=q.data?.snapshots??[],G=N.data?.snapshots??[],J=[...f.map(Pt=>({id:Pt.id,provider:"google-ads",kind:Pt.kind,capturedAt:Pt.capturedAt})),...G.map(Pt=>({id:Pt.id,provider:"gtm",kind:Pt.kind,capturedAt:Pt.capturedAt}))].sort((Pt,$t)=>$t.capturedAt.localeCompare(Pt.capturedAt)).slice(0,5),Se=[],ft=X.data?.googleAdsSnapshot,ot=X.data?.gtmSnapshot;return ft&&Se.push({id:ft.id,provider:"google-ads",kind:ft.kind,capturedAt:ft.capturedAt}),ot&&Se.push({id:ot.id,provider:"gtm",kind:ot.kind,capturedAt:ot.capturedAt}),{contract:X.data?.assessment.contract??re,assessment:X.data?.assessment??null,contractSelectionRequired:le,assessmentState:re?X.isError?"unavailable":X.isLoading?"loading":void 0:void 0,assessmentError:X.isError?ut(X.error):null,googleAds:Nh(ie.data,_i(q.data?.total??0,q.isLoading,q.isError,q.error),ie.isError),gtm:wh(oe.data,_i(N.data?.total??0,N.isLoading,N.isError,N.error),oe.isError),snapshots:J,assessmentEvidenceSnapshots:Se}},[re,le,q.data,q.error,q.isError,q.isLoading,ie.data,ie.isError,N.data,N.error,N.isError,N.isLoading,oe.data,oe.isError,X.data,X.error,X.isError,X.isLoading]),Ae=o.useSyncExternalStore(br,Fn,Fn),we=Object.values(Ae.runs).some(f=>f.projectId===t&&(f.kind===Ts["google-ads-sync"]||f.kind===Ts["gtm-sync"])),O=st.isPending||lt.isPending||Fe.isPending||ee.isPending||Be.isPending||Ve.isPending||ke.isPending||we;async function $(){await Promise.all([ie.refetch(),oe.refetch(),z.refetch(),q.refetch(),N.refetch(),re?X.refetch():Promise.resolve()])}function M(){const f=document.activeElement;Q.current=f instanceof HTMLElement?f:null}function ye(f){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(f);return}globalThis.setTimeout(f,0)}function De(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function te(f){if(!f)return;!f.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!f.hasAttribute("tabindex")&&(f.tabIndex=-1),f.focus({preventScroll:!0})}function Ge(f,G=f){const J=document.getElementById(f);J instanceof HTMLDetailsElement&&(J.open=!0);const Se=J?.scrollIntoView;typeof Se=="function"&&Se.call(J,{behavior:De()?"auto":"smooth",block:"start"}),te(document.getElementById(G)??J)}function He(f,G){M(),ye(()=>Ge(f,G))}function Ze(){const f=Q.current;Q.current=null,f&&ye(()=>{f.isConnected&&f.focus({preventScroll:!0})})}function Pe(){i(null),c(!1),Ze()}function Oe(){i(null),j(null),Ze()}function dt(){i(null),U(!1),Ze()}function ze(){i(null),j(null),c(!0),He("google-ads-connect-panel","google-ads-connect-title")}function et(){i(null),_(""),y(""),b(!1),j("google-ads"),c(!1),He("google-ads-selection-panel","google-ads-selection-title")}function Ie(){i(null),w(""),Y(""),I(""),g(!1),j("gtm"),c(!1),He("gtm-selection-panel","gtm-selection-title")}function wt(){i(null),U(!0),He("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function xt(f,G){fr({id:f.id,projectId:f.projectId,kind:f.kind,projectLabel:s,sourceAction:G}),Ce({title:G==="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:${f.id}`,dedupeMode:"replace"})}async function Le(){us(n),i(null);try{const f=await st.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});x(""),c(!1),l("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Bi(f.authorizationUrl,()=>{$(),l(null),Ze()})}catch(f){i(ut(f))}}async function Me(){us(n),i(null);try{const f=await lt.mutateAsync({path:{name:s},body:{provider:"gtm"}});l("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),Bi(f.authorizationUrl,()=>{$(),l(null),Ze()})}catch(f){i(ut(f))}}async function ct(){if(us(n),!R){i("Select a Google Ads customer before saving.");return}i(null);try{await Fe.mutateAsync({path:{name:s},body:{customerId:R,...B.trim()?{loginCustomerId:B.trim()}:{}}}),j(null),Ze(),await $()}catch(f){i(ut(f))}}async function _e(){if(us(n),!p||!C){i("Select a Tag Manager account and container before saving.");return}i(null);try{await ee.mutateAsync({path:{name:s},body:{accountId:p,containerId:C,...K?{workspaceId:K}:{}}}),j(null),Ze(),await $()}catch(f){i(ut(f))}}async function Gt(){us(n),i(null);try{const f=await Be.mutateAsync({path:{name:s}});xt(f,"google-ads-sync")}catch(f){i(ut(f))}}async function St(){us(n),i(null);try{const f=await Ve.mutateAsync({path:{name:s}});xt(f,"gtm-sync")}catch(f){i(ut(f))}}async function pt(){us(n),i(null);try{const f=await Promise.allSettled([Be.mutateAsync({path:{name:s}}),Ve.mutateAsync({path:{name:s}})]),[G,J]=f;G.status==="fulfilled"&&xt(G.value,"google-ads-sync"),J.status==="fulfilled"&&xt(J.value,"gtm-sync");const Se=f.find(ft=>ft.status==="rejected");if(Se?.status==="rejected")throw Se.reason}catch(f){i(ut(f))}}async function at(){us(n);const f=ie.data?.connection?.selection.customerId,G=oe.data?.selection;if(!f||!G?.accountId||!G.containerId){i("Select Google Ads and Tag Manager resources before declaring a conversion.");return}i(null);try{const J=await ke.mutateAsync({path:{name:s},body:Sh(T,f,{accountId:G.accountId,containerId:G.containerId})});H(Fi),U(!1),Ze(),(await z.refetch()).data?.some(ft=>ft.id===J.id)&&xe(J.id)}catch(J){i(ut(J))}}function F(f){switch(f){case"connect-google-ads":ze();return;case"connect-gtm":M(),Me();return;case"select-google-ads":et();return;case"select-gtm":Ie();return;case"sync-google-ads":Gt();return;case"sync-gtm":St();return;case"sync-static-evidence":pt();return;case"declare-contract":wt();return;case"review-findings":He("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":He("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":$();return;case"select-contract":He("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":X.refetch();return;case"waiting-for-integrity":return}}const je=D.data?.customers??[],me=Z.data?.accounts??[],ve=he.data?.containers??[],jt=$e.data?.workspaces??[],Lt=!!R&&!je.some(f=>f.customerId===R),it=!!p&&!me.some(f=>f.id===p),Ct=!!C&&!ve.some(f=>f.id===C),zt=!!K&&!jt.some(f=>f.id===K),Kt=Lt&&D.isSuccess&&D.data.truncated===!1,kt=it&&Z.isSuccess&&Z.data.truncated===!1,Qt=Ct&&he.isSuccess&&he.data.truncated===!1,Xe=zt&&$e.isSuccess&&$e.data.truncated===!1,vs=kt||Qt||Xe,Nt=kt?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Qt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":Xe?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,ys=$n(Kt,D.data,D.isError),Ht=$n(kt,Z.data,Z.isError),rs=$n(Qt,he.data,he.isError),Jt=$n(Xe,$e.data,$e.isError),tt=D.isError?ut(D.error):null,os=Z.isError?ut(Z.error):he.isError?ut(he.error):$e.isError?ut($e.error):null,At=d==="google-ads"?tt:d==="gtm"?os:null,gt=Rn("customer",D.data,je.length),Zt=Rn("account",Z.data,me.length),rt=Rn("container",he.data,ve.length),Ut=Rn("draft workspace",$e.data,jt.length),k=Z.isError||he.isError||$e.isError&&!!K,be=m||d!==null||L;function Ne(){D.refetch()}function P(){if(Z.isError){Z.refetch();return}if(he.isError){he.refetch();return}$e.isError&&$e.refetch()}return ie.isLoading||oe.isLoading||z.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(f=>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"})]},f))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):z.isError&&!z.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: ",ut(z.error)]}),e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{z.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(jh,{workspace:Je,onPrimaryAction:F,actionPending:O,actionError:be?null:a,contracts:se,selectedContractId:re?.id??null,onSelectContract:f=>xe(f||null),contractError:z.isError?ut(z.error):null,onRetryContracts:()=>{z.refetch()},onRetryEvidence:()=>{Promise.all([q.refetch(),N.refetch()])},onChangeGoogleAdsSelection:et,onChangeGtmSelection:Ie,onAddContract:()=>F("declare-contract")}),r?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:r}):null,m?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:Te(async f=>{f.preventDefault(),await Le()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:qt,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:f=>x(f.target.value),className:Et,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(Qe,{type:"submit",disabled:st.isPending,children:st.isPending?"Starting…":"Continue to Google"}),e.jsx(A,{type:"button",variant:"outline",onClick:Pe,children:"Cancel"})]})]})]}):null,d==="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"})]})}),At?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:At}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:Ne,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Kt?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(Tn,{id:"google-ads-customer",label:"Customer account",value:R,onChange:f=>{b(!0),_(f);const G=je.find(J=>J.customerId===f);y(G?.parentCustomerId??"")},disabled:D.isLoading,children:[e.jsx("option",{value:"",children:D.isLoading?"Loading accessible customers…":"Select a customer"}),Lt?e.jsxs("option",{value:R,disabled:Kt,children:["Saved customer ",R," (",ys,")"]}):null,je.map(f=>e.jsx("option",{value:f.customerId,children:f.descriptiveName??`Customer ${f.customerId}`},f.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:qt,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Et,value:B,onChange:f=>{b(!0),y(f.target.value)},placeholder:"Use only when a manager context is required"})]})]}),gt?e.jsx("p",{role:"status",className:`mt-3 text-sm ${D.data?.truncated?"text-caution":"text-secondary"}`,children:gt}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Qe,{type:"button",disabled:Fe.isPending||D.isLoading||D.isError||Kt||!R,onClick:Te(ct),children:Fe.isPending?"Saving…":"Save customer selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:Oe,children:"Cancel"})]})]}):null,d==="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"})]})}),At?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:At}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:P,children:Z.isError?"Retry account list":he.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Nt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Nt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Tn,{id:"gtm-account",label:"Account",value:p,onChange:f=>{g(!0),f!==p&&(Y(""),I("")),w(f)},disabled:Z.isLoading,children:[e.jsx("option",{value:"",children:Z.isLoading?"Loading accounts…":"Select an account"}),it?e.jsxs("option",{value:p,disabled:kt,children:["Saved account ",p," (",Ht,")"]}):null,me.map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]}),e.jsxs(Tn,{id:"gtm-container",label:"Container",value:C,onChange:f=>{g(!0),f!==C&&I(""),Y(f)},disabled:!p||he.isLoading,children:[e.jsx("option",{value:"",children:he.isLoading?"Loading containers…":"Select a container"}),Ct?e.jsxs("option",{value:C,disabled:Qt,children:["Saved container ",C," (",rs,")"]}):null,ve.map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]}),e.jsxs(Tn,{id:"gtm-workspace",label:"Draft workspace (optional)",value:K,onChange:f=>{g(!0),I(f)},disabled:!C||$e.isLoading,children:[e.jsx("option",{value:"",children:$e.isLoading?"Loading workspaces…":"No draft workspace"}),zt?e.jsxs("option",{value:K,disabled:Xe,children:["Saved draft workspace ",K," (",Jt,")"]}):null,jt.map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[Zt?e.jsx("p",{role:"status",className:Z.data?.truncated?"text-caution":"text-secondary",children:Zt}):null,rt?e.jsx("p",{role:"status",className:he.data?.truncated?"text-caution":"text-secondary",children:rt}):null,Ut?e.jsx("p",{role:"status",className:$e.data?.truncated?"text-caution":"text-secondary",children:Ut}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Qe,{type:"button",disabled:ee.isPending||Z.isLoading||he.isLoading||$e.isLoading&&!!K||k||vs||!p||!C,onClick:Te(_e),children:ee.isPending?"Saving…":"Save container selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:Oe,children:"Cancel"})]})]}):null,L?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:Te(async f=>{f.preventDefault(),await at()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:qt,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Et,value:T.name,onChange:f=>H(G=>({...G,name:f.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:qt,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Et,value:T.eventName,onChange:f=>H(G=>({...G,eventName:f.target.value})),placeholder:"booking_complete"})]}),e.jsxs("label",{htmlFor:"contract-conversion-action",className:qt,children:["Google Ads conversion action ID",e.jsx("input",{id:"contract-conversion-action",required:!0,className:Et,value:T.conversionActionId,onChange:f=>H(G=>({...G,conversionActionId:f.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-gtm-tag",className:qt,children:["Tag Manager tag ID",e.jsx("input",{id:"contract-gtm-tag",required:!0,className:Et,value:T.tagId,onChange:f=>H(G=>({...G,tagId:f.target.value}))})]})]}),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:qt,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Et,value:T.conversionId,onChange:f=>H(G=>({...G,conversionId:f.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:qt,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Et,value:T.conversionLabel,onChange:f=>H(G=>({...G,conversionLabel:f.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:qt,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Et,value:T.triggerIds,onChange:f=>H(G=>({...G,triggerIds:f.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:qt,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Et,value:T.variableIds,onChange:f=>H(G=>({...G,variableIds:f.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:qt,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Et,value:T.campaignIds,onChange:f=>H(G=>({...G,campaignIds:f.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:qt,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Et,value:T.productionHosts,onChange:f=>H(G=>({...G,productionHosts:f.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(qs,{id:"contract-primary-action",checked:T.requirePrimaryAction,onChange:f=>H(G=>({...G,requirePrimaryAction:f})),children:"Google Ads action is primary"}),e.jsx(qs,{id:"contract-biddable-goal",checked:T.requireBiddableGoal,onChange:f=>H(G=>({...G,requireBiddableGoal:f})),children:"Google Ads goal is biddable"}),e.jsx(qs,{id:"contract-runtime-verification",checked:T.verificationRequired,onChange:f=>H(G=>({...G,verificationRequired:f})),children:"Runtime proof is required"}),e.jsx(qs,{id:"contract-transaction-id",checked:T.requireTransactionId,onChange:f=>H(G=>({...G,requireTransactionId:f})),children:"Transaction ID is required"}),e.jsx(qs,{id:"contract-value",checked:T.requireValue,onChange:f=>H(G=>({...G,requireValue:f})),children:"Conversion value is required"}),e.jsx(qs,{id:"contract-currency",checked:T.requireCurrency,onChange:f=>H(G=>({...G,requireCurrency:f})),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(Qe,{type:"submit",disabled:ke.isPending,children:ke.isPending?"Saving…":"Save conversion contract"}),e.jsx(A,{type:"button",variant:"outline",onClick:dt,children:"Cancel"})]})]})]}):null]})}const pa=20,as=50,kh=50,Ah=50;function Fa(t){return t==="viewer"}function _a(t){return t?.status==="unavailable"}function to(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function so(t,s){const n=new Map(s.map(i=>[i.id,i.label])),a=t.map(i=>n.get(i)).filter(i=>!!i);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function Ln(t,s,n){if(t.kind==="all")return s.map(r=>r.id);if(t.kind==="specific")return s.filter(r=>t.propertyIds.includes(r.id)).map(r=>r.id);const a=new Set(t.groupIds),i=new Set(n.filter(r=>a.has(r.id)).flatMap(r=>r.propertyIds));return s.filter(r=>i.has(r.id)).map(r=>r.id)}function Ph(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(i=>s.find(r=>r.id===i)?.name).filter(i=>!!i);return a.length===0?"selected groups":a.join(" + ")}function ga(t,s){const n=new Set(s.map(i=>i.id)),a=t.propertyIds.filter(i=>n.has(i)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function Ui(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Vi(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 Mn(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 La(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function fa(t){return La(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function Ma({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:i=!0}){const[r,l]=o.useState(""),[m,c]=o.useState(!1),h=r.trim().toLocaleLowerCase(),x=h?t.filter(b=>b.label.toLocaleLowerCase().includes(h)):t,d=m?x:x.slice(0,kh),j=d.length<x.length;function S(){const b=new Set([...s,...d.map(v=>v.id)]);n(t.filter(v=>b.has(v.id)).map(v=>v.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:r,onChange:b=>l(b.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),i?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:d.length===0,onClick:S,children:"Select all shown"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),x.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 ",d.length," of ",x.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:d.map(b=>{const v=s.includes(b.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 ${b.label}`,checked:v,type:"checkbox",onChange:g=>n(to(s,b.id,g.currentTarget.checked))}),e.jsx("span",{children:b.label})]}),b.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[b.urlCount," URLs"]})]},b.id)})}),j?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>c(!0),children:"Show all Properties"}):null]})]})}function Ba(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(de,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Ua({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(de,{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 Ih({value:t}){const[s,n]=o.useState(0),[a,i]=o.useState(0),[r,l]=o.useState(null),m=t.preview,c=m?.counts.needsAttention??0,h=m?.rows.filter(C=>C.status==="matched")??[],x=m?.rows??[],d=x.filter(C=>C.status!=="matched"),j=Math.max(1,Math.ceil(x.length/as)),S=Math.min(s,j-1),b=x.slice(S*as,(S+1)*as),v=Math.max(1,Math.ceil(d.length/as)),g=Math.min(a,v-1),R=d.slice(g*as,(g+1)*as),_=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,B=h.length>0&&!t.isApplying,y=m!==null&&r===m.previewChecksum,p=d.length>0&&g===v-1;o.useEffect(()=>{n(0),i(0),l(null)},[m?.previewChecksum]);async function w(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=>{w(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
4
+ Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!_,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]}),m?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:[m.counts.matchedRows," matched · ",m.counts.groupsReady," group",m.counts.groupsReady===1?"":"s"," ready",c>0?` · ${c} need${c===1?"s":""} attention`:""]}),m.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:m.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,m.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 (",m.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:b.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(de,{tone:Ui(C.status),children:Vi(C.status)}),Mn(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Mn(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 ",S+1," of ",j," · ",m.rows.length," rows"]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:S===0,onClick:()=>n(C=>Math.max(0,C-1)),children:"Previous 50 rows"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:S===j-1,onClick:()=>n(C=>Math.min(j-1,C+1)),children:"Next 50 rows"})]})]}):null,c>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",c," row",c===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:R.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(de,{tone:Ui(C.status),children:Vi(C.status)}),Mn(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Mn(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 ",g+1," of ",v]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:g===0,onClick:()=>i(C=>Math.max(0,C-1)),children:"Previous 50 exceptions"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:g===v-1,onClick:()=>i(C=>Math.min(v-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:y,disabled:t.isApplying||!p,onChange:C=>l(C.currentTarget.checked?m.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",c," row",c===1?"":"s"," will be skipped."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!B||!y,onClick:()=>{t.onApply(h.map(C=>C.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(A,{type:"button",className:"mt-3 min-h-11",disabled:!B,onClick:()=>{t.onApply(h.map(C=>C.dataRow))},children:t.isApplying?"Creating groups…":`Create ${m.counts.groupsReady} group${m.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const Rh="—";function $h({access:t,availability:s,properties:n,queries:a,selectedQueryIds:i,isApplying:r=!1,isBusy:l=!1,canContinue:m=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:h,onClearQueryAssignments:x,onRemoveQuery:d,onCreateQueries:j,onCreateAndPairQuestions:S,isCreatingQueries:b=!1,createQueriesError:v=null,onManageProjectQueries:g,groups:R,audience:_,onAudienceChange:B,assignmentImpact:y=null,isPreviewingAssignmentImpact:p=!1,assignmentImpactError:w=null,onRetryAssignmentImpact:C,assignmentNotice:Y=null,onReplaceAssignments:K,isReplacingAssignments:I=!1,onBack:L,onContinue:U}){const[T,H]=o.useState(""),[fe,xe]=o.useState(!1),[Q,ie]=o.useState(!1),[oe,z]=o.useState(""),[q,N]=o.useState(""),[se,ue]=o.useState(null);if(_a(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Ua,{message:s.message})});const re=Fa(t),le=_,X=B,D=Ln(le,n,R),Z=D.length,he=Z>0&&i.length>0&&!r&&!l&&!p&&y!==null&&w===null,$e=x??d,st=T.trim().toLocaleLowerCase(),lt=st?a.filter(M=>fa(M).toLocaleLowerCase().includes(st)):a,Fe=lt.filter(M=>(M.propertyIds?.length??0)===0),ee=Q?Fe:lt,Be=fe?ee:ee.slice(0,Ah),Ve=Be.filter(M=>!La(M)),ke=[...new Set(oe.split(`
5
+ `).map(M=>M.trim()).filter(Boolean))],Je=[...q.matchAll(/\{([a-z][\w-]*)\}/gi)].map(M=>M[1]),Ae=n.filter(M=>D.includes(M.id)),we=Je.length===0||q.trim()===""?[]:Ae.map(M=>({propertyId:M.id,text:Je.reduce((ye,De)=>ye.replaceAll(`{${De}}`,M.label),q.trim())})),O=[...new Set(we.map(M=>M.text))];function $(){const M=new Set([...i,...Ve.map(ye=>ye.id)]);c(a.filter(ye=>M.has(ye.id)).map(ye=>ye.id))}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-queries-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-queries-title",children:"Queries"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose queries, then apply them to Properties."})]})}),re?e.jsx(Ba,{}):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:M=>{const ye=M.currentTarget.value;ye==="all"?X({kind:"all"}):ye==="specific"?X({kind:"specific",propertyIds:[]}):ye.startsWith("group:")&&X({kind:"groups",groupIds:[ye.slice(6)]})},className:"block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsxs("option",{value:"all",children:["All Properties · ",n.length]}),R.length>0?e.jsx("optgroup",{label:"Groups",children:R.map(M=>{const ye=Ln({kind:"groups",groupIds:[M.id]},n,R).length;return e.jsx("option",{value:`group:${M.id}`,disabled:ye===0,children:ga(M,n)},M.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(M=>{const ye=R.find(De=>De.id===M);return ye?e.jsxs("span",{className:"inline-flex min-h-11 items-center gap-1 rounded-md border border-default bg-surface px-2 text-sm text-primary",children:[ga(ye,n),e.jsx("button",{type:"button","aria-label":`Remove ${ye.name}`,className:"-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>{const De=le.groupIds.filter(te=>te!==ye.id);X(De.length>0?{kind:"groups",groupIds:De}:{kind:"all"})},children:"×"})]},ye.id):null})}),R.some(M=>!le.groupIds.includes(M.id)&&Ln({kind:"groups",groupIds:[M.id]},n,R).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:M=>{M.currentTarget.value&&X({kind:"groups",groupIds:[...le.groupIds,M.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"}),R.filter(M=>!le.groupIds.includes(M.id)).map(M=>{const ye=Ln({kind:"groups",groupIds:[M.id]},n,R).length;return e.jsx("option",{value:M.id,disabled:ye===0,children:ga(M,n)},M.id)})]})]}):null,Z===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(Ma,{legend:"Specific Properties",properties:n,selectedPropertyIds:le.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:M=>{X({kind:"specific",propertyIds:M})}})}):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||!j?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:oe,onChange:M=>z(M.currentTarget.value),placeholder:`best apartments in dallas
6
+ luxury apartments atlanta
7
+ pet friendly apartments austin`}),v?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:v}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:ke.length===0||b||l,onClick:()=>{Promise.resolve(j(ke)).then(()=>z(""),()=>{})},children:b?"Adding…":`Add ${ke.length||""} ${ke.length===1?"query":"queries"}`.replace(" "," ")}),g?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:l,onClick:g,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:q,onChange:M=>N(M.target.value),placeholder:"apartments near {property}"}),q.trim()===""?null:Je.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."]}):Ae.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(M=>e.jsx("li",{className:"text-sm text-strong",children:M},M))}),O.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",O.length-3," more"]}):null]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:we.length===0||b||l||!S,onClick:()=>{S&&Promise.resolve(S(we)).then(()=>N(""),()=>{})},children:b?"Adding…":`Add ${we.length||""} ${we.length===1?"query":"queries"}`.replace(" "," ")}),we.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"," ",we.length," assignment",we.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(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:Ve.length===0,onClick:$,children:"Select all shown queries"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i.length===0,onClick:()=>c([]),children:"Clear query selection"}),e.jsx(A,{type:"button",size:"sm",className:"min-h-11",disabled:!he,onClick:()=>{h({queryIds:i,propertyIds:D,...le.kind==="groups"?{groupIds:le.groupIds}:{}})},children:r?"Assigning queries…":`Assign ${i.length||""} ${i.length===1?"query":"queries"} to ${Ph(le,R,Z)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[p?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,y?e.jsxs("p",{className:"text-sm text-secondary",children:[i.length," ",i.length===1?"query":"queries"," → ",y.assignmentCount," Property assignment",y.assignmentCount===1?"":"s"," · ",y.addedAssignments," new, ",y.alreadyPresentAssignments," already assigned"," · ",y.fullRunProviderCalls," provider request",y.fullRunProviderCalls===1?"":"s"," per full run"," · ",y.addedProviderCalls," new",le.kind==="groups"?` · ${y.resolvedPropertyCount} unique ${y.resolvedPropertyCount===1?"Property":"Properties"}${y.overlapCount>0?`, ${y.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):w?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:w}),C?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:C,children:"Retry impact"}):null,L?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:L,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[i.length," ",i.length===1?"query":"queries"," × ",Z," Properties = ",i.length*Z," assignments"]})]}),Y?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:Y}):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:T,onChange:M=>{H(M.currentTarget.value),xe(!1)},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400",placeholder:"Query text"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:["Showing ",Be.length," of ",ee.length," queries,"," ",lt.length-Fe.length," of ",lt.length," applied"]}),re||Fe.length===0?null:e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{ie(M=>!M),xe(!1)},children:Q?"Show all queries":`Show the ${Fe.length} not applied`})]})]}):null,Be.length>0?e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[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:Be.map(M=>{const ye=La(M),De=fa(M),te=i.includes(M.id),Ge=(M.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[re?null:ye?e.jsx("td",{"aria-hidden":"true"}):e.jsx("td",{className:"p-0",children:e.jsx("label",{className:"flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{"aria-label":`Select query ${De}`,checked:te,type:"checkbox",onChange:He=>c(to(i,M.id,He.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:De})}),e.jsx("td",{className:"text-secondary",children:so(M.propertyIds??[],n)}),re?null:e.jsx("td",{className:"text-right",children:Ge?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[K?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:l||I,onClick:()=>ue({queryId:M.id,propertyIds:[...M.propertyIds??[]]}),"aria-label":`Replace query assignments for ${De}`,children:"Replace assignments"}):null,e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:l,onClick:()=>{$e(M.id)},"aria-label":`Clear query assignments for ${De}`,children:"Clear assignments"})]}):null})]},M.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,re||!se?null:(()=>{const M=a.find(te=>te.id===se.queryId),ye=M?fa(M):"this query",De=se.propertyIds.filter(te=>n.some(Ge=>Ge.id===te));return e.jsxs("section",{"aria-labelledby":"advanced-measurement-replace-assignments-title",className:"border-y border-default py-4",children:[e.jsx("h4",{id:"advanced-measurement-replace-assignments-title",className:"text-sm font-medium text-heading",children:"Replace assigned Properties"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:["This replaces every Property assigned to “",ye,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(Ma,{legend:"Properties for this query",properties:n,selectedPropertyIds:De,onSelectedPropertyIdsChange:te=>ue(Ge=>Ge&&{...Ge,propertyIds:[...te]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:I||l,onClick:()=>ue(null),children:"Keep current assignments"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:De.length===0||I||l||!K,onClick:()=>{K&&Promise.resolve(K({queryId:se.queryId,propertyIds:De}))},children:I?"Replacing assignments…":`Replace with ${De.length} ${De.length===1?"Property":"Properties"}`})]})]})})(),Be.length<ee.length?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>xe(!0),children:"Show all queries"}):null,re?null:e.jsxs(e.Fragment,{children:[m?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 ${L?"justify-between":"justify-end"}`,children:[L?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",disabled:l,onClick:L,children:"Back"}):null,e.jsx(A,{type:"button",variant:he?"outline":"default",className:"min-h-11",disabled:!m||l,onClick:U,children:"Continue"})]})]})]})}function Th({access:t,availability:s,properties:n,groups:a,groupDraft:i,isSaving:r=!1,onGroupDraftChange:l,onSaveGroup:m,onEditGroup:c,onRemoveGroup:h,onClearGroupDraft:x,membershipImport:d,onBack:j,onContinue:S}){if(_a(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(Ua,{message:s.message})});const b=Fa(t),v=i.name.trim().length>0&&i.propertyIds.length>0&&!r,g=n.filter(y=>i.propertyIds.includes(y.id)).length,R=i.name.trim().length>0||i.propertyIds.length>0||i.competitorDomains.trim().length>0,_=!b&&(c!==void 0||h!==void 0);function B(){if(x){x();return}l({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."})]})}),b?e.jsx(Ba,{}):null,b||!d?null:e.jsx(Ih,{value:d}),b?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:i.name,onChange:y=>l({...i,name:y.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:[g," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(Ma,{legend:"Properties in this group",properties:n,selectedPropertyIds:i.propertyIds,onSelectedPropertyIdsChange:y=>l({...i,propertyIds:y})})})]}),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:i.competitorDomains,onChange:y=>l({...i,competitorDomains:y.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!v,onClick:()=>{m(i)},children:r?"Saving group…":"Save group"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!R,onClick:B,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."})]}),R?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"}),_?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:y.name}),e.jsx("td",{className:"text-secondary",children:so(y.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:y.competitors.length>0?y.competitors.join(", "):"None"}),_?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[c?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${y.name}`,onClick:()=>c(y),children:"Edit"}):null,h?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${y.name}`,onClick:()=>{h(y.id)},children:"Remove"}):null]})}):null]},y.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,b?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${j?"justify-between":"justify-end"}`,children:[j?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",onClick:j,children:"Back"}):null,e.jsx(A,{type:"button",className:"min-h-11",disabled:R,onClick:S,children:a.length===0&&!R?"Continue without groups":"Continue"})]})]})}function Lh({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:i,onBack:r,onReviewChanges:l,isReviewing:m=!1,canReviewChanges:c=!0,reviewedChanges:h,reviewChangesError:x,canPublish:d,isPublishing:j=!1,onPublish:S}){const[b,v]=o.useState(pa),[g,R]=o.useState(pa),[_,B]=o.useState(pa);if(_a(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(Ua,{message:s.message})});const y=Fa(t),p=i?.items??[],w=i?.coverageItems??[],C=p.slice(0,b),Y=w.slice(0,g),K=a.slice(0,_),I=l!==void 0,L=h!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),y?e.jsx(Ba,{}):null,i?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"}),i.exceptionCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[i.exceptionCount," sitemap ",i.exceptionCount===1?"entry needs":"entries need"," review."]}):null,i.coverageReviewCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[i.coverageReviewCount," ",i.coverageReviewCount===1?"Property has":"Properties have"," URL coverage changes."]}):null]}),i.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 (",i.exceptionCount,")"]}),p.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:C.map(U=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:U.url}),e.jsx("p",{className:"mt-1 text-secondary",children:U.reason})]},`${U.url}-${U.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 ",p.length]}),C.length<p.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>v(U=>U+as),children:"Show next 50 URLs"}):null]})]}):null,y?e.jsx("p",{className:"text-sm text-secondary",children:"An editor must finish this review before publishing."}):e.jsxs(e.Fragment,{children:[i.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 ",i.coverageReviewCount," changed ",i.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 (",i.coverageReviewCount,")"]}),Y.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[Y.map(U=>e.jsxs("section",{"aria-label":`${U.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:U.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:U.savedUrls.map(T=>e.jsx("li",{className:"break-all text-secondary",children:T},T))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),U.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:U.currentSitemapUrls.map(T=>e.jsx("li",{className:"break-all text-secondary",children:T},T))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},U.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",Y.length," of ",w.length]}),Y.length<w.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>R(U=>U+as),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:i.coverageResolution==="keep-existing",onChange:()=>i.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:i.coverageResolution==="replace-with-imported",onChange:()=>i.onCoverageResolutionChange("replace-with-imported")}),"Use current sitemap URLs"]})]}):null,e.jsx(A,{type:"button",className:"min-h-11",onClick:()=>{i.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??Rh})]})})]})}),n.providerCalls===void 0?e.jsx("p",{className:"supporting-copy",children:"Review changes to see how many provider requests one run will make."}):null,n.assignments!==void 0&&n.assignments>n.queries?e.jsxs("p",{className:"supporting-copy",children:[n.queries," ",n.queries===1?"query":"queries"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a query aimed at a market is measured on every Property in it."]}):null,h?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:h.title}),h.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:h.items.map((U,T)=>e.jsx("li",{children:U},`${U}-${T}`))}):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:K.map(U=>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:U.title}),U.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:U.detail}):null]}),e.jsx(de,{tone:U.tone??"caution",children:"Needs attention"})]},U.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",K.length," of ",a.length]}),K.length<a.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>B(U=>U+as),children:"Show next 50 exceptions"}):null]})]})]}),y?null:e.jsxs(e.Fragment,{children:[I&&x?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:x}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${r?"justify-between":"justify-end"}`,children:[r?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",onClick:r,children:"Back"}):null,l!==void 0&&!L?e.jsx(A,{type:"button",className:"min-h-11",disabled:m||!c,onClick:()=>{l()},children:m?"Reviewing changes…":"Review changes"}):e.jsx(A,{type:"button",className:"min-h-11",disabled:!d||j,onClick:()=>{S()},children:j?"Publishing setup…":"Publish setup"})]})]})]})}const Mh={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function Dh(t){return t.trim().toLocaleLowerCase()}function Eh(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function qh({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 Gh({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:i}){const r=!t||i==="reviewing",l=r||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function m(c,h){n({...s,[c]:h})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":i==="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(de,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:c=>{c.preventDefault(),!l&&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:r,onChange:c=>m("sitemapUrl",c.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:r,onChange:c=>m("examplePropertyUrl",c.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:r,onChange:c=>m("preferredHost",c.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:r,onChange:c=>m("propertyPathPattern",c.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:r,onChange:c=>m("additionalHost",c.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:r,onChange:c=>m("additionalPathPattern",c.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:r,onChange:c=>m("excludedPaths",c.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(A,{type:"submit",disabled:l,children:i==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function Oh({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:i,selectedPropertyIds:r,onSelectedPropertyIdsChange:l,onContinue:m,isContinuing:c=!1,onRetryProperties:h,onReturnToImport:x,maxVisibleProperties:d,onShowAllProperties:j}){const S=Dh(a),b=s.filter(K=>Eh(K,S)),v=Math.max(1,d??b.length),g=b.slice(0,v),R=new Set(r),_=s.filter(K=>R.has(K.id)).map(K=>K.id),B=g.length<b.length;function y(K){const I=new Set(K);l(s.filter(L=>I.has(L.id)).map(L=>L.id))}function p(K,I){if(!t||c)return;const L=new Set(_);I?L.add(K):L.delete(K),y(L)}function w(){!t||c||y([..._,...g.map(K=>K.id)])}function C(){!t||c||l([])}function Y(){!t||c||_.length===0||m(_)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||c,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(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:x,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:c,onChange:K=>i(K.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(A,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:w,children:"Select all shown"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:c||_.length===0,onClick:C,children:"Clear selection"})]}):null]}),b.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(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:x,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 ",g.length," of ",b.length," Properties"]}),e.jsxs("p",{children:[_.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:g.map(K=>{const I=Mh[K.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:K.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(qh,{property:K})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(de,{tone:I.tone,children:I.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 ${K.name}`,checked:_.includes(K.id),disabled:c,onChange:L=>p(K.id,L.target.checked),className:"size-6 accent-accent"})})}):null]},K.id)})})]})}),B&&j?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:c,onClick:j,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(A,{type:"button",variant:"ghost",disabled:c,onClick:x,children:"Back"}),e.jsx(A,{type:"button",disabled:c||_.length===0,onClick:Y,children:c?"Saving Properties…":"Continue"})]}):null]}):null]})}function Fh(t){return t.activeStep==="import"?e.jsx(Gh,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(Oh,{...t})}const _h=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function Bh({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:i,children:r}){const l=o.useRef(null),m=o.useRef(null),c=o.useRef(null),h=o.useRef(null),x=o.useRef(!1),[d,j]=o.useState(!1);return o.useEffect(()=>{s||j(!1)},[s]),o.useEffect(()=>{const S=x.current;x.current=d,d?c.current?.focus():S&&h.current?.focus()},[d]),o.useEffect(()=>{const S=l.current;if(l.current=t,S===null||S===t)return;const b=m.current?.querySelector('h1, h2, h3, [role="heading"]');b&&(b.tabIndex=-1,b.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(de,{tone:"caution",children:"Unpublished changes"}),n&&a?d?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(A,{ref:c,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>j(!1),children:"Keep editing"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(A,{ref:h,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>j(!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:_h.map(S=>e.jsx("li",{children:i?e.jsx("button",{type:"button","aria-current":t===S.id?"step":void 0,onClick:()=>i(S.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===S.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:S.label}):e.jsx("span",{"aria-current":t===S.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===S.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:S.label})},S.id))})}),e.jsx("div",{ref:m,children:r})]})}function Uh(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Fh,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx($h,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(Th,{...t.groups,access:s}):"review"in t?e.jsx(Lh,{...t.review,access:s}):null}function Dn(t){return e.jsx(Bh,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Uh(t)})}function no(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Rt(t){return{"If-Match":t,"Idempotency-Key":no()}}function ws(t){return t instanceof Ks&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function Ot(t,s){return t instanceof Ks?s:(t instanceof Error?t.message.trim():"")||s}function Vh(t){const s="Could not calculate assignment impact.";if(!(t instanceof Ks)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const zh={loadSetup:t=>nt(()=>Nc({client:V,path:{name:t}})),loadDraft:t=>nt(()=>jc({client:V,path:{name:t}})),createDraft:(t,s)=>nt(()=>yc({client:V,path:{name:t},headers:{"Idempotency-Key":no()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>nt(()=>vc({client:V,path:{name:t},headers:Rt(s),body:n})),applySitemapSelection:(t,s,n,a)=>nt(()=>bc({client:V,path:{name:t},headers:Rt(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>nt(()=>fc({client:V,path:{name:t},body:s})),applyAssignments:(t,s,n)=>nt(()=>gc({client:V,path:{name:t},headers:Rt(s),body:n})),replaceAssignments:(t,s,n)=>nt(()=>pc({client:V,path:{name:t},headers:Rt(s),body:n})),applyPairedAssignments:(t,s,n)=>nt(()=>xc({client:V,path:{name:t},headers:Rt(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>nt(()=>hc({client:V,path:{name:t},headers:Rt(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>nt(()=>mc({client:V,path:{name:t},headers:Rt(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>nt(()=>uc({client:V,path:{name:t},headers:Rt(s),body:{target:n}})),upsertGroup:(t,s,n)=>nt(()=>dc({client:V,path:{name:t},headers:Rt(s),body:{group:n}})),removeGroup:(t,s,n)=>nt(()=>cc({client:V,path:{name:t},headers:Rt(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>nt(()=>lc({client:V,path:{name:t},headers:Rt(s),body:n})),removeCompetitor:(t,s,n,a)=>nt(()=>oc({client:V,path:{name:t},headers:Rt(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>nt(()=>rc({client:V,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>nt(()=>ic({client:V,path:{name:t},headers:Rt(s),body:n})),compilePreview:t=>nt(()=>ac({client:V,path:{name:t}})),diffPreview:t=>nt(()=>nc({client:V,path:{name:t}})),publish:(t,s,n)=>nt(()=>sc({client:V,path:{name:t},headers:Rt(s),body:n})),discard:(t,s)=>nt(()=>tc({client:V,path:{name:t},headers:Rt(s)}))},zi={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},en={name:"",propertyIds:[],competitorDomains:""},Ki=50;function nn(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Kh(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 Qi(t){const s=t.propertyPathPattern.trim();if(s){const i=(s.startsWith("/")?s:`/${s}`).split("/").slice(1);if(i.filter(l=>l==="*"||l==="{slug}").length!==1||i.some(l=>l.includes("*")&&l!=="*"))throw new Error("Property URL pattern must contain exactly one * or {slug} segment.");return`/${i.map(l=>l==="*"?"{slug}":l).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 Qh(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const i=a.trim().replace(/\/+$/,"");if(!i)continue;const l=i.split("/").filter(Boolean).at(-1)??i,m=l.startsWith("*"),c=l.endsWith("*"),h=l.slice(m?1:0,c?-1:void 0).trim();if(!h)throw new Error("Ignored URL patterns must include text besides *.");const x=m&&c?"contains":m?"suffix":c?"prefix":"exact",d=`${x}:${h}`;n.has(d)||(n.add(d),s.push({kind:x,value:h}))}return s}function Hh(t){const s=Kh(t.sitemapUrl),n=t.examplePropertyUrl.trim()?nn(t.examplePropertyUrl):null,a=nn(t.preferredHost)??n??nn(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const i=nn(t.additionalHost),r=t.additionalHost.trim().length>0,l=t.additionalPathPattern.trim().length>0;if(r!==l||r&&!i)throw new Error("Add both an additional domain and its Property URL pattern.");const m=Qh(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:Qi(t)},...i?{aliases:[{host:i,pathTemplate:Qi({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...m.length>0?{excludedSlugPatterns:m}:{}}}}function Wh(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 Yh(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 Hi(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function Xh(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function ba(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function Da(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function Wi(t){return nn(t)}function ao(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 io(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 ro(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function oo(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Jh(t,s){const n=ao(t.authoring,s.path);if(!n)return;const a=s.path[2],i=s.path[3];if(a==="urlMatchers"&&typeof i=="number"){const r=n.urlMatchers[i];return r?`${n.label} — ${r}`:n.label}if(a==="aliases"&&typeof i=="number"){const r=n.aliases[i];return r?`${n.label} — ${r}`:n.label}return n.label}function Zh(t,s){const n=io(t.authoring,s.path);if(!n)return;const a=s.path[2],i=s.path[3];if(a==="competitors"&&typeof i=="number"){const r=n.competitors.at(i)?.domain;return r?`${n.label} — ${r}`:n.label}if(a==="targetKeys"&&typeof i=="number"){const r=oo(t.authoring,n.targetKeys[i]);return`${n.label} — ${r}`}return n.label}function ex(t,s){const n=ro(t.authoring,s.path);if(!n)return;const a=t.queries.find(i=>i.id===n.queryId)?.query??"an unavailable query";return`${oo(t.authoring,n.targetKey)} — ${a}`}function tx(t,s){return s.path[0]==="identities"?"Project domain":Jh(t,s)??Zh(t,s)??ex(t,s)}function Yi(t,s,n){const a=ro(t.authoring,s.path);if(!a)return;const i={...t.authoring?.defaultContext,...a.contextOverride},r=s.path.at(-1);if(n==="models"&&typeof r=="string")return i.models?.[r];if(n==="locations"&&typeof r=="number")return i.locations?.[r]}function sx(t,s){const n=tx(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,Yi(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,Yi(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 En(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function lo(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 nx(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${En(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${En(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${En(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${En(n,"item")} need review.`:s}})()}${lo(a)}`}function ax(t,s){const n=new Map;for(const a of t){const i=sx(a,s),r=[a.ruleId,a.severity,i.title,i.detail].join("\0"),l=n.get(r)??{ruleId:a.ruleId,severity:a.severity,meaning:i,paths:new Set,affected:new Set};l.paths.add(JSON.stringify(a.path)),i.affected&&l.affected.add(i.affected),n.set(r,l)}return[...n.values()].map((a,i)=>({id:`${a.ruleId}-${a.severity}-${i}`,title:a.meaning.title,detail:nx(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function va(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function ya(t,s,n){const a=ao(n,t.path),i=io(n,t.path),r=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,l=r?n?.targets.find(x=>x.stableKey===r):void 0,m=a?.label??i?.label,c=lo(m?[m]:[]),h={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...h,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${c}`};case"excluded-target-has-assignments":return{...h,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${c}`};case"group-unknown-target":return{...h,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${c}`};case"measurement.discovery.proposed_new_target":{const x=va(a)??"the proposed Property";return{...h,title:"Review a new Property",detail:`Review ${x}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const x=va(a)??"the proposed Property",d=l?.label??"an existing Property";return{...h,title:"Review a moved Property",detail:`Review ${x}. It may be the same Property as ${d}.`}}case"measurement.discovery.rebind_ambiguous":{const x=va(a)??"the proposed Property",d=l?.label??"an existing Property";return{...h,title:"Choose an existing Property",detail:`Review ${x}. It may match ${d}; choose the correct Property.`}}default:return{...h,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function ix(t,s=!1){const n=[],a=t.targets.added.length+t.targets.removed.length+t.targets.changed.length,i=t.groups.added.length+t.groups.removed.length+t.groups.changed.length,r=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),r>0&&n.push(`${r} query assignment ${r===1?"change":"changes"}`),i>0&&n.push(`${i} group ${i===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 Wt(t){return[...new Set(t)]}function gs(t){return Wt(t).sort()}function rx(t,s,n){return t.kind==="groups"?{groupKeys:gs(t.groupIds),queryIds:gs(n)}:{targetKeys:gs(t.kind==="all"?s:t.propertyIds),queryIds:gs(n)}}function ox(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 Xi(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function lx(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(Xi).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(i=>({...i,aliases:[...i.aliases]}))}))};const n=s.targetQuerySelections.flatMap(a=>a.queryIds.map(i=>({targetKey:a.targetKey,queryId:i,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(Xi).filter(Boolean),source:"manual"})),assignments:n,groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:(a.competitors??[]).map(i=>({stableKey:Da(i,"competitor"),label:i,domain:i,aliases:[]}))}))}}function cx({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:i,publishedPlan:r,canEdit:l=!0,onCreateQueries:m,onManageProjectQueries:c,onPublished:h,service:x=zh}){const[d,j]=o.useState(null),[S,b]=o.useState(null),[v,g]=o.useState("import"),[R,_]=o.useState(!0),[B,y]=o.useState(null),[p,w]=o.useState(null),[C,Y]=o.useState([]),[K,I]=o.useState({...zi}),[L,U]=o.useState("idle"),[T,H]=o.useState(""),[fe,xe]=o.useState(Ki),[Q,ie]=o.useState([]),[oe,z]=o.useState([]),[q,N]=o.useState({kind:"all"}),[se,ue]=o.useState(null),[re,le]=o.useState(null),[X,D]=o.useState(!1),[Z,he]=o.useState(null),[$e,st]=o.useState(0),[lt,Fe]=o.useState(null),[ee,Be]=o.useState({...en}),[Ve,ke]=o.useState(null),[Je,Ae]=o.useState(""),[we,O]=o.useState(null),[$,M]=o.useState(!1),[ye,De]=o.useState(!1),[te,Ge]=o.useState(null),[He,Ze]=o.useState(null),[Pe,Oe]=o.useState(null),[dt,ze]=o.useState(null),[et,Ie]=o.useState(null),wt=o.useRef(0),xt=o.useRef(0),Le=S?.draft??null,Me=S?.etag??null,ct=o.useMemo(()=>!l&&r?{baseActiveRevision:r.revision,authoring:lx(r)}:null,[l,r]),_e=Le??ct;async function Gt(P){const W=++wt.current;_(!0),y(null);try{let[f,G]=await Promise.all([x.loadSetup(t),x.loadDraft(t)]);if(!G.draft&&P&&l&&(await x.createDraft(t,f.activeRevision),[f,G]=await Promise.all([x.loadSetup(t),x.loadDraft(t)])),W!==wt.current)return;j(f),b(G),g(Wh(G.draft));const J=ba(G.draft);ie(J)}catch(f){if(W!==wt.current)return;y(Ot(f,"Could not load advanced measurement setup."))}finally{W===wt.current&&_(!1)}}o.useEffect(()=>(Gt(!0),()=>{wt.current+=1}),[t,l,x]),o.useEffect(()=>{!R&&!Le&&ct&&g("properties")},[Le,R,ct]);async function St(){const P=await x.loadDraft(t);return b(P),P}async function pt(P){Ie(null);try{const[W,f]=await Promise.all([x.loadSetup(t),x.loadDraft(t)]);j(W),b(f);const G=ba(f.draft);ie(G),g(J=>Yh(f.draft,J)),w(P)}catch(W){w(Ot(W,P))}}async function at(P,W,f,G={}){const{preserveBusyAction:J=!1}=G;if(!l||!Me||Pe&&!J)return null;J||Oe(P),w(null),Ie(null);try{const Se=await W(Me),ft=await St();return Y((Se.warnings??[]).map((ot,Pt)=>ya(ot,Pt,ft.draft?.authoring))),ft}catch(Se){return ws(Se)?await pt("This setup changed in another session. The latest draft is loaded; review your changes again."):w(Ot(Se,f)),null}finally{J||Oe(null)}}const F=o.useMemo(()=>(_e?.authoring.targets??[]).map(P=>{const W=Hi(P);return{id:P.stableKey,name:P.label,url:W[0]??"No URL",urls:W,state:Xh(P.status)}}),[_e]),je=o.useMemo(()=>_e?.authoring.targets.filter(P=>P.status==="included")??[],[_e]),me=o.useMemo(()=>je.map(P=>({id:P.stableKey,label:P.label,urlCount:Hi(P).length})),[je]),ve=_e?.authoring.assignments.length??0,jt=o.useMemo(()=>{if(!_e)return[];const P=new Set(s.map(G=>G.id)),W=s.map(G=>({id:G.id,text:G.query,source:"saved-project-queries",propertyIds:Wt(_e.authoring.assignments.filter(J=>J.queryId===G.id).map(J=>J.targetKey))})),f=Wt(_e.authoring.assignments.map(G=>G.queryId).filter(G=>!P.has(G))).map(G=>({id:G,source:"unavailable-tracked-query",state:"missing",propertyIds:Wt(_e.authoring.assignments.filter(J=>J.queryId===G).map(J=>J.targetKey))}));return[...W,...f]},[s,_e]),Lt=o.useMemo(()=>(_e?.authoring.groups??[]).map(P=>({id:P.stableKey,name:P.label,propertyIds:P.targetKeys,competitors:P.competitors.map(W=>W.domain)})),[_e]),it=o.useMemo(()=>{if(oe.length===0)return null;const P=rx(q,me.map(f=>f.id),oe);return(P.groupKeys?.length??P.targetKeys?.length??0)>0?P:null},[q,me,oe]),Ct=it?JSON.stringify(it):"";o.useEffect(()=>{const P=it,W=++xt.current;if(!l||!Le||!Me||!P){ue(null),le(null),he(null),D(!1);return}ue(null),le(null),he(null),D(!0);const f=window.setTimeout(()=>{x.previewAssignments(t,P).then(G=>{if(W===xt.current){if(G.draftEtag!==Me){ue(null),le(null),he("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}ue(G),le(Ct)}}).catch(G=>{W===xt.current&&(ue(null),le(null),he(Vh(G)))}).finally(()=>{W===xt.current&&D(!1)})},250);return()=>{window.clearTimeout(f),xt.current+=1}},[it,Ct,$e,l,Le,Me,t,x]);const zt=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"}]:[],..._e?.authoring.assignments.some(P=>P.queryClass==="unclassified")&&!(ct&&r?.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,ct,r,C,_e]),Kt=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 kt(P){let W;try{W=Hh(P)}catch(G){w(Ot(G,"Check the sitemap details and try again."));return}I(P),U("reviewing");const f=await at("import",G=>x.importSitemap(t,G,W),"Could not review this sitemap.");if(f?.draft){const G=f.draft.authoring.targets.filter(Se=>Se.status==="proposed").map(Se=>Se.stableKey),J=f.draft.authoring.targets.filter(Se=>Se.status==="included").map(Se=>Se.stableKey);ie([...J,...G]),H(""),xe(Ki),g("properties"),U("idle")}else U("error")}async function Qt(P){if(!m||P.length===0||Pe)return[];Oe("create-queries"),ze(null);try{return await m(P)}catch(W){throw ze(ut(W)),W}finally{Oe(null)}}async function Xe(P){if(!Le||!Me||Pe)return;const W=new Set(P),G=Le.authoring.targets.filter(Se=>Se.status==="proposed"&&Se.discoveryIdentity).map(Se=>({discoveryIdentity:Se.discoveryIdentity,action:W.has(Se.stableKey)?"create":"ignore"})),J=G.length>0||Le.authoring.targets.some(Se=>Se.status!=="proposed"&&Se.status==="included"!==W.has(Se.stableKey));Oe("properties"),w(null),Ie(null);try{if(!J){ie([...W]),N({kind:"all"}),g("groups");return}await x.applySitemapSelection(t,Me,G,[...W]);const Se=await St(),ft=ba(Se.draft);ie(ft),N({kind:"all"}),g("groups")}catch(Se){ws(Se)?await pt("This setup changed in another session. The latest Properties are loaded."):w(Ot(Se,"Could not save the selected Properties."))}finally{Oe(null)}}async function vs(P){const W=P.groupIds&&P.groupIds.length>0?{groupKeys:gs(P.groupIds),queryIds:gs(P.queryIds)}:{targetKeys:gs(P.propertyIds),queryIds:gs(P.queryIds)};if(!se||re!==JSON.stringify(W)||!Me||se.draftEtag!==Me){w("Review the latest assignment impact before assigning queries.");return}await at("assignments",G=>x.applyAssignments(t,G,W),"Could not apply these queries.")&&(z([]),Fe(`${se.assignments.added} new assignment${se.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function Nt(P){if(P.propertyIds.length===0)return;await at("replace-assignments",f=>x.replaceAssignments(t,f,{targetKeys:Wt(P.propertyIds),queryIds:[P.queryId]}),"Could not replace this query assignment.")&&(z(f=>f.filter(G=>G!==P.queryId)),Fe("Query assignments replaced."))}async function ys(P,W=!1){if(P.length===0)return;if(!await at("paired-assignments",G=>x.applyPairedAssignments(t,G,[...P]),"Could not assign these queries.",{preserveBusyAction:W}))throw new Error("Could not assign these queries.")}async function Ht(P){if(!(!l||!m||P.length===0||Pe)){Oe("create-and-pair-questions"),ze(null);try{let W;try{W=await m(Wt(P.map(J=>J.text)))}catch(J){throw ze(ut(J)),J}const f=new Map(W.map(J=>[J.query,J.id])),G=P.map(J=>({targetKey:J.propertyId,queryId:f.get(J.text)})).filter(J=>J.queryId!==void 0);if(G.length!==P.length){const J=new Error("The created queries could not be matched to their Properties.");throw ze("The queries were added, but could not be paired with every Property. Try again to pair them."),J}try{await ys(G,!0)}catch(J){throw ze("The queries were added, but could not be assigned to their Properties. Try again to pair them."),J}}finally{Oe(null)}}}async function rs(P){if(!Le)return;const W=Wt(Le.authoring.assignments.filter(G=>G.queryId===P).map(G=>G.targetKey));if(W.length===0)return;await at(`remove-${P}`,G=>x.removeAssignment(t,G,W,P),"Could not clear this query assignment.")&&z(G=>G.filter(J=>J!==P))}async function Jt(P){if(!Le||!Me||Pe)return;const W=P.name.trim();if(!W)return;const f=Ve??Da(W,"group"),G=Le.authoring.groups.find(ot=>ot.stableKey===f);if(G&&Ve===null){w(`A group named "${G.label}" already exists. Edit it or choose a different name.`);return}const J=P.competitorDomains.split(/[\s,]+/).map(ot=>ot.trim()).filter(Boolean),Se=J.find(ot=>Wi(ot)===null);if(Se){w(`"${Se}" is not a valid competitor domain.`);return}const ft=Wt(J.map(ot=>Wi(ot)));Oe("group"),w(null),Ie(null);try{const ot=await x.upsertGroup(t,Me,{stableKey:f,label:W,targetKeys:Wt(P.propertyIds),competitors:ft.map($t=>G?.competitors.find(ls=>ls.domain===$t)??{stableKey:Da($t,"competitor"),label:$t,domain:$t,aliases:[]})}),Pt=await St();Y(ot.warnings.map(($t,ls)=>ya($t,ls,Pt.draft?.authoring))),Be({...en}),ke(null)}catch(ot){ws(ot)?await pt("This setup changed in another session. The latest groups are loaded."):w(Ot(ot,"Could not save this group."))}finally{Oe(null)}}function tt(P){const W=Le?.authoring.groups.find(f=>f.stableKey===P);W&&(ke(P),Be({name:W.label,propertyIds:[...W.targetKeys],competitorDomains:W.competitors.map(f=>f.domain).join(", ")}))}async function os(P){await at("remove-group",f=>x.removeGroup(t,f,P),"Could not remove this group.")&&(N(f=>f.kind==="groups"&&f.groupIds.includes(P)?{kind:"all"}:f),Ve===P&&(ke(null),Be({...en})))}function At(P){Ae(P),O(null),Ge(null),Ze(null)}async function gt(){if(!(!l||!Je.trim()||$||ye)){M(!0),Ge(null),Ze(null);try{O(await x.previewGroupMembership(t,{csv:Je}))}catch(P){O(null),Ge(Ot(P,"Could not review this CSV."))}finally{M(!1)}}}async function Zt(P){if(!(!l||!Me||!we||P.length===0||Pe)){if(we.draftEtag!==Me){Ge("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}De(!0),Oe("group-import"),Ge(null),Ze(null),Ie(null);try{const W=await x.applyGroupMembership(t,Me,{csv:Je,sourceChecksum:we.sourceChecksum,previewChecksum:we.previewChecksum,acceptedRows:Wt(P.map(String)).map(Number)}),f=await St();Y(W.warnings.map((G,J)=>ya(G,J,f.draft?.authoring))),Ae(""),O(null),Ze(`${W.addedMemberships} membership${W.addedMemberships===1?"":"s"} added${W.unchangedMemberships>0?`; ${W.unchangedMemberships} already present`:""}.`)}catch(W){ws(W)?(await pt("This setup changed in another session. The latest draft is loaded; review the CSV again."),Ge("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Ge(Ot(W,"Could not apply this CSV."))}finally{Oe(null),De(!1)}}}async function rt(){if(!(!Le||!Me||Pe||ve===0)){Oe("review"),w(null),Ie(null);try{const[P,W]=await Promise.all([x.compilePreview(t),x.diffPreview(t)]),f=[...P.checks,...W.checks],G=f.some(J=>J.ruleId==="active-revision-schema-v1");if(Y(ax(f.filter(J=>J.ruleId!=="active-revision-schema-v1"),{authoring:_e?.authoring,queries:s})),!P.ok||!W.ok)return;if(W.diff.activeRevision!==Le.baseActiveRevision){await pt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(P.compiledChecksum!==W.compiledChecksum){w("The setup changed while it was being reviewed. Review the latest changes again.");return}Ie({etag:Me,baseActiveRevision:Le.baseActiveRevision,compiledChecksum:P.compiledChecksum,changes:ix(W.diff,G),providerCalls:P.plan.executionNodes.reduce((J,Se)=>J+Se.expectedSnapshots,0)})}catch(P){w(Ot(P,"Could not review this setup."))}finally{Oe(null)}}}async function Ut(){if(!(!Le||!Me||!et||Pe)){if(Me!==et.etag||Le.baseActiveRevision!==et.baseActiveRevision){Ie(null),w("The setup changed after review. Review the latest changes before publishing.");return}Oe("publish"),w(null);try{await x.publish(t,Me,{expectedActiveRevision:et.baseActiveRevision,expectedCompiledChecksum:et.compiledChecksum}),b({draft:null,etag:null}),Ie(null),h?.()}catch(P){ws(P)?await pt("The setup changed before it could be published. Review the latest draft and publish again."):w(Ot(P,"Could not publish this setup."))}finally{Oe(null)}}}async function k(){if(!(!Me||Pe)){Oe("discard"),w(null);try{await x.discard(t,Me),b({draft:null,etag:null}),Ie(null),h?.()}catch(P){ws(P)?await pt("This setup changed in another session. The latest draft is loaded."):w(Ot(P,"Could not discard these changes."))}finally{Oe(null)}}}async function be(){if(!(!Le||!Me||!d||Pe)){Oe("restart"),w(null),Ie(null);try{await x.discard(t,Me),await x.createDraft(t,d.activeRevision),I({...zi}),H(""),ie([]),z([]),N({kind:"all"}),ue(null),he(null),Fe(null),Be({...en}),ke(null),Ae(""),O(null),Ge(null),Ze(null),await Gt(!1)}catch(P){ws(P)?await pt("The setup changed again. Reloaded the latest draft and published setup."):w(Ot(P,"Could not restart this setup."))}finally{Oe(null)}}}if(R)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(B)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:B}),e.jsx(A,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Gt(!0)},children:"Try again"})]})]});if(!_e||l&&!Me)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:l?"Start setup from the project Overview.":"No advanced setup is available to review."})]});if(l&&Le&&d&&Le.baseActiveRevision!==d.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(A,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:Pe==="restart",onClick:()=>{be()},children:Pe==="restart"?"Restarting…":"Discard draft and restart"})]}),p?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:p}):null]});const Ne=a&&i?e.jsx("div",{className:"flex justify-end",children:e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:i,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[d?.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,p?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:p}):null,Ne,v==="import"||v==="properties"?e.jsx(Dn,{currentStep:v,hasDraft:Le!==null,canEdit:l,onStepChange:l?void 0:g,onDiscard:()=>{k()},importProperties:{importDraft:K,onImportDraftChange:P=>{I(P),U("idle"),w(null)},onReviewSitemap:P=>{kt(P)},reviewState:L,properties:F,propertiesState:"ready",propertiesSearch:T,onPropertiesSearchChange:H,maxVisibleProperties:fe,onShowAllProperties:()=>xe(F.length),selectedPropertyIds:Q,onSelectedPropertyIdsChange:P=>ie([...P]),onContinue:P=>{Xe(P)},isContinuing:Pe==="properties",onRetryProperties:()=>{St()},onReturnToImport:()=>g("import")}}):v==="queries"?e.jsx(Dn,{currentStep:"queries",hasDraft:Le!==null,canEdit:l,onStepChange:l?void 0:g,onDiscard:()=>{k()},onManageProjectQueries:c,queries:{onCreateQueries:m?P=>Qt(P):void 0,isCreatingQueries:Pe==="create-queries"||Pe==="create-and-pair-questions",isBusy:Pe!==null,createQueriesError:dt,availability:Kt,properties:me,queries:jt,selectedQueryIds:oe,isApplying:Pe==="assignments"||Pe==="paired-assignments",onSelectedQueryIdsChange:P=>z([...P]),onApplySelectedQueries:P=>vs(P),groups:Lt,audience:q,onAudienceChange:P=>{N(P),Fe(null)},assignmentImpact:se&&re===Ct?ox(se):null,isPreviewingAssignmentImpact:X,assignmentImpactError:Z,onRetryAssignmentImpact:()=>st(P=>P+1),assignmentNotice:lt,onReplaceAssignments:Nt,isReplacingAssignments:Pe==="replace-assignments",onCreateAndPairQuestions:l&&m?Ht:void 0,onClearQueryAssignments:rs,onRemoveQuery:rs,canContinue:ve>0,onBack:()=>g("groups"),onContinue:()=>g("review")}}):v==="groups"?e.jsx(Dn,{currentStep:"groups",hasDraft:Le!==null,canEdit:l,onStepChange:l?void 0:g,onDiscard:()=>{k()},groups:{properties:me,groups:Lt,groupDraft:ee,isSaving:Pe==="group",onGroupDraftChange:Be,onSaveGroup:Jt,onEditGroup:P=>tt(P.id),onRemoveGroup:os,onClearGroupDraft:()=>{ke(null),Be({...en})},membershipImport:{csv:Je,preview:we,isReviewing:$,isApplying:ye,error:te,notice:He,onCsvChange:At,onReview:gt,onApply:Zt},onBack:()=>{g("properties")},onContinue:()=>g("queries")}}):e.jsx(Dn,{currentStep:"review",hasDraft:Le!==null,canEdit:l,onStepChange:l?void 0:g,onDiscard:()=>{k()},review:{counts:{properties:je.length,queries:new Set(_e.authoring.assignments.map(P=>P.queryId)).size,groups:_e.authoring.groups.length,assignments:_e.authoring.assignments.length,providerCalls:et?.providerCalls},flaggedExceptions:zt,reviewedChanges:et?.changes,isReviewing:Pe==="review",canReviewChanges:ve>0&&!Pe,onReviewChanges:rt,onBack:()=>g("queries"),canPublish:et!==null&&!Pe,isPublishing:Pe==="publish",onPublish:Ut}})]})}const dx=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function Ji(t){return t.label!=="Complete"}const Ss="__all_properties__",ux=50,co=50,mx=20,hx=50,xx=250,px=5,gx=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],fx={"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"},uo={plan_v1:"Setup update required.",no_completed_run:"Not measured yet.",no_population:"No matching queries.",evidence_incomplete:"Evidence incomplete.",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."},bx={numerator:null,denominator:null,reason:"plan_v1"};function ln(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 vx(t){return ln(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function mo(t){if(ln(t))return"";const s=t.reason??"unavailable";return uo[s]??s}function Zi(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 yx(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function jx(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function Nx(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function an({metric:t,compact:s=!1}){const n=s?ln(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":ln(t)?"text-lg font-semibold text-heading":"text-lg font-semibold text-secondary";return e.jsx("span",{className:"inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums",...ln(t)?{}:{title:mo(t)},children:e.jsx("span",{className:n,children:vx(t)})})}function Va({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(A,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function er({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[i,r]=o.useState(co),l=s.slice(0,i);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:l.map((m,c)=>e.jsx("li",{className:a,children:m},`${m}:${c}`))}),e.jsx(Va,{shown:l.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function wx({evidence:t,state:s="ready",onRetry:n}){const[a,i]=o.useState(co),r=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(A,{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:r.map(l=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(de,{tone:l.tone,children:fx[l.kind]}),l.historical?e.jsx(de,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:l.query}),l.provider||l.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[l.provider,l.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:l.url})]},l.id))})]})}),e.jsx(Va,{shown:r.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>i(Number.MAX_SAFE_INTEGER)})]})]})}function Sx({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(er,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(er,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(wx,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function Cx({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(an,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function tr({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:i=!1}){function r(l){if(i)return;const m=n.findIndex(x=>x.value===s);let c=null;if(l.key==="ArrowRight"||l.key==="ArrowDown"?c=(m+1)%n.length:l.key==="ArrowLeft"||l.key==="ArrowUp"?c=(m-1+n.length)%n.length:l.key==="Home"?c=0:l.key==="End"&&(c=n.length-1),c===null)return;l.preventDefault();const h=n[c];a(h.value),l.currentTarget.querySelectorAll('[role="radio"]')[c].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":i,className:"segmented flex-wrap",onKeyDown:r,children:n.map(l=>{const m=l.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":m,tabIndex:m?0:-1,disabled:i,onClick:()=>a(l.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${m?"segmented-option-active":""}`,children:l.label},l.value)})})}function kx({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(Ke,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function Ax({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:i=!1,isRepublishingSetup:r=!1,isViewLoading:l=!1,isLoadingMore:m=!1,isLoadMoreError:c=!1,viewSearch:h,onViewChange:x,onLoadMore:d,onPropertyExpand:j,onRetryEvidence:S,renderPropertyLink:b}){const v=t.currentView!=null,g=t.classReporting==="available"&&(v||t.classScopes!=null),[R,_]=o.useState(t.currentView?.queryClass??"all"),[B,y]=o.useState(t.currentView?.scope.key??Ss),[p,w]=o.useState(h??""),[C,Y]=o.useState(ux),[K,I]=o.useState(mx),[L,U]=o.useState(t.currentView?.sort??"label-asc"),[T,H]=o.useState(null),fe=o.useRef(h??""),xe=g&&!v&&R!=="all"?R==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,Q=v?{aggregate:t.currentView.aggregate,groups:[]}:xe,ie=o.useCallback(O=>{if(!v||!x)return;const $=O.scope??(B===Ss?"all":"group"),M=O.search??p;fe.current=M,x({scope:$,...$==="group"?{groupKey:O.groupKey??B}:{},queryClass:O.queryClass??R,...M?{search:M}:{},...O.sort?{sort:O.sort}:{}})},[x,p,R,B,v]);o.useEffect(()=>{!t.currentView||l||(_(t.currentView.queryClass),y(t.currentView.scope.key??Ss),t.currentView.sort&&U(t.currentView.sort))},[l,t.currentView]),o.useEffect(()=>{h!==void 0&&(fe.current=h,w(O=>O.trim()===h.trim()?O:h))},[h]),o.useEffect(()=>{if(!v||!x||p===fe.current)return;const O=window.setTimeout(()=>ie({search:p}),xx);return()=>window.clearTimeout(O)},[x,ie,p,v]);const oe=t.availableGroups??Q.groups;o.useEffect(()=>{B===Ss||oe.some(O=>O.id===B)||y(Ss)},[oe,B]);const z=v?void 0:Q.groups.find(O=>O.id===B),q=z?.aggregate??Q.aggregate,N=O=>g?O:bx,se=L,ue=p.trim().toLocaleLowerCase(),re=o.useMemo(()=>!v&&ue?q.properties.filter(O=>O.name.toLocaleLowerCase().includes(ue)):q.properties,[q.properties,ue,v]),le=v?re:re.slice(0,C),X=(v?t.currentView?.scope.kind==="group":z!=null)&&R==="non-brand"&&g&&(v||z.confirmedCompetitorCount>0)&&(q.shareOfVoice?.length??0)>0,D=g?q.unavailablePropertyCount??0:0,Z=t.flaggedResults.reduce((O,$)=>O+($.count??1),0),he=t.flaggedResultsTotal??Z,$e=[N(q.metrics.propertiesMentioned),N(q.metrics.mentionCoverage),N(q.metrics.citationCoverage)].map(mo).find(Boolean),st=g?t.nextActionText??$e??(D>0?`${D} ${D===1?"property is":"properties are"} unavailable.`:he>0?`${he} flagged ${he===1?"result needs":"results need"} review.`:null):uo.plan_v1,ee=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?yx(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Be=jx(t.latestMeasurement.date),Ve=[{value:Ss,label:"All properties"},...oe.map(O=>({value:O.id,label:O.label}))],ke=oe.length>px;function Je(O){y(O),ie(O===Ss?{scope:"all"}:{scope:"group",groupKey:O})}function Ae(O){_(O),ie({queryClass:O})}function we(O){const $=T!==O;H($?O:null),$&&j?.(O)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":l,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:l?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(de,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(de,{tone:"caution",children:"Includes historical data"}):null,ee?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:ee}):null,Be?e.jsx("span",{className:"text-sm text-secondary",children:Be}):null,st?e.jsx("span",{className:"text-sm text-secondary",children:st}):null,s&&g&&n?e.jsx(A,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:i,children:i?"Starting measurement…":"Run measurement"}):s&&!g?e.jsx(A,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||r,children:r?"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:ke?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),ke?e.jsx("select",{id:"advanced-measurement-group",value:B,onChange:O=>Je(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:Ve.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))}):e.jsx(tr,{ariaLabelledBy:"advanced-measurement-group-label",value:B,options:Ve,onChange:Je})]}),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(tr,{ariaLabelledBy:"advanced-measurement-class-label",value:R,options:gx,onChange:Ae,disabled:!g})]}),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:p,onChange:O=>w(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"})]})]}),!l&&X?e.jsx(Cx,{values:q.shareOfVoice??[]}):null,l?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(Ke,{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(kx,{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:[dx.map(O=>{const $=se.startsWith(`${O.key}-`),M=$&&se.endsWith("-desc")?"descending":$?"ascending":"none";return e.jsx("th",{"aria-sort":M,className:(O.numeric,void 0),children:x?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const ye=`${O.key}-${$&&se.endsWith("-asc")?"desc":"asc"}`;U(ye),ie({sort:ye})},"aria-label":`Sort by ${O.label.toLowerCase()}`,children:[O.label,e.jsx(zn,{className:`h-3 w-3 transition-transform ${$?"opacity-100":"opacity-0"} ${M==="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 $=T===O.id;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:M=>{Nx(M.target)||we(O.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[b?b({id:O.id,name:O.name}):O.name,Ji(O.status)||O.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[Ji(O.status)?e.jsx(de,{tone:O.status.tone,children:O.status.label}):null,O.historical?e.jsx(de,{tone:"caution",children:"Historical"}):null]}):null,Zi(O)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Zi(O)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(an,{metric:O.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(an,{metric:O.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{size:"icon",variant:"ghost","aria-expanded":$,"aria-label":$?`Hide details for ${O.name}`:`Show details for ${O.name}`,onClick:()=>we(O.id),children:e.jsx(zn,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${$?"rotate-180":""}`,"aria-hidden":"true"})})})]},O.id),$?(O.providers??[]).map(M=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:M.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(an,{metric:M.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(an,{metric:M.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${O.id}:${M.provider}`)):null,$?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(Sx,{property:O,onRetryEvidence:S})})},`${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]})]})}),v&&t.currentView.nextCursor&&d?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]}),c?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(A,{size:"sm",variant:"outline",disabled:m,onClick:()=>d(t.currentView.nextCursor),children:m?"Loading…":c?"Retry loading more properties":"Show 50 more"})]}):v?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(Va,{shown:le.length,total:re.length,itemLabel:"properties",onShowAll:()=>Y(Number.MAX_SAFE_INTEGER)})]}),!l&&!ue&&he>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 (",he,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,K).map(O=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(de,{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))}),K<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,K).reduce((O,$)=>O+($.count??1),0)," of ",he," flagged results"]}),e.jsx(A,{size:"sm",variant:"outline",onClick:()=>I(O=>Math.min(t.flaggedResults.length,O+hx)),children:"Show 50 more"})]}):Z<he?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",Z," of ",he," flagged results"]}),v&&t.currentView.nextCursor&&d?e.jsx(A,{size:"sm",variant:"outline",disabled:m,onClick:()=>d(t.currentView.nextCursor),children:m?"Loading…":c?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function ho(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function Px(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 Ix({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:i="ready",onOpenSetup:r,onRunMeasurement:l,onRetryReport:m,onViewChange:c,onLoadMore:h,onPropertyExpand:x,onRetryEvidence:d,renderPropertyLink:j,isRunningMeasurement:S,isOpeningSetup:b,isViewLoading:v,isLoadingMore:g,isLoadMoreError:R,viewSearch:_}){return t.surface==="simple-overview"?n:e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&r?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",disabled:b,onClick:r,children:b?"Opening setup…":ho(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,i==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):i==="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."}),m?e.jsx(A,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:m,children:"Retry report"}):null]}):a?e.jsx(Ax,{report:a,canEdit:s,onRunMeasurement:l,onRepublishSetup:r,onViewChange:c,onLoadMore:h,onPropertyExpand:x,onRetryEvidence:d,renderPropertyLink:j,isRunningMeasurement:S,isRepublishingSetup:b,isViewLoading:v,isLoadingMore:g,isLoadMoreError:R,viewSearch:_}):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 Gs={numerator:null,denominator:null,reason:"plan_v1"};function Rx(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function sr(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function $x(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function Tx(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Lx(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 Mx(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function Dx(t){const s=new Map;for(const n of t){const a=Mx(n);if(!a)continue;const i=s.get(a)??[];i.push(n),s.set(a,i)}return s}function Ex(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(b=>[b.stableKey,b])),i=new Map(n.querySnapshots.map(b=>[b.queryId,b.queryText])),r=new Map;for(const b of n.targetQuerySelections){const v=r.get(b.targetKey)??[];v.push(...b.queryIds.map(g=>i.get(g)).filter(g=>!!g)),r.set(b.targetKey,[...new Set(v)])}const l=Dx(s.evidence),m=n.executionNodes.reduce((b,v)=>b+v.expectedSnapshots,0),c=s.run?.status==="completed"&&m>0,h=c?m:0,x=c?m:0,d=s.targets.map(b=>{const v=a.get(b.id),g=l.get(b.id)??[],R=g.map(y=>({id:`${y.observationId}:${y.usageEdgeId}:${y.sourceUrl}`,kind:$x(y.classification),query:y.queryText,url:y.sourceUrl,tone:Tx(y.classification),historical:y.historical||y.bridged})),_=g.some(y=>y.historical||y.bridged),B=s.run?b.completeness.complete?v?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${b.completeness.executed} of ${b.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:b.id,name:b.label,mentionCoverage:sr(b.mentionCoverage),citationCoverage:sr(b.citationCoverage),status:B,assignedQueries:r.get(b.id)??[],urls:v?.urls.map(Rx)??[],evidence:R,historical:_}}),j=new Map(d.map(b=>[b.id,b])),S=new Map(n.groups.map(b=>[b.stableKey,b]));return{classReporting:"plan-v1",latestMeasurement:{status:s.run?.status==="completed"?{label:"Complete",tone:"positive"}:s.run?.status==="partial"?{label:"Partial result",tone:"caution"}:{label:"Not measured",tone:"neutral"},completedSlots:h,totalSlots:x,date:Lx(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Gs,mentionCoverage:Gs,citationCoverage:Gs},properties:d},groups:s.groups.map(b=>({id:b.id,label:b.label,confirmedCompetitorCount:S.get(b.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Gs,mentionCoverage:Gs,citationCoverage:Gs},properties:b.targetIds.map(v=>j.get(v)).filter(v=>!!v)}}))},flaggedResults:[]}}const qx={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function mt(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function Gx(t){if(!t)return"—";const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Ox(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function Fx({projectName:t}){const[s,n]=o.useState(!1),[a,i]=o.useState(null),[r,l]=o.useState(wc),m=Re({...Sc({client:V,path:{name:t},query:{period:r}}),placeholderData:mr});async function c(){n(!0),i(null);try{await kc(t,"client",r)}catch(x){const d=x instanceof Ks||x instanceof Error?x.message:"Download failed";i(d)}finally{n(!1)}}if(m.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(m.error){const x=m.error instanceof Error?m.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-negative-400",children:x})})}const h=m.data;return h?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:h.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[h.meta.project.canonicalDomain," · ",h.meta.project.country," / ",h.meta.project.language.toUpperCase(),h.meta.location?` · Location: ${Ox(h.meta.location)}`:" · No location set"," · ","Last ",h.meta.periodDays," days"," · ","Generated ",Gx(h.meta.generatedAt)]}),a&&e.jsx("p",{className:"mt-2 text-xs text-negative-400",children:a})]}),e.jsxs("div",{className:"page-header-right flex flex-col items-end gap-2",children:[e.jsx(_x,{period:r,onChange:l}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:Te(c),disabled:s,children:[e.jsx(Pr,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(Hx,{report:h}),e.jsx(ep,{report:h,audience:"client"}),e.jsx(Vx,{report:h}),e.jsx(Xx,{report:h,audience:"client",projectName:t}),e.jsx(Jx,{report:h})]}):null}function _x({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:Cc.map(n=>{const a=n===t;return e.jsxs("button",{type:"button",onClick:()=>s(n),"aria-pressed":a,className:`segmented-option ${a?"segmented-option-active":""}`,children:[n,"d"]},n)})})}const nr="AI Visibility — Server-Side",ar="AI engine attention",Bx=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,Ux="Live telemetry from your server logs.";function Vx({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(fn,{eyebrow:ar,title:nr,subtitle:Ux}),e.jsx("p",{className:"text-sm text-muted",children:"Your server-side traffic source is connected. Numbers will appear after the next sync."})]});const n={current:s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,prior:s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior,deltaPct:Wd(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,i=`vs prior ${a} days`,r=ia(n,"requests",i),l=`${mt(s.verifiedCrawlerHits.current)} verified · ${mt(s.unverifiedCrawlerHits.current)} unverified${r?` · ${r}`:""}`,m=ia(s.aiUserFetchHits,"requests",i),h=[ia(s.referralArrivals,"sessions",i),s.referralArrivalsClassSummary].filter(Boolean).join(" · "),x=s.byOperator.filter(d=>d.verifiedHits>0||d.unverifiedHits>0||d.userFetchHits>0||d.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(fn,{eyebrow:ar,title:nr,subtitle:Bx(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(wa,{label:"AI bot requests observed",value:mt(n.current),subtitle:l}),e.jsx(wa,{label:"AI user-fetch requests",value:mt(s.aiUserFetchHits.current),subtitle:m||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(wa,{label:"AI referral sessions",value:mt(s.referralArrivals.current),subtitle:h})]}),x.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:"By AI tool"}),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:"AI tool"}),e.jsxs("th",{children:["Bot requests (",a,"d)"]}),e.jsxs("th",{children:["User fetches (",a,"d)"]}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:x.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:d.operator}),e.jsx("td",{children:mt(d.verifiedHits+d.unverifiedHits)}),e.jsx("td",{children:mt(d.userFetchHits)}),e.jsx("td",{children:mt(d.referralArrivals)})]},d.operator))})]})}),e.jsx("p",{className:"mt-2 text-[11px] text-muted",children:"Bot requests are bulk crawl (GPTBot, PerplexityBot, …). User fetches are on-demand reads triggered by real users inside an AI surface (ChatGPT-User, Perplexity-User, …). Verified means the request came from an IP the operator publishes as its own; unverified means the user-agent matched but the IP is not in a published range. User-fetch totals count both, since many genuine user fetches come from outside any published range."})]})]})}function zx(t,s){return t.audience==="both"||t.audience===s}const Kx={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Wn(t){return Kx[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Qx(t){if(!t)return null;const s=t.window??1,n=s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`;return t.direction==="up"?{text:`Up ${t.deltaAbs.toFixed(1)} points ${n}`,tone:"positive",arrow:"↑"}:t.direction==="down"?{text:`Down ${Math.abs(t.deltaAbs).toFixed(1)} points ${n}`,tone:"negative",arrow:"↓"}:{text:`Holding steady ${s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`}`,tone:"neutral",arrow:"→"}}function Hx({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,i=a>0?`${s.mentionRate}%`:"—",r=a>0?`When customers asked AI ${a} ${a===1?"query":"queries"} about your industry, AI mentioned you in ${s.mentionedQueryCount} of ${a===1?"them":"those answers"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer queries about your business.",l=Qx(t.whatsChanged.mentionRate),m=n.providers.length>0?n.providers.map(Wn).join(", "):`${mt(s.queryCount)} ${s.queryCount===1?"query":"queries"} tested`;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"rounded-2xl border border-default bg-bg-elevated/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-primary sm:text-7xl",children:i}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-neutral sm:text-lg",children:r}),l&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${l.tone==="positive"?"text-positive-400":l.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:l.arrow}),l.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(ja,{label:"AI mentions your name",value:`${s.mentionRate}%`,subtitle:a>0?`Says your name in ${s.mentionedQueryCount} of ${a} ${a===1?"answer":"answers"}`:"No data yet"}),e.jsx(ja,{label:"AI links to your website",value:`${s.citationRate}%`,subtitle:a>0?`Cites your site as a source in ${s.citedQueryCount} of ${a} ${a===1?"answer":"answers"}`:"No data yet"}),e.jsx(ja,{label:"AI tools tested",value:mt(s.providerCount),subtitle:m})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-bg/40 px-4 py-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-semibold text-strong",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-strong",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-strong",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Customer queries we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["These are the ",n.queries.length," ",n.queries.length===1?"query we asked":"queries we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((c,h)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-bg/40 px-3 py-2 text-sm text-strong",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-muted",children:String(h+1).padStart(2,"0")}),e.jsxs("span",{children:['"',c,'"']})]},h))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"How often each AI tool mentions you"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Higher is better. Each bar shows the share of customer queries where the AI named you in the answer."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(c=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:Wn(c.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-positive-500/70",style:{width:`${Math.max(c.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[c.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",c.mentionedCount,"/",c.totalCount,")"]})]})]},c.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((c,h)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:c},h))})]})}function ja({label:t,value:s,subtitle:n}){return e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx("p",{className:"mt-3 text-4xl font-bold tracking-tight text-primary sm:text-5xl",children:s}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:n})]})}function Wx(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function Yx(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function Xx({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(d=>zx(d,s)),i=eu(t,a),r=s==="client",l=Ac(),[m,c]=o.useState(new Set),h=m.size>0?i.filter(d=>!d.targetRef||!m.has(d.targetRef)):i,x=d=>{if(!d.targetRef)return;const j=d.targetRef;c(S=>new Set(S).add(j)),l.mutate({projectName:n,body:{targetRef:j}},{onSuccess:()=>{Ce({tone:"positive",title:`Dismissed "${d.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:S=>{Ce({tone:"negative",title:`Couldn't dismiss "${d.title}"`,detail:String(S)}),c(b=>{const v=new Set(b);return v.delete(j),v})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(fn,{eyebrow:r?"Action plan":"Agency actions",title:r?"What to do next":"Agency Action Plan",subtitle:r?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),h.length===0?e.jsx(Qa,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:h.map((d,j)=>{const S=d.evidence.length>0?d.evidence:d.why,b=d.why.length>0||d.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-default bg-surface p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-mono-800/80 text-sm font-semibold text-heading",title:"Priority — 1 will move the needle fastest",children:j+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(de,{tone:Ic(d),children:r?Wx(d.horizon):Pc(d.horizon)}),!r&&e.jsx(de,{tone:"neutral",children:Rc(d.category)}),e.jsx(de,{tone:"neutral",children:r?Yx(d.confidence):`${$c(d.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:d.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:d.action}),e.jsx(tp,{items:S,limit:3,className:"mt-3"}),b&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:r?"See the data behind this":"Evidence details"}),d.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:r?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.why.map((v,g)=>e.jsx("li",{children:v},g))})]}),d.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:r?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.evidence.map((v,g)=>e.jsx("li",{children:v},g))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:r?"What success looks like:":"Win condition:"})," ",d.successMetric]}),d.targetRef&&!ne()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>x(d),className:"rounded-md border border-default bg-bg-elevated/50 px-2.5 py-1 text-[11px] font-medium text-neutral hover:border-mono-600 hover:bg-mono-800/70 hover:text-heading",title:"Stop showing this recommendation. The page-detection logic relies on GSC/GA syncs that lag by days — if you've already addressed it, dismissing keeps the report current.",children:"Mark addressed"})})]},`${d.priority}-${d.title}`)})})]})}function ir({label:t,value:s,displayValue:n,max:a,barClass:i}){const r=a>0?Math.max(s/a*100,1.5):0;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-neutral",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${i}`,style:{width:`${r}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function Jx({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,i=tu(t).slice(0,5),r=s.length>0?Math.max(...s.map(c=>c.count)):0,l=n?Math.max(...n.topQueries.slice(0,5).map(c=>c.impressions),1):0,m=s.length>0||n!==null||a!==null||i.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(fn,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),m?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"The websites AI tools cited most often when answering customer queries about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(c=>e.jsx(ir,{label:c.domain+(c.isCompetitor?" (competitor)":""),value:c.count,displayValue:`${mt(c.count)}×`,max:r,barClass:"bg-mono-400/70"},c.domain))})]}),a&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${a.indexedPct>=90?"text-positive-400":a.indexedPct>=70?"text-caution-400":"text-negative-400"}`,children:[a.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[mt(a.indexed)," of ",mt(a.total)," pages indexed"]}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${a.indexedPct>=90?"bg-positive-500/70":a.indexedPct>=70?"bg-caution-500/70":"bg-negative-500/70"}`,style:{width:`${Math.max(a.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-medium text-strong",children:mt(a.notIndexed)})," ",a.notIndexed===1?"page is":"pages are"," not indexed yet."]})]}),n&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"What people search Google for"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["You appeared in ",e.jsx("span",{className:"font-semibold text-strong",children:mt(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:mt(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(c=>e.jsx(ir,{label:c.query,value:c.impressions,displayValue:`${mt(c.impressions)} ${c.impressions===1?"search":"searches"}`,max:l,barClass:"bg-info-500/70"},c.query))})]}),i.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Customer queries where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:i.map((c,h)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:c.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[Tc(c.action),c.winnabilityClass==="ceded"&&e.jsx(de,{tone:"caution",children:"Ceded surface"})]})]},h))})]})]}):e.jsx(Qa,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function za(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function Ka(t){return t==="up"?"↑":t==="down"?"↓":"→"}function Na({label:t,delta:s,unit:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"No prior data"})]});const a=n==="%"?"%":"",i=za(s.direction),r=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-heading",l=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:Yd(s);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${r}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:Ka(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:l})]})}function rr({label:t,delta:s,countLabel:n,comparisonWindowDays:a}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Not enough trend data"})]});const i=za(s.direction),r=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-heading",l=Xd(s,n,`vs prior ${a} days`);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${r}`,children:[mt(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:Ka(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:l})]})}function Zx({movements:t,audience:s}){const n=t.filter(i=>i.direction!=="flat");if(n.length===0)return null;const a=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:a?"How each AI tool changed":"AI engine movements"}),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:a?"AI tool":"Engine"}),e.jsx("th",{children:a?"Was":"Prior"}),e.jsx("th",{children:a?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(i=>{const r=i.deltaAbs>0?"+":"",l=za(i.direction),m=l==="positive"?"text-positive-400":l==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?Wn(i.provider):i.provider}),e.jsxs("td",{children:[i.prior,"%"]}),e.jsxs("td",{children:[i.current,"%"]}),e.jsxs("td",{className:m,children:[r,i.deltaAbs.toFixed(1),"% ",Ka(i.direction)]})]},i.provider)})})]})})]})}function or({insights:t,heading:s,emptyMessage:n,audience:a}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-surface p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-muted",children:n})]});const i=a==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:s}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!i&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:i?"What changed":"Title"}),e.jsx("th",{children:i?"Customer query":"Query"}),e.jsx("th",{children:i?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(r=>e.jsxs("tr",{children:[!i&&e.jsxs("td",{children:[e.jsx(de,{tone:qx[r.severity],children:Lc(r.severity)}),r.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",r.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[r.title,i&&r.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",r.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:r.query}),e.jsx("td",{className:"text-xs text-secondary",children:i?Wn(r.provider):r.provider})]},r.id))})]})})]})}function ep({report:t,audience:s}){const n=t.whatsChanged,a=s==="client",i=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,r=e.jsx(fn,{eyebrow:a?"Since last check":"Section 2",title:a?"What's different since last check":"What's Changed",subtitle:a?void 0:n.headline});return i?e.jsxs("section",{className:"page-section-divider",children:[r,e.jsx(Qa,{message:a?"No comparison yet — trends will appear after a few more checks.":"Trends will appear after a few more checks."})]}):e.jsxs("section",{className:"page-section-divider",children:[r,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Na,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(Na,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(Na,{label:a?"Queries AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(rr,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(rr,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(Zx,{movements:n.providerMovements,audience:s}),e.jsx(or,{insights:n.wins,heading:a?"What got better":"Wins",emptyMessage:a?"No new wins this period.":"No new gains in the latest check.",audience:s}),e.jsx(or,{insights:n.regressions,heading:a?"What got worse":"Regressions",emptyMessage:a?"Nothing got worse this period.":"No new regressions in the latest check.",audience:s})]})}function wa({label:t,value:s,tone:n,subtitle:a}){const i=n==="positive"?"text-positive-400":n==="caution"?"text-caution-400":n==="negative"?"text-negative-400":"text-heading";return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${i}`,children:s}),a&&e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:a})]})}function fn({eyebrow:t,title:s,subtitle:n}){return e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("h2",{className:"page-title",children:s}),n&&e.jsx("p",{className:"page-subtitle mt-1",children:n})]})}function tp({items:t,limit:s=3,className:n}){if(t.length===0)return null;const a=t.slice(0,s),i=t.length-a.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[a.map((r,l)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:r},l)),i>0&&e.jsxs("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-secondary",children:["+",i," more"]})]})}function Qa({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function sp({project:t,onUpdateProject:s,onRefresh:n}){const[a,i]=o.useState(!1),[r,l]=o.useState(!1),[m,c]=o.useState(null),[h,x]=o.useState(t.displayName),[d,j]=o.useState(t.canonicalDomain),[S,b]=o.useState(t.country),[v,g]=o.useState(t.language),[R,_]=o.useState(t.ownedDomains??[]),[B,y]=o.useState(""),[p,w]=o.useState(t.aliases??[]),[C,Y]=o.useState(""),[K,I]=o.useState(null),[L,U]=o.useState(!1),[T,H]=o.useState(!1),[fe,xe]=o.useState(""),[Q,ie]=o.useState(""),[oe,z]=o.useState(""),[q,N]=o.useState(""),[se,ue]=o.useState(""),[re,le]=o.useState(null),[X,D]=o.useState(null);o.useEffect(()=>{a||(x(t.displayName),j(t.canonicalDomain),b(t.country),g(t.language),_(t.ownedDomains??[]),w(t.aliases??[]))},[t,a]);function Z(){i(!1),c(null),x(t.displayName),j(t.canonicalDomain),b(t.country),g(t.language),_(t.ownedDomains??[]),w(t.aliases??[]),y(""),Y("")}function he(){const $=B.trim();$&&(R.includes($)||_([...R,$]),y(""))}function $e($){_(R.filter(M=>M!==$))}function st(){const $=C.trim();if(!$)return;const M=$.toLowerCase();p.some(ye=>ye.toLowerCase()===M)||w([...p,$]),Y("")}function lt($){w(p.filter(M=>M!==$))}async function Fe(){if(!(!h.trim()||!d.trim()||!S.trim()||!v.trim())){l(!0),c(null);try{await s(t.name,{displayName:h.trim(),canonicalDomain:d.trim(),ownedDomains:R,aliases:p,country:S.trim(),language:v.trim()}),i(!1),Ce({title:"Project settings saved",detail:`${h.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch($){c($ instanceof Error?$.message:"Failed to save")}finally{l(!1)}}}async function ee(){const $=fe.trim(),M=Q.trim(),ye=oe.trim(),De=q.trim();if(!(!$||!M||!ye||!De)){U(!0),I(null);try{const te={label:$,city:M,region:ye,country:De};se.trim()&&(te.timezone=se.trim()),await Ec(t.name,te),n(),xe(""),ie(""),z(""),N(""),ue(""),H(!1),Ce({title:"Location added",detail:`${$} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${$}`,dedupeMode:"drop"})}catch(te){I(te instanceof Error?te.message:"Failed to add location")}finally{U(!1)}}}async function Be($){U(!0),I(null);try{await Dc(t.name,$),n(),Ce({title:"Location removed",detail:`${$} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${$}`,dedupeMode:"drop"})}catch(M){I(M instanceof Error?M.message:"Failed to remove location")}finally{U(!1)}}async function Ve($){U(!0),I(null);try{await Mc(t.name,$),n(),Ce({title:"Default location updated",detail:`${$} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(M){I(M instanceof Error?M.message:"Failed to set default location")}finally{U(!1)}}async function ke($){le($),D(null);try{await qc(t.name,$),Ce({title:`${$.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(M){D(M instanceof Error?M.message:"Could not download tracking results.")}finally{le(null)}}const Je=h!==t.displayName||d!==t.canonicalDomain||S!==t.country||v!==t.language||JSON.stringify(R)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(p)!==JSON.stringify(t.aliases??[]),Ae="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",we="mb-1 block text-sm font-medium text-secondary",O=fe.trim()&&Q.trim()&&oe.trim()&&q.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"})]}),!ne()&&!a&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>i(!0),children:"Edit settings"})]}),m&&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:[m,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>c(null),children:"×"})]}),!ne()&&a?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:we,children:"Display name"}),e.jsx("input",{className:Ae,type:"text",value:h,onChange:$=>x($.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:we,children:"Canonical domain"}),e.jsx("input",{className:Ae,type:"text",value:d,onChange:$=>j($.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:we,children:"Country"}),e.jsx("input",{className:Ae,type:"text",value:S,onChange:$=>b($.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:we,children:"Language"}),e.jsx("input",{className:Ae,type:"text",value:v,onChange:$=>g($.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:we,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:R.map($=>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:[$,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>$e($),"aria-label":`Remove ${$}`,children:"×"})]},$))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ae} flex-1`,type:"text",placeholder:"docs.example.com",value:B,onChange:$=>y($.target.value),onKeyDown:$=>$.key==="Enter"&&($.preventDefault(),he())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!B.trim(),onClick:he,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:we,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:p.map($=>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:[$,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>lt($),"aria-label":`Remove ${$}`,children:"×"})]},$))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ae} flex-1`,type:"text",placeholder:"Facebook",value:C,onChange:$=>Y($.target.value),onKeyDown:$=>$.key==="Enter"&&($.preventDefault(),st())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!C.trim(),onClick:st,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(A,{type:"button",disabled:r||!Je||!h.trim()||!d.trim(),onClick:Te(Fe),children:r?"Saving...":"Save changes"}),e.jsx(A,{type:"button",variant:"outline",disabled:r,onClick:Z,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($=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:$},$))}):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($=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:$},$))}):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})]}),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:[K&&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:[K,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>I(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($=>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 ${$.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[$.label,$.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:$.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:$.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:$.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:$.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!ne()&&$.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:L,onClick:()=>{Ve($.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${$.label} as default location`,children:"Set default"}),!ne()&&e.jsx("button",{type:"button",disabled:L,onClick:()=>{Be($.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${$.label}`,children:"Remove"})]})})]},$.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),ne()?null:T?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:Ae,type:"text",value:fe,onChange:$=>xe($.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:Ae,type:"text",value:Q,onChange:$=>ie($.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:Ae,type:"text",value:oe,onChange:$=>z($.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:Ae,type:"text",value:q,onChange:$=>N($.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:Ae,type:"text",value:se,onChange:$=>ue($.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(A,{type:"button",size:"sm",disabled:L||!O,onClick:Te(ee),children:L?"Adding...":"Add location"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:L,onClick:()=>{H(!1),I(null)},children:"Cancel"})]})]}):e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:()=>H(!0),children:"+ Add location"})]})]})]})})})]}),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(A,{type:"button",variant:"outline",size:"sm",disabled:re!==null,onClick:Te(()=>ke("csv")),children:re==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:re!==null,onClick:Te(()=>ke("json")),children:re==="json"?"Preparing JSON...":"Download JSON"})]})]}),X&&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:X})]})]})]})}function tn(t){return{...t??{}}}function np(t,s){const n=Object.entries(t).sort(([i],[r])=>i.localeCompare(r)),a=Object.entries(s).sort(([i],[r])=>i.localeCompare(r));return n.length===a.length&&n.every(([i,r],l)=>{const m=a[l];return m?.[0]===i&&m[1]===r})}function ap({project:t,onSave:s}){const n=Re({queryKey:["settings"],queryFn:pr,staleTime:6e4}),[a,i]=o.useState(t.providers.length===0),[r,l]=o.useState(t.providers),[m,c]=o.useState(()=>tn(t.providerModels)),[h,x]=o.useState({providers:t.providers,providerModels:tn(t.providerModels)}),[d,j]=o.useState(!1),[S,b]=o.useState(!1),[v,g]=o.useState(null),[R,_]=o.useState(null),B=o.useRef(null),y=n.data?.providerCatalog??[],p=o.useMemo(()=>new Set((n.data?.providers??[]).filter(T=>T.configured).map(T=>T.name)),[n.data]),w=o.useMemo(()=>{const T=new Map(y.map(H=>[H.name,H]));for(const H of Object.keys(m))T.has(H)||T.set(H,{name:H,displayName:H,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...T.values()].sort((H,fe)=>H.displayName.localeCompare(fe.displayName))},[y,m]),C=!np(m,h.providerModels);o.useEffect(()=>{if(d||S)return;const T={providers:t.providers,providerModels:tn(t.providerModels)};x(T),i(T.providers.length===0),l(T.providers),c(T.providerModels)},[t]);function Y(){b(!0),i(!1),r.length===0&&l([...p])}function K(T,H,fe=!1){b(!0),c(xe=>{const Q={...xe};return H==="__inherit__"?delete Q[T]:H==="__custom__"?Q[T]=fe?"":Q[T]??"":Q[T]=H,Q}),H==="__custom__"&&queueMicrotask(()=>B.current?.focus())}function I(T,H){b(!0),l(fe=>H?[...new Set([...fe,T])]:fe.filter(xe=>xe!==T))}function L(){b(!1),i(h.providers.length===0),l(h.providers),c(tn(h.providerModels)),g(null),_(null)}async function U(){if(!(n.isError||n.isLoading||!a&&r.length===0)){j(!0),g(null),_(null);try{const T=Object.fromEntries(Object.entries(m).filter(([fe,xe])=>xe.trim()!==""&&(a||r.includes(fe)))),H={providers:a?[]:r,providerModels:T};await s(H),x({providers:[...H.providers],providerModels:tn(H.providerModels)}),b(!1),_("Engine settings saved. They apply on the next sweep.")}catch(T){g(qa(T))}finally{j(!1)}}}return ne()?null:n.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…"})}):n.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(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):y.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(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):p.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(Xt,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":d,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:d,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:a,onChange:()=>{b(!0),i(!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:!a,onChange:Y})," Choose engines"]}),!a&&e.jsx("div",{className:"project-engine-list",children:w.map(T=>{const H=r.includes(T.name),fe=p.has(T.name),xe=H&&!fe,Q=m[T.name],ie=T.knownModels.some(z=>z.id===Q),oe=Q===void 0?"__inherit__":ie?Q:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:H,disabled:!fe&&!H,onChange:z=>I(T.name,z.target.checked)})," ",e.jsx("span",{children:T.displayName}),xe&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),H&&(T.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${T.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${T.name}`,value:oe,onChange:z=>K(T.name,z.target.value,ie),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",T.defaultModel||"default"]}),T.knownModels.map(z=>e.jsx("option",{value:z.id,children:z.displayName},z.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),oe==="__custom__"&&e.jsx("input",{ref:B,"aria-label":`${T.displayName} custom model ID`,value:Q??"",onChange:z=>{b(!0),c(q=>({...q,[T.name]:z.target.value}))},"aria-describedby":`project-model-hint-${T.name}`}),e.jsxs("p",{id:`project-model-hint-${T.name}`,className:"project-engine-help",children:[Q?"Project override":"Inherited from instance settings",". ",T.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},T.name)})})]}),!a&&r.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),v&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:v}),R&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:R}),C&&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(A,{type:"button",onClick:()=>{U()},disabled:d||!a&&r.length===0,children:d?"Saving engines…":"Save engines"}),e.jsx(A,{type:"button",variant:"outline",onClick:L,disabled:d,children:"Cancel"})]})]})}const ip=[{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:"custom",label:"Custom cron expression"}],lr=["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 rp({projectName:t}){const[s,n]=o.useState("loading"),[a,i]=o.useState(!1),[r,l]=o.useState("daily"),[m,c]=o.useState(6),[h,x]=o.useState(""),[d,j]=o.useState("UTC"),[S,b]=o.useState(!1),[v,g]=o.useState(""),[R,_]=o.useState(!1),[B,y]=o.useState(!1),[p,w]=o.useState(null);o.useEffect(()=>{Gc(t).then(n).catch(()=>n(null))},[t]);const C=()=>{if(s&&s!=="loading"){const L=Fc(s.preset??null,s.cronExpr);l(L.freq),c(L.hour),x(L.customCron);const U=lr.includes(s.timezone);j(U?s.timezone:"Other"),b(!U),g(U?"":s.timezone)}else l("daily"),c(6),x(""),j("UTC"),b(!1),g("");w(null),i(!0)},Y=async()=>{_(!0),w(null);try{const U={timezone:S?v.trim()||"UTC":d};r==="custom"?U.cron=h.trim():U.preset=Bc(r,m);const T=await ci(t,U);n(T),i(!1),Ce({title:"Schedule saved",detail:na(T.preset??null,T.cronExpr,T.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(L){w(L instanceof Error?L.message:"Failed to save schedule")}finally{_(!1)}},K=async()=>{if(!(!s||s==="loading")){_(!0),w(null);try{const L={timezone:s.timezone,enabled:!s.enabled};s.preset?L.preset=s.preset:L.cron=s.cronExpr;const U=await ci(t,L);n(U),Ce({title:U.enabled?"Schedule resumed":"Schedule paused",detail:na(U.preset??null,U.cronExpr,U.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(L){w(L instanceof Error?L.message:"Failed to update schedule")}finally{_(!1)}}},I=async()=>{y(!0),w(null);try{await _c(t),n(null),i(!1),Ce({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(L){w(L instanceof Error?L.message:"Failed to remove schedule")}finally{y(!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"})]}),!ne()&&s!=="loading"&&!a&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:C,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!a&&s===null&&e.jsx(pe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),s!=="loading"&&!a&&s!==null&&e.jsxs(pe,{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:[e.jsx("p",{className:"text-sm font-medium text-strong",children:na(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(de,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),!ne()&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:R,onClick:Te(K),children:s.enabled?"Pause":"Resume"}),!ne()&&e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:B,onClick:Te(I),children:B?"Removing...":"Remove"})]})]}),p&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:p})]}),!ne()&&a&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[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",value:r,onChange:L=>l(L.target.value),children:ip.map(L=>e.jsx("option",{value:L.value,children:L.label},L.value))})]}),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:m,disabled:r==="twice-daily"||r==="custom",onChange:L=>c(parseInt(L.target.value)),children:Array.from({length:24},(L,U)=>e.jsx("option",{value:U,children:Oc(U)},U))})]})]}),r==="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:h,onChange:L=>x(L.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",value:S?"Other":d,onChange:L=>{L.target.value==="Other"?(b(!0),j("Other")):(b(!1),j(L.target.value))},children:[lr.map(L=>e.jsx("option",{value:L,children:L},L)),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:L=>g(L.target.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(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!1),w(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:R||r==="custom"&&!h.trim(),onClick:Te(Y),children:R?"Saving...":"Save schedule"})]})]})]})}const op=[{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 lp({projectName:t}){const[s,n]=o.useState("loading"),[a,i]=o.useState(!1),[r,l]=o.useState(""),[m,c]=o.useState(["citation.lost","citation.gained"]),[h,x]=o.useState(!1),[d,j]=o.useState(null),[S,b]=o.useState({}),[v,g]=o.useState(new Set);o.useEffect(()=>{Uc(t).then(n).catch(()=>n([]))},[t]);const R=p=>{c(w=>w.includes(p)?w.filter(C=>C!==p):[...w,p])},_=async()=>{if(!(!r.trim()||m.length===0)){x(!0),j(null);try{const p=await Vc(t,{channel:"webhook",url:r.trim(),events:m});n(w=>w==="loading"?[p]:[...w,p]),l(""),c(["citation.lost","citation.gained"]),i(!1),Ce({title:"Webhook added",detail:`Notifications will be sent to ${p.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(p){j(p instanceof Error?p.message:"Failed to add webhook")}finally{x(!1)}}},B=async p=>{if(!v.has(p)){g(w=>new Set(w).add(p));try{await Kc(t,p),n(w=>w==="loading"?w:w.filter(C=>C.id!==p)),Ce({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${p}`,dedupeMode:"drop"})}catch(w){j(w instanceof Error?w.message:"Failed to remove webhook")}finally{g(w=>{const C=new Set(w);return C.delete(p),C})}}},y=async p=>{b(w=>({...w,[p]:{state:"testing"}}));try{const w=await zc(t,p);b(C=>({...C,[p]:{state:w.ok?"ok":"fail",status:w.status}})),w.ok&&Ce({title:"Test notification sent",detail:`Webhook returned status ${w.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${p}`,dedupeMode:"replace"})}catch{b(w=>({...w,[p]:{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"})]}),!ne()&&s!=="loading"&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!a),j(null)},children:a?"Cancel":"+ Add webhook"})]}),!ne()&&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:r,onChange:p=>l(p.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:op.map(p=>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:m.includes(p.value),onChange:()=>R(p.value)}),e.jsx("span",{className:"text-sm text-neutral",children:p.label})]},p.value))})]}),d&&e.jsx("p",{className:"text-negative-400 text-sm",children:d}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!1),j(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:h||!r.trim()||m.length===0,onClick:Te(_),children:h?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(pe,{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(p=>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:p.urlHost,children:p.urlDisplay??p.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:p.events.map(w=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-strong bg-surface-inset px-2 py-0.5 text-[10px] font-medium text-secondary uppercase tracking-wide",children:w.replace("."," ")},w))})}),e.jsx("td",{children:e.jsx(de,{tone:p.enabled?"positive":"neutral",children:p.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[S[p.id]&&(()=>{const w=S[p.id],C=w.state==="testing"?"Sending…":w.state==="ok"?`Delivered${w.status?` (${w.status})`:""}`:`Failed${w.status?` (${w.status})`:""}`;return e.jsx(de,{tone:w.state==="ok"?"positive":w.state==="fail"?"negative":"neutral",children:C})})(),!ne()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:S[p.id]?.state==="testing",onClick:()=>{y(p.id)},children:"Test"}),!ne()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:v.has(p.id),onClick:()=>{B(p.id)},children:v.has(p.id)?"Removing…":"Remove"})]})})]},p.id))})]}),d&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:d})]})]})}const cr=2e3,dr=3e5;function cp(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 dp({projectName:t,refreshNonce:s}){const n=bs(),[a,i]=o.useState(null),[r,l]=o.useState([]),[m,c]=o.useState(null),[h,x]=o.useState([]),[d,j]=o.useState([]),[S,b]=o.useState(null),[v,g]=o.useState(""),[R,_]=o.useState(""),[B,y]=o.useState(""),[p,w]=o.useState(!0),[C,Y]=o.useState(!1),[K,I]=o.useState(null),[L,U]=o.useState("performance");o.useEffect(()=>{T()},[t,s]);async function T(){w(!0),I(null);try{const N=await n.fetchQuery({...Cr({client:V,path:{name:t}}),staleTime:vt});if(i(N),N.connected){const[se,ue,re,le]=await Promise.all([n.fetchQuery({...kr({client:V,path:{name:t}}),staleTime:vt}).catch(()=>null),n.fetchQuery({...fd({client:V,path:{name:t}}),staleTime:vt}).catch(()=>[]),n.fetchQuery({...bd({client:V,path:{name:t}}),staleTime:vt}).catch(()=>[]),N.siteUrl?Promise.resolve([]):n.fetchQuery({...vd({client:V,path:{name:t}}),staleTime:vt}).then(X=>X.sites).catch(()=>[])]);c(se),x(ue),j(re),l(le)}else c(null),x([]),j([]),l([])}catch(N){I(N instanceof Error?N.message:"Failed to load Bing data")}finally{w(!1)}}async function H(){if(R.trim()){I(null);try{const N=await yd(t,R.trim());await ht(n,"bing"),_(""),N.availableSites.length>0&&l(N.availableSites),await T()}catch(N){I(N instanceof Error?N.message:"Failed to connect")}}}async function fe(){try{await jd(t),await ht(n,"bing"),i(null),l([]),c(null),x([]),j([]),b(null),y(""),I(null)}catch(N){I(N instanceof Error?N.message:"Failed to disconnect")}}async function xe(){if(B)try{await Nd(t,B),await ht(n,"bing"),await T()}catch(N){I(N instanceof Error?N.message:"Failed to set site")}}async function Q(){if(v.trim())try{const N=await wd(t,v.trim());await ht(n,"bing"),b(N),x(se=>[N,...se])}catch(N){I(N instanceof Error?N.message:"Inspection failed")}}async function ie(N){Y(!0),I(null);try{const se=await ui(t,{urls:[N]}),{succeeded:ue,failed:re,total:le}=se.summary;Ce({title:"Bing submission requested",detail:re===0?`${ue} URL submitted to Bing.`:`${ue}/${le} submitted successfully, ${re} failed.`,tone:re===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${N}`,dedupeMode:"replace"})}catch(se){const ue=se instanceof Error?se.message:"Submission failed";I(ue),Ce({title:"Bing submission failed",detail:ue,tone:"negative",dedupeKey:`bing:indexing:${t}:${N}`,dedupeMode:"replace"})}finally{Y(!1)}}async function oe(){Y(!0),I(null),Ce({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const N=await ui(t,{allUnindexed:!0}),{succeeded:se,failed:ue,total:re}=N.summary;Ce({title:"Bing submissions requested",detail:ue===0?`${se}/${re} URL${re!==1?"s":""} submitted to Bing.`:`${se}/${re} submitted successfully, ${ue} failed.`,tone:ue===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(N){const se=N instanceof Error?N.message:"Batch submission failed";I(se),Ce({title:"Bing submissions failed",detail:se,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{Y(!1)}}if(p)return e.jsx(pe,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return ne()?e.jsxs(pe,{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(de,{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(pe,{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(de,{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:R,onChange:N=>_(N.target.value),onKeyDown:N=>{N.key==="Enter"&&H()}}),e.jsx(Qe,{size:"sm",disabled:!R.trim(),onClick:Te(H),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"})]})]}),K&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:K})]});if(!a.siteUrl)return e.jsxs(pe,{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(de,{tone:"positive",children:"Connected"}),!ne()&&e.jsx(Qe,{size:"sm",variant:"ghost",onClick:Te(fe),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?Tt(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"}),r.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:B,onChange:N=>y(N.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),r.map(N=>e.jsxs("option",{value:N.url,children:[N.url,N.verified?" (verified)":""]},N.url))]}),!ne()&&e.jsx(Qe,{size:"sm",disabled:!B,onClick:Te(xe),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."})]})]}),K&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:K})]});const z=[{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"}],q=z.find(N=>N.key===L)??z[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(pe,{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(de,{tone:"positive",children:"Connected"}),!ne()&&e.jsx(Qe,{size:"sm",variant:"ghost",onClick:Te(fe),children:"Disconnect"})]})]}),K&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:K}),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?Tt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(pe,{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:q.eyebrow}),e.jsx("h3",{children:q.title})]}),e.jsx("p",{className:"text-xs text-muted",children:m?.lastInspectedAt?`Last inspected ${Tt(m.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:z.map(N=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${L===N.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>U(N.key),children:N.label},N.key))}),L==="coverage"&&m&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Sn,{label:"Indexed",value:m.summary.indexed,tone:"positive"}),e.jsx(Sn,{label:"Not in index",value:m.summary.notIndexed+(m.summary.unknown??0),tone:"negative"}),e.jsx(Sn,{label:"Status unknown",value:m.summary.unknown??0,tone:"neutral"}),e.jsx(Sn,{label:"Coverage",value:`${m.summary.percentage}%`,tone:"neutral"})]}),m.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 (",m.notIndexed.length,")"]}),!ne()&&e.jsx(Qe,{size:"sm",variant:"ghost",disabled:C,onClick:Te(oe),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"}),!ne()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:m.notIndexed.map(N=>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:N.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:N.httpCode??"—"}),!ne()&&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:()=>{ie(N.url)},children:"Submit"})})]},N.id))})]})})]}),(m.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 (",(m.unknown??[]).length,")"]}),!ne()&&e.jsx(Qe,{size:"sm",variant:"ghost",disabled:C,onClick:Te(oe),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"}),!ne()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(m.unknown??[]).map(N=>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:N.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:N.lastCrawledDate?Tt(N.lastCrawledDate):"—"}),!ne()&&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:()=>{ie(N.url)},children:"Submit"})})]},N.id))})]})})]}),m.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",m.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:m.indexed.map(N=>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:N.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:N.lastCrawledDate?Tt(N.lastCrawledDate):"—"})]},N.id))})]})})]})]}),L==="coverage"&&!m&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),L==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!ne()&&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:v,onChange:N=>g(N.target.value),onKeyDown:N=>{N.key==="Enter"&&Q()}}),e.jsx(Qe,{size:"sm",disabled:!v.trim(),onClick:Te(Q),children:"Inspect"})]}),S&&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:S.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:S.inIndex?"text-positive-400":"text-negative-400",children:S.inIndex?"Yes":"No"})," · ","HTTP: ",S.httpCode??"—"," · ","Crawled: ",S.lastCrawledDate??"—"]})]}),h.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:h.map(N=>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:N.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(de,{tone:N.inIndex?"positive":"negative",children:N.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:N.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Tt(N.inspectedAt)})]},N.id))})]})})]}),L==="performance"&&e.jsx("div",{className:"mt-4",children:d.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:wn[As.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:wn[As.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:wn[As.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:wn[As.Position]})]})}),e.jsx("tbody",{children:d.map((N,se)=>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:N.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:N.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:N.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(N.ctr)?N.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:N.averagePosition.toFixed(1)})]},se))})]})})})]})]})}function up({projectName:t}){const s=bs(),[n,a]=o.useState("google"),[i,r]=o.useState(!0),[l,m]=o.useState("idle"),[c,h]=o.useState(null),x=o.useRef(null),[d,j]=o.useState(!1),[S,b]=o.useState(null),[v,g]=o.useState(null),[R,_]=o.useState(!1),[B,y]=o.useState(null),[p,w]=o.useState(null),[C,Y]=o.useState(0);async function K(z=!1){z||r(!0),h(null);try{const[q,N,se]=await Promise.all([s.fetchQuery(jr({client:V})).catch(()=>null),s.fetchQuery({...Ea({client:V,path:{name:t}}),staleTime:vt}).catch(()=>[]),s.fetchQuery({...Cr({client:V,path:{name:t}}),staleTime:vt}).catch(()=>null)]),ue=N.find(X=>X.connectionType==="gsc")??null;j(!!q?.google?.configured),_(!!q?.bing?.configured),b(ue),y(se);const[re,le]=await Promise.all([ue?s.fetchQuery({...gr({client:V,path:{name:t}}),staleTime:vt}).catch(()=>null):Promise.resolve(null),se?.connected?s.fetchQuery({...kr({client:V,path:{name:t}}),staleTime:vt}).catch(()=>null):Promise.resolve(null)]);g(re),w(le)}catch(q){h(q instanceof Error?q.message:"Failed to load search console overview")}finally{r(!1)}}async function I(){if(l!=="idle")return;x.current?.abort();const z=new AbortController;x.current=z;const q=z.signal;m("syncing"),h(null),Ce({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const N=[],se=[];try{async function ue(){if(!S)return;const X=await pd(t);if(!X?.id)return;const D=Date.now()+dr;for(;Date.now()<D;){if(q.aborted||(await new Promise(he=>setTimeout(he,cr)),q.aborted))return;const Z=await Ca(X.id).catch(()=>null);if(!Z)break;if(["completed","failed","cancelled"].includes(Z.status)){Z.status!=="completed"&&N.push(`Google sync ${Z.status}`);return}}se.push("Google sync is still running — search data will appear shortly")}async function re(){if(!B?.connected)return;const X=await gd(t).catch(()=>null);if(!X?.id){N.push("Bing sweep could not be started");return}const D=Date.now()+dr;for(;Date.now()<D;){if(q.aborted||(await new Promise(he=>setTimeout(he,cr)),q.aborted))return;const Z=await Ca(X.id).catch(()=>null);if(!Z)break;if(["completed","failed","cancelled","partial"].includes(Z.status)){Z.status==="failed"?N.push("Bing sweep failed"):Z.status==="partial"&&se.push("Bing sweep finished with some pages unverified");return}}se.push("Bing sweep is still running — coverage will update shortly")}const le=await Promise.allSettled([ue(),re()]);for(const X of le)X.status==="rejected"&&N.push(X.reason instanceof Error?X.reason.message:"Sync failed");if(await Promise.all([ht(s,"gsc"),ht(s,"bing")]),q.aborted)return;if(m("reloading"),await K(!0),Y(X=>X+1),N.length>0){const X=`Partial refresh: ${[...N,...se].join("; ")}`;h(X),Ce({title:"Search coverage partially refreshed",detail:X,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else se.length>0?Ce({title:"Search coverage refresh incomplete",detail:se.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):Ce({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(ue){if(!q.aborted){const re=ue instanceof Error?ue.message:"Refresh failed";h(re),Ce({title:"Search coverage refresh failed",detail:re,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{q.aborted||m("idle")}}o.useEffect(()=>(K(),()=>{x.current?.abort()}),[t]);const L=S?"positive":d?"caution":"negative",U=S?"Connected":d?"Ready to connect":"Needs setup",T=v?`${v.summary.percentage}% indexed`:S?"Awaiting coverage":"No coverage data",H=v?`${v.summary.notIndexed} not indexed${v.summary.deindexed>0?` · ${v.summary.deindexed} deindexed`:""}`:S?"Run sitemap inspection to populate coverage":d?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",fe=B?.connected?"positive":R?"caution":"negative",xe=B?.connected?"Connected":R?"Ready to connect":"Needs setup",Q=p?`${p.summary.percentage}% indexed`:B?.connected?"Awaiting coverage":"No coverage data",ie=p?p.summary.notIndexed+(p.summary.unknown??0):0,oe=p?`${ie} not in index`:B?.connected?"Inspect URLs to populate coverage":R?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(pe,{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:"Search engines"}),e.jsx("h2",{children:"Coverage and performance"})]}),!ne()&&e.jsxs(Qe,{type:"button",variant:"outline",size:"sm",disabled:i||l!=="idle",onClick:()=>{I()},children:[e.jsx(Un,{className:`h-3.5 w-3.5 ${l!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),i?"Loading…":l==="syncing"?"Refreshing Google & Bing…":l==="reloading"?"Reloading workspaces…":"Refresh all"]})]}),c&&e.jsx("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:c}),e.jsx("div",{className:"mt-4 divide-y divide-default border-y border-default",children:[["Google Search Console",i?"Loading…":U,i?"neutral":L,i?"Loading overview…":H,T],["Bing Webmaster Tools",i?"Loading…":xe,i?"neutral":fe,i?"Loading overview…":oe,Q]].map(([z,q,N,se,ue])=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:z}),e.jsx("span",{className:"ml-2 text-secondary",children:se})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"tabular-nums text-secondary",children:ue}),e.jsx(de,{tone:N,children:q})]})]},z))})]}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([z,q])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===z,className:`project-subnav-link ${n===z?"project-subnav-link-active":""}`,onClick:()=>a(z),children:q},z))}),n==="google"&&e.jsx(qu,{projectName:t,refreshNonce:C}),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(dp,{projectName:t,refreshNonce:C})]})]})}function cn({label:t,summary:s,displayValue:n,tooltip:a}){const i=s.value.trim()!==""&&Number.isFinite(Number(s.value)),r=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(Ke,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${od[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[s.value,i?e.jsx("span",{className:"text-faint",children:"%"}):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:`${r}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function mp({model:t,sweepRunning:s}){const n=t.citationMovement,a=t.mentionMovement,i=t.movementComparison,r=t.recentRuns.find(j=>j.kind===Ts["answer-visibility"]),l=j=>j.tone==="positive"?"improved":j.tone==="negative"?"declined":j.gained>0||j.lost>0?"mixed":"steady",m=l(a),c=l(n),h=(()=>{if(s)return"A fresh sweep is running now";if(!i.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(i.querySetChanged)return"Tracking scope changed since the previous sweep";if(m===c)return m==="steady"?"Answer mentions and citation coverage held steady":m==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${m}`;const j=m==="mixed"?"Answer mention movement was mixed":m==="steady"?"Answer mentions held steady":`Answer mentions ${m}`,S=c==="mixed"?"citation movement was mixed":c==="steady"?"citation coverage held steady":`citation coverage ${c}`;return`${j}; ${S}`})(),x=[i.addedQueryCount>0&&`${i.addedQueryCount} ${i.addedQueryCount===1?"query":"queries"} added`,i.removedQueryCount>0&&`${i.removedQueryCount} ${i.removedQueryCount===1?"query":"queries"} removed`].filter(Boolean).join(", "),d=`${i.comparableQueryCount} comparable ${i.comparableQueryCount===1?"query":"queries"}`;return e.jsxs("section",{className:"overview-brief","aria-labelledby":"overview-brief-title",children:[e.jsxs("div",{className:"overview-brief-head",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft",children:["Visibility",e.jsx(Ke,{text:"Each sweep records two independent signals: answer mentions (your brand named in the answer text) and source citations (your domain in the engine's source list). They move separately."})]}),e.jsx("h2",{id:"overview-brief-title",className:"overview-brief-title",children:h})]}),e.jsx("p",{className:"overview-brief-updated",children:r?`Updated ${r.startedAt}`:"No completed sweep"})]}),e.jsxs("div",{className:"overview-brief-grid",children:[e.jsxs("div",{className:"overview-brief-panel overview-brief-coverage",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage now"}),e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(cn,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(cn,{label:"Cited",summary:t.visibilitySummary})]}),t.mentionSummary.providerCoverage&&e.jsxs("p",{className:"overview-brief-note",children:["Partial sweep: ",t.mentionSummary.providerCoverage]})]}),e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Since last sweep"}),i.hasPreviousRun?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"overview-signal-change-list",children:[e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Mentioned"}),a.gained===0&&a.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[a.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",a.gained]}),a.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",a.lost]})]})]}),e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Cited"}),n.gained===0&&n.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[n.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",n.gained]}),n.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",n.lost]})]})]})]}),e.jsx("p",{className:`overview-brief-panel-copy ${i.querySetChanged?"text-caution-400/80":""}`,children:i.querySetChanged?`${x||"Query set changed"} · ${d}.`:`${d}.`})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:"No comparison yet"}),e.jsx("p",{className:"overview-brief-panel-copy",children:"Run another sweep to measure mention and citation movement."})]})]})]})]})}function Sa({id:t,eyebrow:s,title:n,meta:a,defaultOpen:i=!1,children:r}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:i||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"eyebrow eyebrow-soft",children:s}),e.jsx("span",{className:"overview-disclosure-title",children:n})]}),e.jsxs("span",{className:"overview-disclosure-meta",children:[a&&e.jsx("span",{children:a}),e.jsx(zn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:r})]})}function ur({breakdown:t,projectLabel:s}){const n=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(n===0)return null;const a=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...t.perCompetitor.map(r=>({label:r.domain,mentions:r.mentionSnapshots,isYou:!1}))].sort((r,l)=>l.mentions-r.mentions),i=a[0]?.mentions??1;return e.jsx("ul",{className:"mention-share-breakdown-rows",children:a.map(r=>{const l=r.mentions/n*100;return e.jsxs("li",{className:"mention-share-breakdown-row",children:[e.jsx("span",{className:`mention-share-breakdown-label ${r.isYou?"text-heading font-medium":"text-secondary"}`,children:r.label}),e.jsx("div",{className:"mention-share-breakdown-bar",children:e.jsx("div",{className:`mention-share-breakdown-bar-fill ${r.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${Math.max(r.mentions/i*100,2)}%`}})}),e.jsx("span",{className:"mention-share-breakdown-count",children:r.mentions}),e.jsxs("span",{className:"mention-share-breakdown-share",children:[l.toFixed(1),"%"]})]},r.label)})})}function hp({summary:t,projectLabel:s,hasCompetitiveFrame:n}){const a=t.breakdown,i=t.branded,r=a.projectMentionSnapshots+a.competitorMentionSnapshots,l=i.projectMentionSnapshots+i.competitorMentionSnapshots;if(r===0&&l===0)return null;const m=t.scope==="non-brand",c=m?"Mention share breakdown · non-brand queries · latest run":"Mention share breakdown · all tracked queries · latest run",h=m?"Queries that do not contain your name. This is where competitive placement is decided: on a branded query you are named almost always and a competitor cannot be, so counting both in one total would rank you on your own brand recall instead of on your category.":"Branded and non-brand queries could not be separated because this project has no brand name or domain to match against. Set a display name or aliases to split them — until then this figure pools both and is not a competitive read.";if(!n){const x=m?"non-brand answers":"pooled answers";return e.jsxs("div",{className:"mention-share-breakdown",children:[e.jsxs("p",{className:"mention-share-breakdown-title",children:["Brand mention counts · ",m?"non-brand queries":"pooled queries · classification unavailable"," · latest run",e.jsx(Ke,{text:h})]}),e.jsxs("p",{className:"mention-share-breakdown-empty",children:["Your brand was named in ",a.projectMentionSnapshots," of ",a.snapshotsWithAnswerText," ",x,"."," ","Add tracked competitors to calculate mention share."]}),l>0&&e.jsxs("p",{className:"mention-share-breakdown-empty",children:["On branded queries, your brand was named in ",i.projectMentionSnapshots," of ",i.snapshotsWithAnswerText," answers — recognition, not competitive placement."]})]})}return e.jsxs("div",{className:"mention-share-breakdown",children:[e.jsxs("p",{className:"mention-share-breakdown-title",children:[c,e.jsx(Ke,{text:h})]}),r>0?e.jsx(ur,{breakdown:a,projectLabel:s}):e.jsx("p",{className:"mention-share-breakdown-empty",children:"No brand mentions on non-brand queries in this run."}),l>0&&e.jsxs("div",{className:"mention-share-breakdown-branded",children:[e.jsxs("p",{className:"mention-share-breakdown-title",children:["Branded queries · recognition, not placement",e.jsx(Ke,{text:"Queries containing your own name. Counted separately and never pooled with the figure above: these measure whether AI knows you when asked about you by name, not where you place against competitors."})]}),e.jsx(ur,{breakdown:i,projectLabel:s})]})]})}function xp({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:a}=hr(),i=Sr(),[r,l]=o.useState(new Set);if(t.length===0&&s.rows.length===0)return null;const m=g=>{l(R=>{const _=new Set(R);return _.delete(g),_})},c=g=>{l(R=>new Set(R).add(g)),i.mutate({projectName:n,queries:[g]},{onSuccess:()=>{Ce({tone:"positive",title:`Tracking "${g}"`}),m(g)},onError:R=>{Ce({tone:"negative",title:`Could not track "${g}"`,detail:String(R)}),m(g)}})},h=g=>e.jsxs("div",{className:"py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:g.title}),g.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:g.detail}):null]}),e.jsx(de,{tone:g.tone,children:g.actionLabel})]}),g.affectedPhrases.length>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:["Evidence · ",g.affectedPhrases.length," affected ",g.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:g.affectedPhrases.map((R,_)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(ka,{state:R.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:R.query}),R.provider?e.jsx(zs,{provider:R.provider}):null,!ne()&&R.evidenceId?e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(R.evidenceId)},children:"View evidence"}):null]},R.evidenceId||`${g.id}-${_}`))})]}):null]},g.id),x=g=>{const R=r.has(g.query);return e.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:g.query}),e.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:g.reason})]}),ne()?null:e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:R,"aria-label":`Track query "${g.query}"`,onClick:()=>c(g.query),children:R?"Tracking…":"Track"})]},g.query)},d=t.slice(0,1),j=s.rows.slice(0,1),S=t.slice(1),b=s.rows.slice(1),v=S.length+b.length;return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[d.map(h),j.map(x)]}),v>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:[v," more ",v===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[S.map(h),b.map(x)]})]}):null]})}function Rp(t){const{projectName:s}=So({from:"/projects/$projectName"}),a=Qc()?.dashboard.projects.find(j=>j.project.name===s||j.project.id===s)?.project.name??null,i=Re({...Hc({client:V}),enabled:!a}),r=a??i.data?.find(j=>j.name===s||j.id===s)?.name??null,{commandCenter:l,isLoading:m,latestVisibilityRevision:c,refetch:h}=Wc(r),x=!a&&i.isLoading||m;return!r&&!a&&i.isSuccess&&!m?e.jsx("div",{className:"page-container",children:e.jsxs(pe,{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(A,{asChild:!0,children:e.jsx(Xt,{to:"/",children:"Return to overview"})})]})}):!l||x?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(j=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},j))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(j=>e.jsx("div",{className:"skeleton-text-sm w-full"},j))})]})]}):e.jsx(gp,{model:l,refetch:h,latestVisibilityRevision:c,...t})}function pp({items:t,activeTab:s}){const[n,a]=o.useState(!1),i=o.useRef(null);if(o.useEffect(()=>{if(!n)return;const l=c=>{i.current&&!i.current.contains(c.target)&&a(!1)},m=c=>{c.key==="Escape"&&a(!1)};return document.addEventListener("pointerdown",l),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",l),document.removeEventListener("keydown",m)}},[n]),t.length===0)return null;const r=t.some(l=>l.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:i,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${r?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(l=>!l),children:["More",e.jsx(zn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(l=>e.jsx(Xt,{to:l.href,role:"menuitem",className:`project-subnav-menu-item ${l.key===s?"project-subnav-menu-item-active":""}`,"aria-current":l.key===s?"page":void 0,onClick:()=>a(!1),children:l.label},l.key))}):null]})}function gp({tab:t,model:s,refetch:n,latestVisibilityRevision:a}){const i=Co(),r=bs(),{canWrite:l}=wr(),m=o.useMemo(()=>{const k=Yc();return k?Xc(k.projectTabs):void 0},[]),c=Jc(t,m),h=o.useMemo(()=>s.competitors.map(k=>k.domain),[s.competitors]),[x,d]=o.useState(!1),[j,S]=o.useState(!1),b=Sr(),v=ko({strict:!1}),g=v.manageQueries===!0,R=o.useCallback(()=>{i({to:".",replace:!0,search:k=>({...k,siteHealthRunId:void 0})})},[i]),[_,B]=o.useState(g),[y,p]=o.useState(""),[w,C]=o.useState(!1),[Y,K]=o.useState(null),[I,L]=o.useState(!1),[U,T]=o.useState(""),[H,fe]=o.useState(!1),[xe,Q]=o.useState(void 0),[ie,oe]=o.useState(!1),[z,q]=o.useState(null),[N,se]=o.useState(null),[ue,re]=o.useState(!1),le=au(v),[X,D]=o.useState(void 0),[Z,he]=o.useState(void 0),$e=o.useCallback(k=>{D(k.search),k.sort&&he(k.sort),i({to:".",search:be=>({...be,...ru(k)}),replace:!1})},[i]),[st,lt]=o.useState(!1),Fe=s?.visibilityEvidence??[],ee=s?.project.name??"",Be=s?.project.displayName||s?.project.name||ee,Ve=Zc(),ke=Re({...ed({client:V,path:{name:ee}}),enabled:c==="portfolio"&&!!ee,staleTime:0,refetchOnMount:"always"}),Je=Re({...td({client:V,path:{name:ee}}),enabled:!ne()&&!!ee,retry:!1}),Ae=Re({...sd({client:V,path:{name:ee}}),enabled:!ne()&&(c==="portfolio"||c==="overview"||c==="settings")&&!!ee,staleTime:0,refetchOnMount:"always"}),we=Re({...nd({client:V,path:{name:ee}}),enabled:!ne()&&(c==="portfolio"||c==="overview"||c==="settings")&&!!ee,staleTime:0,refetchOnMount:"always"}),O=Je.data,$=O?.enabled&&O.nextRunAt?`Next AI sweep ${new Date(O.nextRunAt).toLocaleString()}`:null,M=Ae.data?.active??null,ye=Ae.data!==void 0,De=new Set(M&&Number(M.plan.schemaVersion)===2?M.plan.groups?.map(k=>k.stableKey)??[]:[]),Ge={...le.scope==="group"&&!!le.groupKey&&ye&&!De.has(le.groupKey)?{scope:"all",queryClass:le.queryClass}:le,...X?{search:X}:{}},He=M===null?null:Number(M.plan.schemaVersion),Ze=M?.revision??0,Pe=ye?`${ee}:${Ze}`:null,Oe=o.useRef(null);o.useEffect(()=>{const k=Oe.current;Pe!==null&&(Oe.current=Pe),iu(k,Pe)&&($e({scope:"all",queryClass:"all"}),lt(!1))},[Pe,$e]);const dt={client:V,path:{name:ee},query:{scope:Ge.scope,...Ge.groupKey?{groupKey:Ge.groupKey}:{},queryClass:Ge.queryClass,...Ge.search?{search:Ge.search}:{},...Z?{sort:Z}:{},limit:50}},ze=Ao({...ad(dt),enabled:c==="overview"&&!!ee&&He===2,initialPageParam:dt,getNextPageParam:(k,be)=>{if(!k.properties.nextCursor)return;const Ne=be[0]?.measurement.displayedRunId;return{path:dt.path,query:{...dt.query,cursor:k.properties.nextCursor,...Ne?{runId:Ne}:{}}}},placeholderData:mr,staleTime:0,refetchOnMount:"always"}),et=ze.data?.pages[0]?.measurement.displayedRunId,Ie=Re({...id({client:V,path:{name:ee},query:{revision:Ze,...et?{runId:et}:{}}}),enabled:c==="overview"&&!!ee&&M!==null&&(He===1||st&&et!==void 0),staleTime:0,refetchOnMount:"always"}),wt=Ae.data!==void 0,xt=ke.data!==void 0,Le=Ae.isPending&&!wt,Me=Ae.isError&&!wt,ct=ke.isPending&&!xt,_e=ke.isError&&!xt,Gt=Ie.data!==void 0,St=Px({activePlanSchemaVersion:we.data?.activeSchemaVersion??He,hasDraft:we.data?.draft!==null&&we.data?.draft!==void 0}),pt=we.data===void 0&&Ae.data===void 0&&(Ae.isLoading||we.isLoading),at=we.data!==void 0?"success":we.isError?"error":"pending",F=o.useMemo(()=>{const k=ze.data?.pages;return k?!Vd(k):!1},[ze.data]),je=o.useMemo(()=>{const k=ze.data?.pages,be=k?.[0],Ne=k?.at(-1);if(!(!be||!Ne||F))return{...be,properties:{...be.properties,items:k.flatMap(P=>P.properties.items),nextCursor:Ne.properties.nextCursor}}},[F,ze.data]),me=o.useMemo(()=>{if(M)return M.plan.schemaVersion===1?Ie.data?Ex(M,Ie.data):void 0:je?zd({overview:je,activePlan:M,sort:Z,report:Ie.data,reportState:je.measurement.displayedRunId===void 0?"ready":Ie.isFetching&&Ie.data===void 0?"loading":Ie.isError&&Ie.data===void 0?"error":Ie.data?"ready":"loading"}):void 0},[M,Ie.data,Ie.isError,Ie.isFetching,je]),ve=He===2?F?"error":ze.isPending?"loading":ze.isError&&me===void 0?"error":"ready":Ie.isPending&&!Gt?"loading":Ie.isError&&!Gt?"error":"ready",jt=(s?.recentRuns??[]).some(k=>k.kind===Ts["answer-visibility"]&&(k.status===di.running||k.status===di.queued)),Lt=o.useMemo(()=>(s?.project.locations??[]).map(k=>k.label),[s?.project.locations]),it=o.useMemo(()=>new Set(Fe.map(k=>k.location??"")),[Fe]),Ct=it.has(""),zt=o.useMemo(()=>[...new Set(Fe.map(k=>k.query))].sort((k,be)=>k.localeCompare(be)),[Fe]),Kt=o.useMemo(()=>{const k=[...it].filter(Boolean);return k.length>1?k:Lt},[it,Lt]);o.useEffect(()=>{if(xe===void 0||xe===""||!ee){se(null),re(!1);return}re(!0),rd(ee,xe,20).then(k=>{se(k),re(!1)}).catch(()=>{se(null),re(!1)})},[xe,ee]);const kt=o.useMemo(()=>{if(!N)return null;const k=new Map;for(const be of N){for(const[Ne,P]of Object.entries(be.providerRuns??{}))k.set(`${be.query}::${Ne}`,P.map(W=>({runId:W.runId,citationState:W.citationState,createdAt:W.createdAt,answerMentioned:W.answerMentioned,visibilityState:W.visibilityState,visibilityTransition:W.visibilityTransition,mentionState:W.mentionState,mentionTransition:W.mentionTransition})));(!be.providerRuns||Object.keys(be.providerRuns).length===0)&&k.set(`${be.query}::`,be.runs.map(Ne=>({runId:Ne.runId,citationState:Ne.citationState,createdAt:Ne.createdAt,answerMentioned:Ne.answerMentioned,visibilityState:Ne.visibilityState,visibilityTransition:Ne.visibilityTransition,mentionState:Ne.mentionState,mentionTransition:Ne.mentionTransition})))}return k},[N]),Qt=o.useMemo(()=>{let k=xe!==void 0?Fe.filter(be=>xe===""?!be.location:be.location===xe):Fe;if(z){const be=z.toLowerCase();k=k.filter(Ne=>Ne.competitorDomains.some(P=>P.toLowerCase()===be))}return kt?k.map(be=>{const Ne=kt.get(`${be.query}::${be.provider}`)??kt.get(`${be.query}::`);return Ne?{...be,runHistory:Ne}:be}):k},[Fe,xe,z,kt]);async function Xe(){try{await Ve.mutateAsync({projectName:ee,projectLabel:Be,sourceAction:"project-run"}),n()}catch{}}async function vs(){S(!0);try{await xd(ee),Ce({title:"Project deleted",detail:`${Be} was removed.`,tone:"positive",dedupeKey:`project:delete:${ee}`,dedupeMode:"drop"}),i({to:"/"}),n()}catch(k){console.error("Failed to delete project:",k)}finally{S(!1)}}async function Nt(){const k=y.split(`
8
+ `).map(be=>be.trim()).filter(Boolean);if(k.length!==0){C(!0);try{await ud(ee,k),n(),p("")}finally{C(!1)}}}async function ys(k){K(k);try{await dd(ee,[k]),n()}catch(be){Ce({title:"Could not remove query",detail:be instanceof Error?be.message:`Failed to remove "${k}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{K(null)}}async function Ht(){const k=U.trim();if(k){fe(!0);try{await ld(ee,[k]),n(),T(""),L(!1)}finally{fe(!1)}}}async function rs(k){const be=s.competitors.find(Ne=>Ne.domain===k);if(!be){Ce({title:"Could not remove competitor",detail:`Could not find ${k} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"});return}try{await cd(ee,be.id),n()}catch(Ne){Ce({title:"Could not remove competitor",detail:Ne instanceof Error?Ne.message:`Failed to remove ${be.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function Jt(k,be){const Ne=await md(k,be);return await r.invalidateQueries({queryKey:Nr({client:V})}),r.setQueryData(hd({client:V,path:{name:k}}),Ne),cp(r,Ne),Ne}const tt=`/projects/${encodeURIComponent(s.project.name)}`,os=[{key:"overview",label:"AI Visibility",href:tt},{key:"search-console",label:"Search Engines",href:`${tt}/search-console`},{key:"activity",label:"Activity",href:`${tt}/activity`},{key:"technical-aeo",label:"Site Health",href:`${tt}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${tt}/conversions`},{key:"local",label:"Local Presence",href:`${tt}/local`},{key:"discovery",label:"Query Discovery",href:`${tt}/discovery`},{key:"backlinks",label:"Backlinks",href:`${tt}/backlinks`}],At=[{key:"report",label:"Report",href:`${tt}/report`},{key:"history",label:"Change History",href:`${tt}/history`}],gt=os.filter(k=>aa(k.key,m)),Zt=At.filter(k=>aa(k.key,m)),rt=aa("settings",m)?{key:"settings",label:"Settings",href:`${tt}/settings`}:null;function Ut(k,be=!1){const Ne=document.getElementById(k);if(!Ne)return;be&&Ne instanceof HTMLDetailsElement&&(Ne.open=!0);const P=window.matchMedia("(prefers-reduced-motion: reduce)").matches;window.requestAnimationFrame(()=>{Ne.scrollIntoView({behavior:P?"auto":"smooth",block:"start"}),(Ne instanceof HTMLDetailsElement?Ne.querySelector("summary"):Ne)?.focus({preventScroll:!0})})}return e.jsxs("div",{className:"page-container",children:[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]}),!ne()&&e.jsxs("div",{className:"tag-row",children:[e.jsx("span",{className:"tag",children:s.project.country}),e.jsx("span",{className:"tag",children:s.project.language.toUpperCase()}),s.project.tags.map(k=>e.jsx("span",{className:"tag",children:k},k))]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:s.dateRangeLabel}),!ne()&&e.jsxs("div",{className:"flex items-center gap-3",children:[$?e.jsx("p",{className:"text-sm text-secondary",children:$}):null,e.jsx(Qe,{type:"button",variant:"outline",disabled:Ve.isPending||jt,onClick:Te(Xe),children:Ve.isPending?"Starting…":jt?"AI sweep running…":"Run AI sweep"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[gt.map(k=>e.jsx(Xt,{to:k.href,className:`project-subnav-link ${k.key===c?"project-subnav-link-active":""}`,"aria-current":k.key===c?"page":void 0,children:k.label},k.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(pp,{items:Zt,activeTab:c}),rt&&e.jsx(Xt,{to:rt.href,className:`project-subnav-link ${c==="settings"?"project-subnav-link-active":""}`,"aria-current":c==="settings"?"page":void 0,children:rt.label},rt.key)]})]}),c==="portfolio"&&!ne()?e.jsx(cx,{projectName:ee,canEdit:l,queries:ke.data??[],isQueryLoading:ct,isQueryError:_e,onRetryQueries:()=>{ke.refetch()},publishedPlan:M,onCreateQueries:async k=>(await b.mutateAsync({projectName:ee,queries:[...k]}),(await ke.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{i({to:"/projects/$projectName",params:{projectName:ee},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([we.refetch(),Ae.refetch()]).finally(()=>{i({to:"/projects/$projectName",params:{projectName:ee}})})}},ee):c==="overview"?pt?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"})]}):e.jsxs(e.Fragment,{children:[Me?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(A,{type:"button",size:"sm",variant:"outline",onClick:()=>{Ae.refetch()},children:"Retry setup check"})]}):null,e.jsx(Ix,{mode:St,canEdit:l&&!ne()&&!Le&&!Me,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(zm,{projectName:s.project.name,competitorDomains:h,analyticsRevision:a})}),e.jsx(mp,{model:s,sweepRunning:jt}),e.jsx(xp,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:s.project.name}),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:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[s.competitors.length," tracked"]}),!ne()&&e.jsx(Qe,{type:"button",variant:"outline",size:"sm",onClick:()=>L(!I),children:I?"Cancel":"+ Add competitor"})]})]}),e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(cn,{label:"Mention share",summary:s.mentionShareSummary,tooltip:s.mentionShareSummary.tooltip||(s.mentionShareSummary.scope==="non-brand"?"Of the brand mentions in answer text on your non-brand queries (you + tracked competitors), the percentage that were you. Branded queries are counted separately below.":"Classification is unavailable, so all tracked queries remain pooled. This is not a competitive category read.")}),e.jsx(cn,{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-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was mentioned in the answer but your brand was not."}),e.jsx(cn,{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-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was cited as a source but you were not."})]}),e.jsx(hp,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,hasCompetitiveFrame:s.competitors.length>0})]}),I&&e.jsxs("div",{className:"mt-4 mb-3 flex gap-2 rounded-lg border border-base bg-bg-elevated/40 p-3",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:"competitor.com",value:U,onChange:k=>T(k.target.value),onKeyDown:k=>{k.key==="Enter"&&Ht()}}),e.jsx(Qe,{type:"button",size:"sm",disabled:!U.trim()||H,onClick:Te(Ht),children:H?"Adding...":"Add"})]}),s.competitors.length>0&&e.jsxs("details",{className:"inline-disclosure mt-4",children:[e.jsx("summary",{children:"Review tracked competitors"}),e.jsx("div",{className:"mt-3",children:e.jsx(gu,{competitors:s.competitors,onSelectCompetitor:k=>{q(k),Ut("evidence-section",!0)},onRemoveCompetitor:ne()?void 0:k=>{rs(k)},activeFilter:z})})]})]}),e.jsxs(Sa,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:ne(),children:[!ne()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(Qe,{type:"button",variant:"outline",size:"sm",onClick:()=>B(!_),children:_?"Done":"Manage queries"})}),!ne()&&_&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[zt.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:zt.map(k=>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:k,children:k}),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 ${k}`,title:`Stop tracking "${k}"`,disabled:Y!==null,onClick:()=>{ys(k)},children:Y===k?"Removing…":"Remove"})]},k))}):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:y,onChange:k=>p(k.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[y.split(`
9
+ `).filter(k=>k.trim()).length," to add"]}),e.jsx(Qe,{type:"button",size:"sm",disabled:!y.trim()||w,onClick:Te(Nt),children:w?"Adding...":"Add queries"})]})]}),s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${xe===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":xe===void 0,onClick:()=>{Q(void 0)},children:"All locations"}),s.project.locations.map(k=>e.jsx("button",{className:`filter-chip ${xe===k.label?"filter-chip-active":""}`,type:"button","aria-pressed":xe===k.label,onClick:()=>{Q(k.label),oe(!1)},children:k.label},k.label)),Ct&&e.jsx("button",{className:`filter-chip ${xe===""?"filter-chip-active":""}`,type:"button","aria-pressed":xe==="",onClick:()=>{Q(""),oe(!1)},children:"No location"}),Kt.length>1&&xe===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${ie?"filter-chip-active":""}`,type:"button","aria-pressed":ie,onClick:()=>oe(k=>!k),title:"Side-by-side location comparison",children:"Compare"})]}),z&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-negative-900/40 bg-negative-950/20 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-negative-400",children:"Competitor filter"}),e.jsxs("span",{className:"text-sm text-strong",children:["Showing queries where ",e.jsx("span",{className:"font-semibold",children:z})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-secondary hover:text-strong",onClick:()=>q(null),children:"Clear filter ×"})]}),e.jsx(mu,{evidence:Qt,compareLocations:ie})]}),e.jsxs(Sa,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:ne(),children:[e.jsx(dm,{projectName:s.project.name}),s.providerScores.length>1&&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:"Model breakdown"}),e.jsxs("h2",{children:["Citation rate by model ",e.jsx(Ke,{text:"Per-model citation rate in the latest sweep. The same query set can perform differently across engines."})]})]})}),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",{scope:"col",children:"Model"}),e.jsx("th",{scope:"col",children:"Citation rate"}),e.jsx("th",{scope:"col",children:"Cited queries"})]})}),e.jsx("tbody",{children:s.providerScores.map(k=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(zs,{provider:k.provider}),k.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:k.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[k.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[k.cited," of ",k.total]})]},`${k.provider}::${k.model??"unknown"}`))})]})})]})]}),!ne()&&e.jsx(Sa,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(k=>e.jsx(Sd,{run:k},k.id))})})]}),report:me,reportState:ve,onOpenSetup:ne()?void 0:()=>{i({to:"/projects/$projectName/portfolio",params:{projectName:ee}})},onRetryReport:()=>{He===2?Promise.all([ze.refetch(),Ie.refetch()]):Ie.refetch()},onViewChange:k=>{$e({scope:k.scope,...k.groupKey?{groupKey:k.groupKey}:{},queryClass:k.queryClass,...k.search?.trim()?{search:k.search.trim()}:{}})},onLoadMore:k=>{k===je?.properties.nextCursor&&ze.fetchNextPage()},onPropertyExpand:()=>{st&&Ie.isError&&Ie.refetch(),lt(!0)},onRetryEvidence:()=>{Ie.refetch()},renderPropertyLink:He===2&&!ne()?({id:k,name:be})=>e.jsx(Xt,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:ee,targetKey:k},className:"text-link hover:underline",children:be}):void 0,isViewLoading:ze.isPlaceholderData,isLoadingMore:ze.isFetchingNextPage,isLoadMoreError:ze.isFetchNextPageError,viewSearch:Ge.search??""},`${ee}:${Ze}`)]}):c==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(sp,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(k,be)=>{await Jt(k,be)},onRefresh:()=>{n()}}),e.jsx(ap,{project:s.project,onSave:async k=>{await Jt(s.project.name,k)}}),l&&!ne()?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."}),at==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):at==="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(A,{type:"button",size:"sm",variant:"outline",onClick:()=>{we.refetch()},children:"Retry"})]}):e.jsx(A,{type:"button",variant:"outline",onClick:()=>{i({to:"/projects/$projectName/portfolio",params:{projectName:ee}})},children:ho(St.setupAction)})]}):null,e.jsx(rp,{projectName:s.project.name}),e.jsx(lp,{projectName:s.project.name}),l&&!ne()?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."}),x?e.jsxs(pe,{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(A,{type:"button",variant:"destructive",disabled:j,onClick:Te(vs),children:j?"Deleting...":"Yes, delete project"}),e.jsx(A,{type:"button",variant:"outline",disabled:j,onClick:()=>d(!1),children:"Cancel"})]})]}):e.jsxs(Qe,{type:"button",variant:"outline",onClick:()=>d(!0),children:[e.jsx(Dd,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):c==="report"?e.jsx(Fx,{projectName:s.project.name}):c==="discovery"?e.jsx(eh,{projectName:ee}):c==="technical-aeo"?e.jsx(kd,{projectName:s.project.name,projectId:s.project.id,initialRunId:v.siteHealthRunId,onReleaseInitialRun:R}):c==="conversions"?e.jsx(Ch,{projectId:s.project.id,projectName:s.project.name},s.project.id):c==="history"?e.jsx(rh,{projectName:s.project.name}):c==="activity"?e.jsx(Su,{projectName:s.project.name}):c==="backlinks"?e.jsx(cm,{projectName:s.project.name}):c==="local"?e.jsx(Ou,{projectName:s.project.name,projectId:s.project.id}):c==="search-console"?e.jsx(up,{projectName:s.project.name}):null]})}export{Rp as ProjectPage,cp as patchProjectDashboardCache};