@canonry/canonry 7.7.0 → 7.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/assets/agent-workspace/skills/aero/SKILL.md +43 -17
  2. package/assets/agent-workspace/skills/aero/references/agent-operations.md +4 -1
  3. package/assets/agent-workspace/skills/aero/references/portfolio-analysis.md +15 -7
  4. package/assets/agent-workspace/skills/canonry/SKILL.md +4 -1
  5. package/assets/assets/{AuditHistoryPanel-qumC-I56.js → AuditHistoryPanel-D0nukTwD.js} +1 -1
  6. package/assets/assets/{BacklinksPage-BNyYcY5w.js → BacklinksPage-B525ij0g.js} +1 -1
  7. package/assets/assets/{HistoryPage-CQfOM6NA.js → HistoryPage-DvupqQDM.js} +1 -1
  8. package/assets/assets/{MeasurementPropertyPage-D0LTQHL7.js → MeasurementPropertyPage-CwDbi1XN.js} +1 -1
  9. package/assets/assets/{ProjectPage-QQErJAT8.js → ProjectPage-DmZZ2C7q.js} +1 -1
  10. package/assets/assets/{RunsPage-CniAGDVF.js → RunsPage-DHTvHcGm.js} +1 -1
  11. package/assets/assets/{SettingsPage-BPsrE4ao.js → SettingsPage-BwAFzB7A.js} +1 -1
  12. package/assets/assets/SiteHealthSection-hi54eSIt.js +4 -0
  13. package/assets/assets/{TrafficPage-DXKk92zy.js → TrafficPage-BOcXASAM.js} +1 -1
  14. package/assets/assets/{TrafficSourceDetailPage-4POLIA_c.js → TrafficSourceDetailPage-DTq0cN6g.js} +1 -1
  15. package/assets/assets/{extract-error-message-C6t0hB2w.js → extract-error-message-BOTDI6g5.js} +1 -1
  16. package/assets/assets/index-BLJfGYUw.js +86 -0
  17. package/assets/assets/{index-HWSQgVum.css → index-Rcbm8bK1.css} +1 -1
  18. package/assets/assets/{react-sigma_core.esm.min-D7GjzWYV.js → react-sigma_core.esm.min-BEBdJNtD.js} +1 -1
  19. package/assets/assets/{v2-overview-adapter-ChE5k_dV.js → v2-overview-adapter-BPZ-H3VY.js} +1 -1
  20. package/assets/index.html +2 -2
  21. package/dist/{chunk-ODEAE5T5.js → chunk-AAMKTL6B.js} +3 -3
  22. package/dist/{chunk-WJJTKZKK.js → chunk-DO7XPDG5.js} +5977 -5743
  23. package/dist/{chunk-75RSUOHZ.js → chunk-KRFTA4I7.js} +1126 -475
  24. package/dist/{chunk-WBTYXLXL.js → chunk-LO56QXPO.js} +5 -4
  25. package/dist/{chunk-LFUSODDL.js → chunk-NU62UT2S.js} +444 -158
  26. package/dist/{chunk-JJXTHJ4E.js → chunk-T2V2PESH.js} +4 -3
  27. package/dist/{chunk-3DB43KT2.js → chunk-ZLB7WX5D.js} +26 -33
  28. package/dist/cli.js +67 -28
  29. package/dist/{demo-server-UWBPY743.js → demo-server-KDMG3APY.js} +4 -4
  30. package/dist/index.js +6 -6
  31. package/dist/{intelligence-service-LOH37GPJ.js → intelligence-service-LAXJFE3U.js} +2 -2
  32. package/dist/mcp.js +4 -4
  33. package/package.json +9 -9
  34. package/assets/assets/SiteHealthSection-zW3ykBCu.js +0 -4
  35. package/assets/assets/index-DBQ-8jB1.js +0 -86
@@ -1,4 +1,4 @@
1
- import{j as e,r as o,t as nd,u as qe,L as Ts,h as ms,o as Ot,B as wi,C as Tl,D as ad,k as rd,l as id}from"./vendor-tanstack-ZXXkndVj.js";import{T as je,t as od,a as ld,s as Si,M as xa,I as Ge,f as tt,R as Wn,m as cd,B as T,c as dd,b as ud,d as md,S as Ml,e as Ll,u as Ci,g as hd,n as Un,C as pd,h as $l,i as ql,j as ki,k as xd,l as gd,o as fd,p as bn,q as El,r as Dl,v as ve,w as er,x as Y,y as ie,z as Ms,A as Tt,D as Je,E as yd,F as bd,G as vd,H as Ol,J as jd,K as Nd,L as rn,N as vn,O as wd,P as Sd,Q as Tn,U as Ht,V as Cd,W as kd,X as eo,Y as Fl,Z as zt,_ as Ai,$ as Ad,a0 as Rd,a1 as Pd,a2 as Id,a3 as to,a4 as Fe,a5 as Td,a6 as Md,a7 as Nr,a8 as Ld,a9 as $d,aa as qd,ab as Ed,ac as Dd,ad as Od,ae as Fd,af as Kd,ag as Gd,ah as _d,ai as Ud,aj as Bd,ak as Vd,al as Qd,am as zd,an as Kl,ao as _s,ap as Hd,aq as Gl,ar,as as Wd,at as We,au as Yd,av as Jd,aw as Xd,ax as rr,ay as Zd,az as eu,aA as tu,aB as Bn,aC as su,aD as nu,aE as au,aF as _l,aG as ti,aH as ru,aI as Ri,aJ as iu,aK as Vn,aL as cs,aM as hr,aN as Is,aO as Ul,aP as tr,aQ as si,aR as ou,aS as so,aT as Bl,aU as ga,aV as lu,aW as Vl,aX as Ql,aY as cu,aZ as zl,a_ as mn,a$ as Pi,b0 as wr,b1 as du,b2 as uu,b3 as mu,b4 as hu,b5 as pu,b6 as ma,b7 as no,b8 as $a,b9 as Sr,ba as xu,bb as gu,bc as ao,bd as Cr,be as jn,bf as Hl,bg as Ii,bh as Wl,bi as fu,bj as yu,bk as ro,bl as bu,bm as vu,bn as ju,bo as Nu,bp as wu,bq as Su,br as Cu,bs as ku,bt as Au,bu as Ru,bv as Pu,bw as Iu,bx as Tu,by as Mu,bz as Lu,bA as $u,bB as qu,bC as Eu,bD as Du,bE as Ou,bF as Fu,bG as Ku,bH as Gu,bI as _u,bJ as Uu,bK as Bu,bL as Vu,bM as Qu,bN as Ss,bO as zu,bP as bt,bQ as Hu,bR as Wu,bS as Yu,bT as Ju,bU as Xu,bV as Zu,bW as em,bX as tm,bY as sm,bZ as nm,b_ as am,b$ as rm,c0 as im,c1 as om,c2 as lm,c3 as cm,c4 as dm,c5 as um,c6 as mm,c7 as hm,c8 as pm,c9 as xm,ca as io,cb as gm,cc as fm,cd as ym,ce as bm,cf as vm,cg as Yl,ch as jm,ci as Nm,cj as wm,ck as Jl,cl as kr,cm as Sm,cn as Cm,co as oo,cp as km,cq as Am,cr as Rm,cs as Pm,ct as Im,cu as Tm,cv as Mm,cw as Xl,cx as Lm,cy as Zl,cz as ec,cA as tc,cB as sc,cC as $m,cD as qm,cE as Em,cF as Dm,cG as Om,cH as Fm,cI as Km,cJ as lo,cK as Gm,cL as _m,cM as Um,cN as Bm,cO as Vm,cP as Qm,cQ as zm,cR as Hm,cS as co,cT as Wm,cU as Ym,cV as Jm,cW as Xm,cX as Zm,cY as eh,cZ as th,c_ as sh,c$ as nh,d0 as ah,d1 as rh,d2 as ih,d3 as Ar,d4 as oh,d5 as lh,d6 as ch,d7 as dh,d8 as uh,d9 as mh,da as hh,db as ph,dc as xh,dd as gh,de as fh,df as yh,dg as bh,dh as vh,di as jh,dj as nc,dk as Nh,dl as wh,dm as Sh,dn as Ch,dp as kh,dq as Ah,dr as qa,ds as Rh,dt as Ph,du as Ih,dv as uo,dw as Th}from"./index-DBQ-8jB1.js";import{u as Nn,D as Zs,a as Ks,b as ac,M as sr,c as Ds,F as Mh,P as rc,s as Lh,p as $h,S as qh}from"./SiteHealthSection-zW3ykBCu.js";import{A as Ti,a as Eh,b as Dh,c as Oh,V as mo}from"./v2-overview-adapter-ChE5k_dV.js";import{o as Ut,C as fa,f as wn,a as ds,b as _t,c as Pt,d as es,e as lt,g as us,h as Yn,M as ic,i as Fh,j as wa,p as Kh,k as Gh,l as ho,m as _h}from"./ChartPrimitives-CYlrwLJs.js";import{g as oc,y as ya,U as Uh,z as Bh,L as Vh,D as Qh,l as zh,j as ir,I as Hh,J as Wh,C as Qn,X as Yh,e as Jh,K as Xh,P as Zh,N as ep,O as lc}from"./vendor-lucide-N6vOpZmh.js";import{u as tp,a as sp,b as np,t as ap,e as rp,c as Nt}from"./extract-error-message-C6t0hB2w.js";import{R as en,C as tn,a as ba,X as sn,Y as nn,T as an,b as ni,L as or,A as Js,d as Fs,e as ip}from"./vendor-recharts-D-cUuLZo.js";import{A as op}from"./AuditHistoryPanel-qumC-I56.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B4giJcws.js";import"./vendor-yaml-GWJz5H2G.js";const lp=1e6;function cp(t,s="USD",n={}){const a=new Intl.NumberFormat("en-US",{style:"currency",currency:s,...n.fractionDigits===void 0?{}:{minimumFractionDigits:n.fractionDigits,maximumFractionDigits:n.fractionDigits}}),r=a.format(t/lp);if(n.showTinyAsLessThan&&t>0&&r===a.format(0)){const l=10**-(a.resolvedOptions().maximumFractionDigits??0);return`<${a.format(l)}`}return r}const Ea={projectWide:"Project-wide",projectWideHelp:"This tab covers the whole project. Your measurement scope stays selected for AI Visibility and Queries.",savedScopeUnavailable:"Saved scope unavailable"};function cc(t,s){return t!=="viewer"||s!==null}function dc(t,s){return t==="research"&&!s?"tracked":t}function uc(t,s){return s.measurementScope==="project"?!1:s.measurementScopeKey?!(s.measurementScope==="group"?t.groups:s.measurementScope==="property"?t.targets:t.markets).some(a=>a.stableKey===s.measurementScopeKey):!0}function ai(t,s){return t.find(n=>n.kind===s.measurementScope&&(n.kind==="project"||n.id===s.measurementScopeKey))}function dp(t){return t.measurementScope!=="project"||t.marketKey!==void 0}function up(t){if(t.embedded)return{kind:"none"};const{tab:s}=t;switch(s){case"overview":return t.surface==="advanced-overview"?{kind:"report-picker"}:{kind:"none"};case"queries":case"discovery":{const{tracking:n}=t;return t.queryWorkspace!=="tracked"||n.state!=="ready"||n.mode!=="advanced"?{kind:"none"}:n.scopeUnavailable?{kind:"scope-unavailable"}:{kind:"tracking-picker"}}case"search-console":case"activity":case"technical-aeo":case"conversions":case"local":case"backlinks":case"history":return t.scoped&&t.surface==="advanced-overview"?{kind:"project-wide"}:{kind:"none"};case"settings":case"portfolio":return{kind:"none"};default:return s}}function ri({state:t,label:s,className:n}){return e.jsx(je,{tone:ld(t),className:n,children:s??od(t)})}const hn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],po={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},mp={"non-brand":"On queries that do not contain your name: of the brand names written into the answer text, the share that were yours. Branded queries are scored separately because you are named on nearly all of them and a competitor cannot be.",branded:"On queries that contain your name: of the brand names written into the answer text, the share that were yours. This is recognition, not competitive placement, and it is never pooled with the non-brand figure.",pooled:"This project has no brand name or domain to match on, so branded and non-brand queries could not be separated. This figure pools both and is not a competitive read. Set a display name or aliases to split them."},hp="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function pp(t,s){return s.unavailable?{headline:"No data",numeric:!1,detail:"could not load, refresh to retry",showRows:!1}:s.noRun?{headline:"No data",numeric:!1,detail:"no sweep has run yet",showRows:!1}:t.snapshotsTotal===0?s.otherClassHasData?{headline:"No non-brand queries",numeric:!1,detail:"every tracked query names your brand",showRows:!1}:{headline:"No queries",numeric:!1,detail:"none tracked",showRows:!1}:t.snapshotsWithAnswerText===0?{headline:"No answers",numeric:!1,detail:"no answer text in this run",showRows:!1}:s.hasCompetitors?t.combinedMentionSnapshots===0||t.score===null?{headline:"No mentions",numeric:!1,detail:`no brand named in ${t.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:tt(t.score,Wn.percent),numeric:!0,detail:`${t.projectMentionSnapshots} of ${t.combinedMentionSnapshots} brand mentions`,showRows:!0}:{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1}}function xp({breakdown:t,projectLabel:s}){if(t.ranking.length===0)return null;const n=t.ranking.map(a=>({label:a.kind==="project"?`${s} (you)`:a.domain??"",mentions:a.mentionSnapshots,share:a.share,isYou:a.kind==="project"}));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Ge,{text:hp})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:n.map(a=>e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${a.isYou?"text-heading font-medium":"text-secondary"}`,children:a.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${a.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${a.share>0?Math.max(a.share*100,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:a.mentions}),e.jsx("td",{className:"mention-share-share",children:tt(a.share)})]},a.label))})]})}function gp({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=o.useState("non-brand"),l=o.useId(),i=t.scope==="pooled",c=!i&&t.branded.snapshotsTotal>0,d=c?a:"non-brand",m=i?"pooled":d,u=d==="branded"?t.branded:t.breakdown,p=d==="branded"?t.breakdown:t.branded,x=pp(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:p.snapshotsTotal>0}),h=Si(x.headline),y=m==="non-brand"?xa[t.tone]:"text-secondary";function f(b){const j=hn.findIndex(P=>P.value===d);let A=null;b.key==="ArrowRight"||b.key==="ArrowDown"?A=(j+1)%hn.length:b.key==="ArrowLeft"||b.key==="ArrowUp"?A=(j-1+hn.length)%hn.length:b.key==="Home"?A=0:b.key==="End"&&(A=hn.length-1),A!==null&&(b.preventDefault(),r(hn[A].value),b.currentTarget.querySelectorAll('[role="radio"]')[A]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:l,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Ge,{text:mp[m]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":l,className:"segmented flex-wrap",onKeyDown:f,children:hn.map(b=>{const j=b.value===d;return e.jsx("button",{type:"button",role:"radio","aria-checked":j,tabIndex:j?0:-1,onClick:()=>r(b.value),className:`segmented-option min-h-11 ${j?"segmented-option-active":""}`,children:b.label},b.value)})}):e.jsx("span",{className:"mention-share-class",children:po[m]})]}),x.numeric?e.jsxs("p",{className:`mention-share-value ${y}`,children:[h.figure,h.sign?e.jsx("span",{className:"text-faint",children:h.sign}):null]}):e.jsx("p",{className:"mention-share-value-text",children:x.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:po[m]}),` · ${x.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),x.showRows&&e.jsx(xp,{breakdown:u,projectLabel:s})]})}function Sa({items:t,label:s="Details"}){return t.length===0?null:e.jsxs("details",{className:"av-details",children:[e.jsx("summary",{children:s}),e.jsx("ul",{className:"av-details-list",children:t.map((n,a)=>e.jsx("li",{children:n},a))})]})}function ha({options:t,value:s,onChange:n,label:a,className:r=""}){const l=o.useId();function i(c){const d=t.findIndex(u=>u.value===s);let m=null;c.key==="ArrowRight"||c.key==="ArrowDown"?m=(d+1)%t.length:c.key==="ArrowLeft"||c.key==="ArrowUp"?m=(d-1+t.length)%t.length:c.key==="Home"?m=0:c.key==="End"&&(m=t.length-1),m!==null&&(c.preventDefault(),n(t[m].value),c.currentTarget.querySelectorAll('[role="radio"]')[m].focus())}return e.jsx("div",{role:"radiogroup","aria-label":a,className:`segmented ${r}`.trim(),onKeyDown:i,children:t.map(c=>{const d=c.value===s,m=c.description?`${l}-${c.value}`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button",role:"radio","aria-checked":d,"aria-describedby":m,tabIndex:d?0:-1,onClick:()=>n(c.value),className:`segmented-option pointer-coarse:min-h-11 ${d?"segmented-option-active":""}`,children:c.label}),c.description?e.jsx("span",{id:m,className:"sr-only",children:c.description}):null]},c.value)})})}const fp=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],yp={"7d":"last 7 days","30d":"last 30 days","90d":"last 90 days",all:"all sweeps"},bp={"non-brand":"Non-brand",branded:"Branded",all:"All queries"},vp={"non-brand":"Counts queries that do not name your brand.",branded:"Counts queries that name your brand.",all:"Counts every tracked query, so mention share is not shown."},jp={"select-query-class":"no query type selected","no-competitors":"no competitors configured","insufficient-observed":"needs 3 observed competitors, each named in 3 or more answers","no-answers":"no answer text","no-mentions":"no brands named",unavailable:"competitor data unavailable"},xo="Mention share: your share of the brand mentions in these answers, each brand counted at most once per answer. Named: answers that name the brand. Cited: answers whose sources link to its site. Company names in answers are observations. Only competitor sites count toward mention share.",ii=100;function Np(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function mc(t){return t==="unavailable"?"Unavailable":"Not measured"}function oi(t){switch(t){case"own":return"Your domain";case"direct-competitor":return"Competitor";case"ota-aggregator":return"Aggregator";case"editorial-media":return"Editorial";case"other":return"Other";default:return"Unclassified"}}function Cs(t,s,n){return t===1?s:n}function hc(t){const s=t.label.trim(),n=dd(t.domain);return s&&s.toLowerCase()!==t.domain.toLowerCase()&&s.toLowerCase()!==n.toLowerCase()?s:null}function pc({row:t,aliases:s=[]}){const n=hc(t),a=s.length>0?e.jsxs("span",{className:"av-of block",children:["Also named ",s.join(", ")]}):null;return n?e.jsxs(e.Fragment,{children:[n," ",e.jsx("span",{className:"av-of",children:t.domain}),a]}):e.jsxs(e.Fragment,{children:[t.domain,a]})}function wp(t){const s=hc(t);return s?`${s} (${t.domain})`:t.domain}function go(t,s){return s&&t>=ii?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:t})]}):e.jsx("strong",{children:t})}function li({action:t,domain:s,mutation:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(null);async function c(){if(!a){r(!0),i(null);try{await n(s)===!1&&i(`Could not ${t} competitor. Try again.`)}catch{i(`Could not ${t} competitor. Try again.`)}finally{r(!1)}}}return e.jsxs(e.Fragment,{children:[e.jsxs(T,{type:"button",size:"sm",variant:"outline",disabled:a,onClick:()=>{c()},children:[t==="pin"?"Pin":"Unpin"," ",e.jsx("span",{className:"sr-only",children:s})]}),l?e.jsx("span",{role:"alert",className:"sr-only",children:l}):null]})}function Sp({urls:t}){return e.jsxs("details",{className:"inline-disclosure text-left text-xs text-secondary",children:[e.jsx("summary",{children:"Source URLs"}),e.jsx("ul",{className:"mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal",children:t.map(s=>e.jsx("li",{className:"break-all",children:s},s))})]})}function Dn({count:t,of:s,state:n,toneClass:a}){return n!=="measured"?e.jsx("span",{className:"text-[13px] text-secondary",children:mc(n)}):e.jsxs("span",{className:"whitespace-nowrap",children:[e.jsx("span",{className:`av-n-sm ${a}`,children:t})," ",e.jsxs("span",{className:"av-of",children:["of ",s]})]})}function fo({percent:t,state:s,toneClass:n}){if(s!=="measured"||t===null)return e.jsx("span",{className:"text-[13px] text-secondary",children:s==="measured"?"Not measured":mc(s)});const{figure:a,sign:r}=Si(tt(t,Wn.percent));return e.jsxs("span",{className:`av-n-sm ${n}`,children:[a,r?e.jsx("span",{className:"text-faint",children:r}):null]})}function Cp({rows:t,state:s,named:n,cited:a,onPin:r}){return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":"Other competitors seen",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Competitor"}),e.jsx("th",{scope:"col",children:"Type"}),e.jsx("th",{scope:"col",children:"Named"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(pc,{row:l})}),e.jsx("td",{className:"text-[13px] text-secondary",children:oi(l.surfaceClass)}),e.jsx("td",{children:e.jsx(Dn,{count:l.mentionCount,of:n,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Dn,{count:l.citationCount,of:a,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex min-w-max items-start gap-2",children:[s==="measured"&&l.sampleUrls.length>0?e.jsx(Sp,{urls:l.sampleUrls}):null,r?e.jsx(li,{action:"pin",domain:l.domain,mutation:r}):null]})})]},l.domain))})]})})}function kp({onAddCompetitor:t}){const s=o.useId(),[n,a]=o.useState(""),[r,l]=o.useState(!1),[i,c]=o.useState(null);async function d(){const m=n.trim();if(!(!m||r)){l(!0),c(null);try{if(await t(m)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("Could not add competitor. Try again.")}finally{l(!1)}}}return e.jsxs("details",{className:"inline-disclosure",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:m=>{m.preventDefault(),d()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:m=>a(m.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(T,{type:"submit",size:"sm",className:"min-h-10",disabled:r||!n.trim(),children:r?"Adding…":"Add competitor"}),i?e.jsx("p",{role:"alert",className:"w-full text-sm text-negative",children:i}):null]})]})}function Ap({window:t,landscape:s,pinnedFallback:n=[],competitorAliases:a={},canWrite:r,isEmbed:l,onWindowChange:i,onPin:c,onUnpin:d,onAddCompetitor:m,error:u,onRetry:p,isLoading:x=!1,scopeLabel:h}){const y=o.useId(),f=r&&!l,b=s?.pinned??n,j=s?.observed??[],A=s?.otherSources??[],P=s?.evidence,C=Np(s),g=s?.basis==="observed",v=g?j.filter(k=>k.shareOfVoice!==null):b,S=g?j.filter(k=>k.shareOfVoice===null):j,L=s?.filters.queryClass,M=s?.marketState?.draft?.pendingCompetitorDomains.length??0,w=s?.truncated===!0,U=P?.answeredResults??0,F=P?P.answeredResults+P.missingAnswerTextResults:0,z=L==="non-brand"&&s?.project.shareOfVoice!=null?xa[cd(s.project.shareOfVoice)]:"text-primary",_=k=>f?k.pinned?d?e.jsx(li,{action:"unpin",domain:k.domain,mutation:d}):null:c?e.jsx(li,{action:"pin",domain:k.domain,mutation:c}):null:null,B=v.some(k=>_(k)!==null),te=[h,L?bp[L]:null,yp[t],s?.basis?g?"observed competitors only":"tracked competitors only":null].filter(Boolean).join(" · "),O=[];if(s&&!g&&v.length===0&&O.push({key:"no-pins",text:"No pinned competitors."}),s?.reason&&O.push({key:"reason",text:`Mention share: ${jp[s.reason]}`}),s&&S.length>0){const k=S.length;O.push({key:"others",text:w&&k>=ii?`${ii} or more other competitors seen`:`${k} other ${Cs(k,"competitor","competitors")} seen`})}M>0&&O.push({key:"pending",text:`${s?.scope.kind==="all-markets"?"Pending publication across markets":"Pending publication"}: ${M} ${Cs(M,"competitor","competitors")}`});const V=[P&&P.missingAnswerTextResults>0?"Answer data incomplete":null,P&&P.incompleteSourceResults>0?"Citation data incomplete":null].filter(Boolean);V.length>0&&O.push({key:"incomplete",text:V.join(" · "),className:xa.caution});const Q=[];if(s&&P){Q.push(s.runCount!==void 0?e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:s.runCount})," ",Cs(s.runCount,"sweep","sweeps"),", ",e.jsx("strong",{children:P.answeredResults})," ",Cs(P.answeredResults,"answer","answers")]}):e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:P.answeredResults})," ",Cs(P.answeredResults,"answer","answers")]})),!s.reason&&C==="measured"&&s.project.shareOfVoice!==null&&Q.push(e.jsxs(e.Fragment,{children:["Mention share: you ",e.jsx("strong",{children:s.project.mentionCount}),v.map(H=>e.jsxs(nd.Fragment,{children:[", ",H.domain," ",e.jsx("strong",{children:H.mentionCount})]},H.domain))," ","of ",e.jsx("strong",{children:P.mentionCredits})," ",g?"brand mentions":"tracked-brand mentions"]})),Q.push(e.jsxs(e.Fragment,{children:["Answers with source links: ",e.jsx("strong",{children:P.sourceResults})]})),S.length===0&&Q.push("Other competitors seen: none"),P.missingAnswerTextResults>0&&Q.push(e.jsxs(e.Fragment,{children:["No answer text: ",e.jsx("strong",{children:P.missingAnswerTextResults})," ",Cs(P.missingAnswerTextResults,"answer","answers"),", left out of mention share"]})),P.incompleteSourceResults>0&&Q.push(e.jsxs(e.Fragment,{children:["Incomplete source lists: ",e.jsx("strong",{children:P.incompleteSourceResults})," ",Cs(P.incompleteSourceResults,"answer","answers"),", not counted as misses"]}));const k=P.excludedProbeResults+P.excludedNonCompletedResults;k>0&&Q.push(e.jsxs(e.Fragment,{children:["Left out: ",e.jsx("strong",{children:k})," ",Cs(k,"answer","answers")," from spot checks or unfinished sweeps"]}))}const E=[...s?[{name:"You",row:s.project}]:[],...v.map(k=>({name:k.domain,row:k}))].filter(k=>k.row.sampleUrls.length>0);C==="measured"&&E.length>0&&Q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsx("summary",{children:"Sample pages cited"}),e.jsx("div",{className:"av-subdetails-body",children:E.map(({name:k,row:H})=>e.jsxs("div",{children:[e.jsx("p",{children:k}),e.jsx("ul",{className:"space-y-1 font-mono text-[11px] text-muted",children:H.sampleUrls.map(se=>e.jsx("li",{className:"break-all",children:se},se))})]},H.domain))})]})),s&&S.length>0&&Q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other competitors seen: ",go(S.length,w)]}),e.jsx("div",{className:"av-subdetails-body",children:e.jsx(Cp,{rows:S,state:C,named:U,cited:F,onPin:f?c:void 0})})]}));const J=s?.observedNames??[];if(J.length>0){const k=s?.observedNamesTotal??J.length;Q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Company names in answers: ",k>J.length?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:J.length})," of ",e.jsx("strong",{children:k})]}):e.jsx("strong",{children:J.length})]}),e.jsx("ul",{className:"av-subdetails-body",children:J.map(H=>e.jsxs("li",{children:[H.name," · ",H.answerCount," ",Cs(H.answerCount,"answer","answers")]},H.name))})]}))}return A.length>0&&Q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other sites cited: ",go(A.length,w)]}),e.jsx("ul",{className:"av-subdetails-body",children:A.map(k=>e.jsxs("li",{children:[e.jsxs("span",{children:[wp(k)," · ",oi(k.surfaceClass)," · ",k.citationCount," ",Cs(k.citationCount,"citation","citations")]}),k.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:k.sampleUrls.map(H=>e.jsx("li",{className:"break-all",children:H},H))}):null]},k.domain))})]})),e.jsxs("section",{"aria-labelledby":y,"aria-busy":x,className:"overview-brief",children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:y,className:"av-card-title",children:"Competitors over time"}),e.jsx(Ge,{text:L?`${vp[L]} ${xo}`:xo})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsx("p",{className:"av-card-meta",children:te}),e.jsx(ha,{label:"Competitors over time window",className:"flex-wrap",options:fp,value:t,onChange:i})]})]}),e.jsxs("div",{className:"av-card-body space-y-3",children:[u?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:[e.jsx("span",{children:u}),p?e.jsx(T,{type:"button",size:"sm",variant:"outline",onClick:p,children:"Retry competitors over time"}):null]}):null,x&&!s&&b.length===0?e.jsx("div",{role:"status","aria-live":"polite",className:"h-24 animate-pulse rounded-md bg-surface",children:e.jsx("span",{className:"sr-only",children:"Loading competitors over time"})}):s||v.length>0?e.jsxs("table",{className:"av-grid av-grid-brands","aria-label":"Competitors over time",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Brand"})}),e.jsx("th",{scope:"col",className:"av-brand-type",children:"Type"}),e.jsx("th",{scope:"col",children:"Mention share"}),e.jsx("th",{scope:"col",children:"Named"}),e.jsx("th",{scope:"col",children:"Cited"}),B?e.jsx("th",{scope:"col",className:"av-brand-actions",children:e.jsx("span",{className:"sr-only",children:"Actions"})}):null]})}),e.jsxs("tbody",{children:[s?e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:s.project.label.trim()?e.jsxs(e.Fragment,{children:[s.project.label.trim()," ",e.jsx("span",{className:"av-of",children:"(you)"})]}):"You"}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:"Your brand"}),e.jsx("td",{children:e.jsx(fo,{percent:s.project.shareOfVoice,state:C,toneClass:z})}),e.jsx("td",{children:e.jsx(Dn,{count:s.project.mentionCount,of:U,state:C,toneClass:z})}),e.jsx("td",{children:e.jsx(Dn,{count:s.project.citationCount,of:F,state:C,toneClass:z})}),B?e.jsx("td",{className:"av-brand-actions"}):null]}):null,v.map(k=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(pc,{row:k,aliases:k.pinned?a[k.domain]:void 0})}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:oi(k.surfaceClass)}),e.jsx("td",{children:e.jsx(fo,{percent:k.shareOfVoice,state:C,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Dn,{count:k.mentionCount,of:U,state:C,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Dn,{count:k.citationCount,of:F,state:C,toneClass:"text-primary"})}),B?e.jsx("td",{className:"av-brand-actions",children:_(k)}):null]},k.domain))]})]}):null,O.length>0?e.jsx("div",{className:"space-y-1 text-[13px] text-secondary",children:O.map(k=>e.jsx("p",{className:k.className,children:k.text},k.key))}):null]}),e.jsx(Sa,{items:Q}),f&&m?e.jsx("div",{className:"border-t border-subtle px-5 py-3",children:e.jsx(kp,{onAddCompetitor:m})}):null]})}function yo({history:t,maxDots:s=12,signal:n="citations"}){const a=t.slice(-s);if(a.length===0)return e.jsx("span",{className:"text-[13px] text-secondary",children:"No data"});const r=n==="mentions"?"Mention":"Citation",l=n==="mentions"?{cited:"mentioned","not-cited":"not mentioned",lost:"mention lost",emerging:"new mention",pending:"mention pending"}:{cited:"cited","not-cited":"not cited",lost:"citation lost",emerging:"new citation",pending:"citation pending"},i={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},c={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},d=a.length-1,m=new Date(a[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(a[d].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),p=`${a.length} ${a.length===1?"run":"runs"}`,x=a.map((h,y)=>{const f=new Date(h.createdAt).toLocaleDateString();return`${y===d?"Latest run, ":""}${f}: ${l[h.citationState]??h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"inline-flex w-max items-center gap-2 whitespace-nowrap",role:"img","aria-label":`${r} history across ${p}. ${x}`,children:[a.length>1?e.jsx("span",{className:"text-[11px] text-secondary shrink-0","aria-hidden":"true",children:m}):null,e.jsx("div",{className:"flex shrink-0 items-center gap-[3px]",title:p,"aria-hidden":"true",children:a.map((h,y)=>{const f=!!(h.model&&y>0&&a[y-1]?.model&&a[y-1].model!==h.model),b=y===d;return e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 ${c[h.citationState]??"rounded-sm"} ${i[h.citationState]??"bg-mono-700"} ${f?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[l[h.citationState]??h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,f?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[11px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{children:"latest"})]})]})}function ci(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const l=s.get(r.createdAt);l?l.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:l}])=>({runId:l,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const Ca="__cited__",ka="__mentioned__",Gs="__mentionShare__";function Ls(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Ut(n),end:Ut(a),sweepCount:s.sweepCount??1}}function va(t,s=new Date){return md(t,s)}function Aa(t,s=new Date){const n=Ls(t);if(!n)return null;const a=va(n.start,s),r=va(n.end,s);return a===r?a:`${a} to ${r}`}function Mi(t,s=new Date){const n=Ls(t),a=Aa(t,s);return!n||!a?"Sweep date unavailable":`${a} · ${n.sweepCount} ${n.sweepCount===1?"sweep":"sweeps"}`}function Rp(t){const s=Ls(t);return s?ud(s.start):""}function ja(t){return t.trim().toLowerCase()}function Pp(t,s={}){return t.map(n=>{const a=n.trim().toLowerCase(),r=(s[n]??[]).map(l=>l.trim().toLowerCase()).filter(Boolean).sort();return a&&r.length>0?`${a}=${r.join("|")}`:a}).filter(Boolean).sort().join(`
1
+ import{j as e,r as o,t as nd,u as qe,L as Ts,h as ms,o as Ot,B as wi,C as Tl,D as ad,k as rd,l as id}from"./vendor-tanstack-ZXXkndVj.js";import{T as je,t as od,a as ld,s as Si,M as xa,I as Ge,f as tt,R as Wn,m as cd,B as T,c as dd,b as ud,d as md,S as Ml,e as Ll,u as Ci,g as hd,n as Un,C as pd,h as $l,i as ql,j as ki,k as xd,l as gd,o as fd,p as bn,q as El,r as Dl,v as ve,w as er,x as Y,y as ie,z as Ms,A as Tt,D as Je,E as yd,F as bd,G as vd,H as Ol,J as jd,K as Nd,L as rn,N as vn,O as wd,P as Sd,Q as Tn,U as Ht,V as Cd,W as kd,X as eo,Y as Fl,Z as zt,_ as Ai,$ as Ad,a0 as Rd,a1 as Pd,a2 as Id,a3 as to,a4 as Fe,a5 as Td,a6 as Md,a7 as Nr,a8 as Ld,a9 as $d,aa as qd,ab as Ed,ac as Dd,ad as Od,ae as Fd,af as Kd,ag as Gd,ah as _d,ai as Ud,aj as Bd,ak as Vd,al as Qd,am as zd,an as Kl,ao as _s,ap as Hd,aq as Gl,ar,as as Wd,at as We,au as Yd,av as Jd,aw as Xd,ax as rr,ay as Zd,az as eu,aA as tu,aB as Bn,aC as su,aD as nu,aE as au,aF as _l,aG as ti,aH as ru,aI as Ri,aJ as iu,aK as Vn,aL as cs,aM as hr,aN as Is,aO as Ul,aP as tr,aQ as si,aR as ou,aS as so,aT as Bl,aU as ga,aV as lu,aW as Vl,aX as Ql,aY as cu,aZ as zl,a_ as mn,a$ as Pi,b0 as wr,b1 as du,b2 as uu,b3 as mu,b4 as hu,b5 as pu,b6 as ma,b7 as no,b8 as $a,b9 as Sr,ba as xu,bb as gu,bc as ao,bd as Cr,be as jn,bf as Hl,bg as Ii,bh as Wl,bi as fu,bj as yu,bk as ro,bl as bu,bm as vu,bn as ju,bo as Nu,bp as wu,bq as Su,br as Cu,bs as ku,bt as Au,bu as Ru,bv as Pu,bw as Iu,bx as Tu,by as Mu,bz as Lu,bA as $u,bB as qu,bC as Eu,bD as Du,bE as Ou,bF as Fu,bG as Ku,bH as Gu,bI as _u,bJ as Uu,bK as Bu,bL as Vu,bM as Qu,bN as Ss,bO as zu,bP as bt,bQ as Hu,bR as Wu,bS as Yu,bT as Ju,bU as Xu,bV as Zu,bW as em,bX as tm,bY as sm,bZ as nm,b_ as am,b$ as rm,c0 as im,c1 as om,c2 as lm,c3 as cm,c4 as dm,c5 as um,c6 as mm,c7 as hm,c8 as pm,c9 as xm,ca as io,cb as gm,cc as fm,cd as ym,ce as bm,cf as vm,cg as Yl,ch as jm,ci as Nm,cj as wm,ck as Jl,cl as kr,cm as Sm,cn as Cm,co as oo,cp as km,cq as Am,cr as Rm,cs as Pm,ct as Im,cu as Tm,cv as Mm,cw as Xl,cx as Lm,cy as Zl,cz as ec,cA as tc,cB as sc,cC as $m,cD as qm,cE as Em,cF as Dm,cG as Om,cH as Fm,cI as Km,cJ as lo,cK as Gm,cL as _m,cM as Um,cN as Bm,cO as Vm,cP as Qm,cQ as zm,cR as Hm,cS as co,cT as Wm,cU as Ym,cV as Jm,cW as Xm,cX as Zm,cY as eh,cZ as th,c_ as sh,c$ as nh,d0 as ah,d1 as rh,d2 as ih,d3 as Ar,d4 as oh,d5 as lh,d6 as ch,d7 as dh,d8 as uh,d9 as mh,da as hh,db as ph,dc as xh,dd as gh,de as fh,df as yh,dg as bh,dh as vh,di as jh,dj as nc,dk as Nh,dl as wh,dm as Sh,dn as Ch,dp as kh,dq as Ah,dr as qa,ds as Rh,dt as Ph,du as Ih,dv as uo,dw as Th}from"./index-BLJfGYUw.js";import{u as Nn,D as Zs,a as Ks,b as ac,M as sr,c as Ds,F as Mh,P as rc,s as Lh,p as $h,S as qh}from"./SiteHealthSection-hi54eSIt.js";import{A as Ti,a as Eh,b as Dh,c as Oh,V as mo}from"./v2-overview-adapter-BPZ-H3VY.js";import{o as Ut,C as fa,f as wn,a as ds,b as _t,c as Pt,d as es,e as lt,g as us,h as Yn,M as ic,i as Fh,j as wa,p as Kh,k as Gh,l as ho,m as _h}from"./ChartPrimitives-CYlrwLJs.js";import{g as oc,y as ya,U as Uh,z as Bh,L as Vh,D as Qh,l as zh,j as ir,I as Hh,J as Wh,C as Qn,X as Yh,e as Jh,K as Xh,P as Zh,N as ep,O as lc}from"./vendor-lucide-N6vOpZmh.js";import{u as tp,a as sp,b as np,t as ap,e as rp,c as Nt}from"./extract-error-message-BOTDI6g5.js";import{R as en,C as tn,a as ba,X as sn,Y as nn,T as an,b as ni,L as or,A as Js,d as Fs,e as ip}from"./vendor-recharts-D-cUuLZo.js";import{A as op}from"./AuditHistoryPanel-D0nukTwD.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B4giJcws.js";import"./vendor-yaml-GWJz5H2G.js";const lp=1e6;function cp(t,s="USD",n={}){const a=new Intl.NumberFormat("en-US",{style:"currency",currency:s,...n.fractionDigits===void 0?{}:{minimumFractionDigits:n.fractionDigits,maximumFractionDigits:n.fractionDigits}}),r=a.format(t/lp);if(n.showTinyAsLessThan&&t>0&&r===a.format(0)){const l=10**-(a.resolvedOptions().maximumFractionDigits??0);return`<${a.format(l)}`}return r}const Ea={projectWide:"Project-wide",projectWideHelp:"This tab covers the whole project. Your measurement scope stays selected for AI Visibility and Queries.",savedScopeUnavailable:"Saved scope unavailable"};function cc(t,s){return t!=="viewer"||s!==null}function dc(t,s){return t==="research"&&!s?"tracked":t}function uc(t,s){return s.measurementScope==="project"?!1:s.measurementScopeKey?!(s.measurementScope==="group"?t.groups:s.measurementScope==="property"?t.targets:t.markets).some(a=>a.stableKey===s.measurementScopeKey):!0}function ai(t,s){return t.find(n=>n.kind===s.measurementScope&&(n.kind==="project"||n.id===s.measurementScopeKey))}function dp(t){return t.measurementScope!=="project"||t.marketKey!==void 0}function up(t){if(t.embedded)return{kind:"none"};const{tab:s}=t;switch(s){case"overview":return t.surface==="advanced-overview"?{kind:"report-picker"}:{kind:"none"};case"queries":case"discovery":{const{tracking:n}=t;return t.queryWorkspace!=="tracked"||n.state!=="ready"||n.mode!=="advanced"?{kind:"none"}:n.scopeUnavailable?{kind:"scope-unavailable"}:{kind:"tracking-picker"}}case"search-console":case"activity":case"technical-aeo":case"conversions":case"local":case"backlinks":case"history":return t.scoped&&t.surface==="advanced-overview"?{kind:"project-wide"}:{kind:"none"};case"settings":case"portfolio":return{kind:"none"};default:return s}}function ri({state:t,label:s,className:n}){return e.jsx(je,{tone:ld(t),className:n,children:s??od(t)})}const hn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],po={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},mp={"non-brand":"On queries that do not contain your name: of the brand names written into the answer text, the share that were yours. Branded queries are scored separately because you are named on nearly all of them and a competitor cannot be.",branded:"On queries that contain your name: of the brand names written into the answer text, the share that were yours. This is recognition, not competitive placement, and it is never pooled with the non-brand figure.",pooled:"This project has no brand name or domain to match on, so branded and non-brand queries could not be separated. This figure pools both and is not a competitive read. Set a display name or aliases to split them."},hp="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function pp(t,s){return s.unavailable?{headline:"No data",numeric:!1,detail:"could not load, refresh to retry",showRows:!1}:s.noRun?{headline:"No data",numeric:!1,detail:"no sweep has run yet",showRows:!1}:t.snapshotsTotal===0?s.otherClassHasData?{headline:"No non-brand queries",numeric:!1,detail:"every tracked query names your brand",showRows:!1}:{headline:"No queries",numeric:!1,detail:"none tracked",showRows:!1}:t.snapshotsWithAnswerText===0?{headline:"No answers",numeric:!1,detail:"no answer text in this run",showRows:!1}:s.hasCompetitors?t.combinedMentionSnapshots===0||t.score===null?{headline:"No mentions",numeric:!1,detail:`no brand named in ${t.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:tt(t.score,Wn.percent),numeric:!0,detail:`${t.projectMentionSnapshots} of ${t.combinedMentionSnapshots} brand mentions`,showRows:!0}:{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1}}function xp({breakdown:t,projectLabel:s}){if(t.ranking.length===0)return null;const n=t.ranking.map(a=>({label:a.kind==="project"?`${s} (you)`:a.domain??"",mentions:a.mentionSnapshots,share:a.share,isYou:a.kind==="project"}));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Ge,{text:hp})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:n.map(a=>e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${a.isYou?"text-heading font-medium":"text-secondary"}`,children:a.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${a.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${a.share>0?Math.max(a.share*100,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:a.mentions}),e.jsx("td",{className:"mention-share-share",children:tt(a.share)})]},a.label))})]})}function gp({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=o.useState("non-brand"),l=o.useId(),i=t.scope==="pooled",c=!i&&t.branded.snapshotsTotal>0,d=c?a:"non-brand",m=i?"pooled":d,u=d==="branded"?t.branded:t.breakdown,p=d==="branded"?t.breakdown:t.branded,x=pp(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:p.snapshotsTotal>0}),h=Si(x.headline),y=m==="non-brand"?xa[t.tone]:"text-secondary";function f(b){const j=hn.findIndex(P=>P.value===d);let A=null;b.key==="ArrowRight"||b.key==="ArrowDown"?A=(j+1)%hn.length:b.key==="ArrowLeft"||b.key==="ArrowUp"?A=(j-1+hn.length)%hn.length:b.key==="Home"?A=0:b.key==="End"&&(A=hn.length-1),A!==null&&(b.preventDefault(),r(hn[A].value),b.currentTarget.querySelectorAll('[role="radio"]')[A]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:l,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Ge,{text:mp[m]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":l,className:"segmented flex-wrap",onKeyDown:f,children:hn.map(b=>{const j=b.value===d;return e.jsx("button",{type:"button",role:"radio","aria-checked":j,tabIndex:j?0:-1,onClick:()=>r(b.value),className:`segmented-option min-h-11 ${j?"segmented-option-active":""}`,children:b.label},b.value)})}):e.jsx("span",{className:"mention-share-class",children:po[m]})]}),x.numeric?e.jsxs("p",{className:`mention-share-value ${y}`,children:[h.figure,h.sign?e.jsx("span",{className:"text-faint",children:h.sign}):null]}):e.jsx("p",{className:"mention-share-value-text",children:x.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:po[m]}),` · ${x.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),x.showRows&&e.jsx(xp,{breakdown:u,projectLabel:s})]})}function Sa({items:t,label:s="Details"}){return t.length===0?null:e.jsxs("details",{className:"av-details",children:[e.jsx("summary",{children:s}),e.jsx("ul",{className:"av-details-list",children:t.map((n,a)=>e.jsx("li",{children:n},a))})]})}function ha({options:t,value:s,onChange:n,label:a,className:r=""}){const l=o.useId();function i(c){const d=t.findIndex(u=>u.value===s);let m=null;c.key==="ArrowRight"||c.key==="ArrowDown"?m=(d+1)%t.length:c.key==="ArrowLeft"||c.key==="ArrowUp"?m=(d-1+t.length)%t.length:c.key==="Home"?m=0:c.key==="End"&&(m=t.length-1),m!==null&&(c.preventDefault(),n(t[m].value),c.currentTarget.querySelectorAll('[role="radio"]')[m].focus())}return e.jsx("div",{role:"radiogroup","aria-label":a,className:`segmented ${r}`.trim(),onKeyDown:i,children:t.map(c=>{const d=c.value===s,m=c.description?`${l}-${c.value}`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button",role:"radio","aria-checked":d,"aria-describedby":m,tabIndex:d?0:-1,onClick:()=>n(c.value),className:`segmented-option pointer-coarse:min-h-11 ${d?"segmented-option-active":""}`,children:c.label}),c.description?e.jsx("span",{id:m,className:"sr-only",children:c.description}):null]},c.value)})})}const fp=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],yp={"7d":"last 7 days","30d":"last 30 days","90d":"last 90 days",all:"all sweeps"},bp={"non-brand":"Non-brand",branded:"Branded",all:"All queries"},vp={"non-brand":"Counts queries that do not name your brand.",branded:"Counts queries that name your brand.",all:"Counts every tracked query, so mention share is not shown."},jp={"select-query-class":"no query type selected","answer-selection":"answers selected by the brands they named","no-competitors":"no competitors configured","insufficient-observed":"needs 3 observed competitors, each named in 3 or more answers","no-answers":"no answer text","no-mentions":"no brands named",unavailable:"competitor data unavailable"},xo="Mention share: your share of the brand mentions in these answers, each brand counted at most once per answer. Named: answers that name the brand. Cited: answers whose sources link to its site. Company names in answers are observations. Only competitor sites count toward mention share.",ii=100;function Np(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function mc(t){return t==="unavailable"?"Unavailable":"Not measured"}function oi(t){switch(t){case"own":return"Your domain";case"direct-competitor":return"Competitor";case"ota-aggregator":return"Aggregator";case"editorial-media":return"Editorial";case"other":return"Other";default:return"Unclassified"}}function Cs(t,s,n){return t===1?s:n}function hc(t){const s=t.label.trim(),n=dd(t.domain);return s&&s.toLowerCase()!==t.domain.toLowerCase()&&s.toLowerCase()!==n.toLowerCase()?s:null}function pc({row:t,aliases:s=[]}){const n=hc(t),a=s.length>0?e.jsxs("span",{className:"av-of block",children:["Also named ",s.join(", ")]}):null;return n?e.jsxs(e.Fragment,{children:[n," ",e.jsx("span",{className:"av-of",children:t.domain}),a]}):e.jsxs(e.Fragment,{children:[t.domain,a]})}function wp(t){const s=hc(t);return s?`${s} (${t.domain})`:t.domain}function go(t,s){return s&&t>=ii?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:t})]}):e.jsx("strong",{children:t})}function li({action:t,domain:s,mutation:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(null);async function c(){if(!a){r(!0),i(null);try{await n(s)===!1&&i(`Could not ${t} competitor. Try again.`)}catch{i(`Could not ${t} competitor. Try again.`)}finally{r(!1)}}}return e.jsxs(e.Fragment,{children:[e.jsxs(T,{type:"button",size:"sm",variant:"outline",disabled:a,onClick:()=>{c()},children:[t==="pin"?"Pin":"Unpin"," ",e.jsx("span",{className:"sr-only",children:s})]}),l?e.jsx("span",{role:"alert",className:"sr-only",children:l}):null]})}function Sp({urls:t}){return e.jsxs("details",{className:"inline-disclosure text-left text-xs text-secondary",children:[e.jsx("summary",{children:"Source URLs"}),e.jsx("ul",{className:"mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal",children:t.map(s=>e.jsx("li",{className:"break-all",children:s},s))})]})}function Dn({count:t,of:s,state:n,toneClass:a}){return n!=="measured"?e.jsx("span",{className:"text-[13px] text-secondary",children:mc(n)}):e.jsxs("span",{className:"whitespace-nowrap",children:[e.jsx("span",{className:`av-n-sm ${a}`,children:t})," ",e.jsxs("span",{className:"av-of",children:["of ",s]})]})}function fo({percent:t,state:s,toneClass:n}){if(s!=="measured"||t===null)return e.jsx("span",{className:"text-[13px] text-secondary",children:s==="measured"?"Not measured":mc(s)});const{figure:a,sign:r}=Si(tt(t,Wn.percent));return e.jsxs("span",{className:`av-n-sm ${n}`,children:[a,r?e.jsx("span",{className:"text-faint",children:r}):null]})}function Cp({rows:t,state:s,named:n,cited:a,onPin:r}){return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":"Other competitors seen",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Competitor"}),e.jsx("th",{scope:"col",children:"Type"}),e.jsx("th",{scope:"col",children:"Named"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(pc,{row:l})}),e.jsx("td",{className:"text-[13px] text-secondary",children:oi(l.surfaceClass)}),e.jsx("td",{children:e.jsx(Dn,{count:l.mentionCount,of:n,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Dn,{count:l.citationCount,of:a,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex min-w-max items-start gap-2",children:[s==="measured"&&l.sampleUrls.length>0?e.jsx(Sp,{urls:l.sampleUrls}):null,r?e.jsx(li,{action:"pin",domain:l.domain,mutation:r}):null]})})]},l.domain))})]})})}function kp({onAddCompetitor:t}){const s=o.useId(),[n,a]=o.useState(""),[r,l]=o.useState(!1),[i,c]=o.useState(null);async function d(){const m=n.trim();if(!(!m||r)){l(!0),c(null);try{if(await t(m)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("Could not add competitor. Try again.")}finally{l(!1)}}}return e.jsxs("details",{className:"inline-disclosure",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:m=>{m.preventDefault(),d()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:m=>a(m.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(T,{type:"submit",size:"sm",className:"min-h-10",disabled:r||!n.trim(),children:r?"Adding…":"Add competitor"}),i?e.jsx("p",{role:"alert",className:"w-full text-sm text-negative",children:i}):null]})]})}function Ap({window:t,landscape:s,pinnedFallback:n=[],competitorAliases:a={},canWrite:r,isEmbed:l,onWindowChange:i,onPin:c,onUnpin:d,onAddCompetitor:m,error:u,onRetry:p,isLoading:x=!1,scopeLabel:h}){const y=o.useId(),f=r&&!l,b=s?.pinned??n,j=s?.observed??[],A=s?.otherSources??[],P=s?.evidence,C=Np(s),g=s?.basis==="observed",v=g?j.filter(k=>k.shareOfVoice!==null):b,S=g?j.filter(k=>k.shareOfVoice===null):j,L=s?.filters.queryClass,M=s?.marketState?.draft?.pendingCompetitorDomains.length??0,w=s?.truncated===!0,U=P?.answeredResults??0,F=P?P.answeredResults+P.missingAnswerTextResults:0,z=L==="non-brand"&&s?.project.shareOfVoice!=null?xa[cd(s.project.shareOfVoice)]:"text-primary",_=k=>f?k.pinned?d?e.jsx(li,{action:"unpin",domain:k.domain,mutation:d}):null:c?e.jsx(li,{action:"pin",domain:k.domain,mutation:c}):null:null,B=v.some(k=>_(k)!==null),te=[h,L?bp[L]:null,yp[t],s?.basis?g?"observed competitors only":"tracked competitors only":null].filter(Boolean).join(" · "),O=[];if(s&&!g&&v.length===0&&O.push({key:"no-pins",text:"No pinned competitors."}),s?.reason&&O.push({key:"reason",text:`Mention share: ${jp[s.reason]}`}),s&&S.length>0){const k=S.length;O.push({key:"others",text:w&&k>=ii?`${ii} or more other competitors seen`:`${k} other ${Cs(k,"competitor","competitors")} seen`})}M>0&&O.push({key:"pending",text:`${s?.scope.kind==="all-markets"?"Pending publication across markets":"Pending publication"}: ${M} ${Cs(M,"competitor","competitors")}`});const V=[P&&P.missingAnswerTextResults>0?"Answer data incomplete":null,P&&P.incompleteSourceResults>0?"Citation data incomplete":null].filter(Boolean);V.length>0&&O.push({key:"incomplete",text:V.join(" · "),className:xa.caution});const Q=[];if(s&&P){Q.push(s.runCount!==void 0?e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:s.runCount})," ",Cs(s.runCount,"sweep","sweeps"),", ",e.jsx("strong",{children:P.answeredResults})," ",Cs(P.answeredResults,"answer","answers")]}):e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:P.answeredResults})," ",Cs(P.answeredResults,"answer","answers")]})),!s.reason&&C==="measured"&&s.project.shareOfVoice!==null&&Q.push(e.jsxs(e.Fragment,{children:["Mention share: you ",e.jsx("strong",{children:s.project.mentionCount}),v.map(H=>e.jsxs(nd.Fragment,{children:[", ",H.domain," ",e.jsx("strong",{children:H.mentionCount})]},H.domain))," ","of ",e.jsx("strong",{children:P.mentionCredits})," ",g?"brand mentions":"tracked-brand mentions"]})),Q.push(e.jsxs(e.Fragment,{children:["Answers with source links: ",e.jsx("strong",{children:P.sourceResults})]})),S.length===0&&Q.push("Other competitors seen: none"),P.missingAnswerTextResults>0&&Q.push(e.jsxs(e.Fragment,{children:["No answer text: ",e.jsx("strong",{children:P.missingAnswerTextResults})," ",Cs(P.missingAnswerTextResults,"answer","answers"),", left out of mention share"]})),P.incompleteSourceResults>0&&Q.push(e.jsxs(e.Fragment,{children:["Incomplete source lists: ",e.jsx("strong",{children:P.incompleteSourceResults})," ",Cs(P.incompleteSourceResults,"answer","answers"),", not counted as misses"]}));const k=P.excludedProbeResults+P.excludedNonCompletedResults;k>0&&Q.push(e.jsxs(e.Fragment,{children:["Left out: ",e.jsx("strong",{children:k})," ",Cs(k,"answer","answers")," from spot checks or unfinished sweeps"]}))}const E=[...s?[{name:"You",row:s.project}]:[],...v.map(k=>({name:k.domain,row:k}))].filter(k=>k.row.sampleUrls.length>0);C==="measured"&&E.length>0&&Q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsx("summary",{children:"Sample pages cited"}),e.jsx("div",{className:"av-subdetails-body",children:E.map(({name:k,row:H})=>e.jsxs("div",{children:[e.jsx("p",{children:k}),e.jsx("ul",{className:"space-y-1 font-mono text-[11px] text-muted",children:H.sampleUrls.map(se=>e.jsx("li",{className:"break-all",children:se},se))})]},H.domain))})]})),s&&S.length>0&&Q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other competitors seen: ",go(S.length,w)]}),e.jsx("div",{className:"av-subdetails-body",children:e.jsx(Cp,{rows:S,state:C,named:U,cited:F,onPin:f?c:void 0})})]}));const J=s?.observedNames??[];if(J.length>0){const k=s?.observedNamesTotal??J.length;Q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Company names in answers: ",k>J.length?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:J.length})," of ",e.jsx("strong",{children:k})]}):e.jsx("strong",{children:J.length})]}),e.jsx("ul",{className:"av-subdetails-body",children:J.map(H=>e.jsxs("li",{children:[H.name," · ",H.answerCount," ",Cs(H.answerCount,"answer","answers")]},H.name))})]}))}return A.length>0&&Q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other sites cited: ",go(A.length,w)]}),e.jsx("ul",{className:"av-subdetails-body",children:A.map(k=>e.jsxs("li",{children:[e.jsxs("span",{children:[wp(k)," · ",oi(k.surfaceClass)," · ",k.citationCount," ",Cs(k.citationCount,"citation","citations")]}),k.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:k.sampleUrls.map(H=>e.jsx("li",{className:"break-all",children:H},H))}):null]},k.domain))})]})),e.jsxs("section",{"aria-labelledby":y,"aria-busy":x,className:"overview-brief",children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:y,className:"av-card-title",children:"Competitors over time"}),e.jsx(Ge,{text:L?`${vp[L]} ${xo}`:xo})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsx("p",{className:"av-card-meta",children:te}),e.jsx(ha,{label:"Competitors over time window",className:"flex-wrap",options:fp,value:t,onChange:i})]})]}),e.jsxs("div",{className:"av-card-body space-y-3",children:[u?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:[e.jsx("span",{children:u}),p?e.jsx(T,{type:"button",size:"sm",variant:"outline",onClick:p,children:"Retry competitors over time"}):null]}):null,x&&!s&&b.length===0?e.jsx("div",{role:"status","aria-live":"polite",className:"h-24 animate-pulse rounded-md bg-surface",children:e.jsx("span",{className:"sr-only",children:"Loading competitors over time"})}):s||v.length>0?e.jsxs("table",{className:"av-grid av-grid-brands","aria-label":"Competitors over time",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Brand"})}),e.jsx("th",{scope:"col",className:"av-brand-type",children:"Type"}),e.jsx("th",{scope:"col",children:"Mention share"}),e.jsx("th",{scope:"col",children:"Named"}),e.jsx("th",{scope:"col",children:"Cited"}),B?e.jsx("th",{scope:"col",className:"av-brand-actions",children:e.jsx("span",{className:"sr-only",children:"Actions"})}):null]})}),e.jsxs("tbody",{children:[s?e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:s.project.label.trim()?e.jsxs(e.Fragment,{children:[s.project.label.trim()," ",e.jsx("span",{className:"av-of",children:"(you)"})]}):"You"}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:"Your brand"}),e.jsx("td",{children:e.jsx(fo,{percent:s.project.shareOfVoice,state:C,toneClass:z})}),e.jsx("td",{children:e.jsx(Dn,{count:s.project.mentionCount,of:U,state:C,toneClass:z})}),e.jsx("td",{children:e.jsx(Dn,{count:s.project.citationCount,of:F,state:C,toneClass:z})}),B?e.jsx("td",{className:"av-brand-actions"}):null]}):null,v.map(k=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(pc,{row:k,aliases:k.pinned?a[k.domain]:void 0})}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:oi(k.surfaceClass)}),e.jsx("td",{children:e.jsx(fo,{percent:k.shareOfVoice,state:C,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Dn,{count:k.mentionCount,of:U,state:C,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(Dn,{count:k.citationCount,of:F,state:C,toneClass:"text-primary"})}),B?e.jsx("td",{className:"av-brand-actions",children:_(k)}):null]},k.domain))]})]}):null,O.length>0?e.jsx("div",{className:"space-y-1 text-[13px] text-secondary",children:O.map(k=>e.jsx("p",{className:k.className,children:k.text},k.key))}):null]}),e.jsx(Sa,{items:Q}),f&&m?e.jsx("div",{className:"border-t border-subtle px-5 py-3",children:e.jsx(kp,{onAddCompetitor:m})}):null]})}function yo({history:t,maxDots:s=12,signal:n="citations"}){const a=t.slice(-s);if(a.length===0)return e.jsx("span",{className:"text-[13px] text-secondary",children:"No data"});const r=n==="mentions"?"Mention":"Citation",l=n==="mentions"?{cited:"mentioned","not-cited":"not mentioned",lost:"mention lost",emerging:"new mention",pending:"mention pending"}:{cited:"cited","not-cited":"not cited",lost:"citation lost",emerging:"new citation",pending:"citation pending"},i={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},c={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},d=a.length-1,m=new Date(a[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(a[d].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),p=`${a.length} ${a.length===1?"run":"runs"}`,x=a.map((h,y)=>{const f=new Date(h.createdAt).toLocaleDateString();return`${y===d?"Latest run, ":""}${f}: ${l[h.citationState]??h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"inline-flex w-max items-center gap-2 whitespace-nowrap",role:"img","aria-label":`${r} history across ${p}. ${x}`,children:[a.length>1?e.jsx("span",{className:"text-[11px] text-secondary shrink-0","aria-hidden":"true",children:m}):null,e.jsx("div",{className:"flex shrink-0 items-center gap-[3px]",title:p,"aria-hidden":"true",children:a.map((h,y)=>{const f=!!(h.model&&y>0&&a[y-1]?.model&&a[y-1].model!==h.model),b=y===d;return e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 ${c[h.citationState]??"rounded-sm"} ${i[h.citationState]??"bg-mono-700"} ${f?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[l[h.citationState]??h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,f?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[11px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{children:"latest"})]})]})}function ci(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const l=s.get(r.createdAt);l?l.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:l}])=>({runId:l,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const Ca="__cited__",ka="__mentioned__",Gs="__mentionShare__";function Ls(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Ut(n),end:Ut(a),sweepCount:s.sweepCount??1}}function va(t,s=new Date){return md(t,s)}function Aa(t,s=new Date){const n=Ls(t);if(!n)return null;const a=va(n.start,s),r=va(n.end,s);return a===r?a:`${a} to ${r}`}function Mi(t,s=new Date){const n=Ls(t),a=Aa(t,s);return!n||!a?"Sweep date unavailable":`${a} · ${n.sweepCount} ${n.sweepCount===1?"sweep":"sweeps"}`}function Rp(t){const s=Ls(t);return s?ud(s.start):""}function ja(t){return t.trim().toLowerCase()}function Pp(t,s={}){return t.map(n=>{const a=n.trim().toLowerCase(),r=(s[n]??[]).map(l=>l.trim().toLowerCase()).filter(Boolean).sort();return a&&r.length>0?`${a}=${r.join("|")}`:a}).filter(Boolean).sort().join(`
2
2
  `)}const Ip={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",muse:"Muse",local:"Local"};function ot(t){const s=ja(t);return Ip[s]??t.charAt(0).toUpperCase()+t.slice(1)}function di(t){return Math.round(t*1e3)/10}function ui(t){return t.byProvider??{}}function Tp(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?Ca:ka,m=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(p=>({date:p.startDate,[d]:di(p[m])})),series:[d],hasData:a,singleBucket:r}}const l=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys(ui(d))))].sort();return{rows:t.buckets.map(d=>{const m={date:d.startDate},u=ui(d);for(const p of i){const x=u[p];m[p]=x?di(x[l]):null}return m}),series:i,hasData:a,singleBucket:r}}function xc(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Mp(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Lp(t){return t.servedModelAttribution??{}}function $p(t){return t.modelServiceMismatch??{}}function qp(t){return t.modelPointerChanges??{}}function pa(t){return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function Na(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return t.models.length===0?"Unknown model":`${t.models.join(", ")}${t.includesUnknown?" and an unknown model":""}`}}function Ep(t){return pa([...t.models,...t.includesUnknown?["an unknown model"]:[]])}function Dp(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const l=s.get(r.bucketStartDate)??[];l.push({provider:n,event:r}),s.set(r.bucketStartDate,l)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,l)=>r.provider.localeCompare(l.provider)||r.event.observedAt.localeCompare(l.event.observedAt))}))}function Op(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const l=r.events.filter(i=>!i.fromPreWindowAnchor);for(const i of r.events)i.fromPreWindowAnchor&&n.push({provider:a,event:i});l.length>0&&(s[a]={...r,events:l})}return{buckets:Dp(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Fp(t){const s=[];for(const[n,a]of Object.entries(t)){const r=a.eventTotal??a.events.length;r>a.events.length&&s.push({provider:n,shown:a.events.length,total:r})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Kp(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[Gs]:r?.rate==null?null:di(r.rate)}}),n=s.map(a=>a[Gs]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Gs],hasData:n.length>0,singleBucket:n.length===1}}function Gp(t,s,n){return s==="mentionShare"?Kp(t):Tp(t,s,n)}function _p(t,s){if(s==="mentionShare")return t.buckets.flatMap(a=>{const r=a.mentionShare?.rate;return typeof r=="number"&&Number.isFinite(r)?[r]:[]});const n=s==="cited"?"citationRate":"mentionRate";return t.buckets.map(a=>a[n])}function Up(t,s){const n=t.windowChange;if(!n)return null;switch(s){case"cited":return n.citationRate;case"mentioned":return n.mentionRate;case"mentionShare":return n.mentionShare}}function Bp(t,s,n){const a=n==="mentioned"?"mentionRate":"citationRate";for(let r=t.buckets.length-1;r>=0;r--){const l=ui(t.buckets[r])[s];if(l)return l[a]}return null}function He(t){return Date.parse(t)}function gc(t,s){const n=Ls(t);if(!n)return!1;const a=He(s);return a>=He(n.start)&&a<=He(n.end)}function fc(t){return t.basketChanges??[]}function yc(t,s){return s.filter(n=>gc(t,n.at)).sort((n,a)=>He(n.at)-He(a.at))}function lr(t,s){return ja(t)==="perplexity"&&s.status==="known"&&!s.model.includes("/")}function Vp(t){return Object.entries(t).filter(([s,n])=>!lr(s,n.configured)).sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>({provider:s,mismatch:n}))}function Qp(t){return[...fc(t)].sort((s,n)=>He(n.at)-He(s.at)).map(s=>({at:Ut(s.at),added:s.added,removed:s.removed}))}function zp(t,s){const n=[...t.events].sort((r,l)=>He(r.observedAt)-He(l.observedAt));let a=n[0]?.from??t.latestObservation.state;for(const r of n)He(r.observedAt)<=He(s)&&(a=r.to);return a}function bo(t,s,n,a){return{provider:t,at:Ut(s.observedAt),onOrBefore:s.fromPreWindowAnchor===!0,anchorAt:s.anchorObservedAt?Ut(s.anchorObservedAt):null,from:s.from,to:s.to,served:n,reroute:a}}function Hp(t,s){const n=[];for(const[a,r]of Object.entries(t)){const i=s[a]?.events??[],c=new Set(r.events.map(d=>d.observedAt));for(const d of r.events){const m=lr(a,d.to)?i.find(u=>u.observedAt===d.observedAt):void 0;n.push(bo(a,d,m?{from:m.from,to:m.to}:null,!1))}for(const d of i)c.has(d.observedAt)||lr(a,zp(r,d.observedAt))&&n.push(bo(a,d,null,!0))}return n.sort((a,r)=>He(r.at)-He(a.at)||a.provider.localeCompare(r.provider))}function Wp({latest:t,queryChanges:s,modelRows:n,now:a=new Date}){const r=[...s.map(x=>x.at),...n.map(x=>x.at)];if(r.length===0)return null;const l=x=>t!==void 0&&gc(t,x),i=s.filter(x=>l(x.at)),c=i.reduce((x,h)=>x+h.added.length,0),d=i.reduce((x,h)=>x+h.removed.length,0),m=n.filter(x=>l(x.at)).length,u=t?Aa(t,a):null;if(u===null||c+d+m===0){const x=r.reduce((h,y)=>He(y)>He(h)?y:h);return`No changes since ${va(x,a)}`}const p=[u];return c>0&&p.push(`${c} ${c===1?"query":"queries"} added`),d>0&&p.push(`${d} ${d===1?"query":"queries"} removed`),m>0&&p.push(`${m} new ${m===1?"model":"models"}`),p.join(" · ")}function Yp(t,s,n,a=null){const r=He(t);if(!Number.isFinite(r))return null;const l=s.filter(m=>He(m)<r);if(l.length>0)return Ut(l.reduce((m,u)=>He(u)>He(m)?u:m));const i=n.map(m=>Ls(m)).filter(m=>m!==null).sort((m,u)=>He(m.start)-He(u.start)),c=i.findIndex(m=>He(m.start)<=r&&r<=He(m.end));if(c===-1)return null;const d=i[c];return He(d.start)===r?c>0?i[c-1].end:a&&He(a)<r?Ut(a):null:d.sweepCount===2&&He(d.end)===r?d.start:null}function Jp(t){const s=new Map,n=(a,r)=>{const l=s.get(a);l?l.push(r):s.set(a,[r])};for(const a of[...t].sort((r,l)=>r.revision-l.revision)){const r=He(a.at);for(const l of a.removed)n(l,{at:r,member:!1});for(const l of a.added)n(l,{at:r,member:!0})}return new Map([...s].filter(([,a])=>a.at(-1).member))}function zn(t,s){let n=!t[0].member;for(const a of t)a.at<=s&&(n=a.member);return n}function Xp(t,s,n){return t.some(a=>a.at>s&&a.at<=n)}function mi(t,s){const n=He(s.start),a=He(s.end);return s.sweepCount>2?Xp(t,n,a):zn(t,n)!==zn(t,a)}function bc(t,s,n,a){const r=He(s),l=He(n),i={added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]},c=new Set;for(const[p,x]of Jp(t)){if(!a(x))continue;c.add(p);const h=zn(x,r),y=zn(x,l);h!==y?(y?i.added:i.removed).push(p):(h?i.removedAndAddedBack:i.addedAndRemovedAgain).push(p)}if(c.size===0)return null;const d=p=>[...p.added,...p.removed].some(x=>c.has(x)),m=t.filter(p=>He(p.at)>r&&He(p.at)<=l&&d(p)).sort((p,x)=>He(p.at)-He(x.at)),u=[...new Set(m.flatMap(p=>[...p.added,...p.removed]))].filter(p=>c.has(p));return{changes:m,keys:u,moves:i}}function Zp(t,s){if(t.length<2)return null;const n=t[0],a=t.at(-1),r=Ls(n),l=Ls(a),i=r?.start??n.startDate,c=l?.end??a.endDate,d=bc(s,i,c,m=>zn(m,He(i))!==zn(m,He(c))||r!==null&&mi(m,r)||l!==null&&mi(m,l));return!d&&n.queryCount===a.queryCount?null:{...d??{changes:[],keys:[],moves:{added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]}},firstCount:n.queryCount,latestCount:a.queryCount}}function vc(t,s){const n=Ls(t);if(!n)return null;const a=bc(s,n.start,n.end,r=>mi(r,n));return a?{...a,firstCount:t.queryCount,latestCount:t.queryCount}:null}function Rr(t){return`${t} ${t===1?"query":"queries"}`}function ex(t){const s=[],n=a=>s.length===0?Rr(a):String(a);return t.added.length>0&&s.push(`${n(t.added.length)} added`),t.removed.length>0&&s.push(`${n(t.removed.length)} removed`),t.removedAndAddedBack.length>0&&s.push(`${Rr(t.removedAndAddedBack.length)} removed and added back`),t.addedAndRemovedAgain.length>0&&s.push(`${Rr(t.addedAndRemovedAgain.length)} added and removed again`),pa(s)}function vo(t,s,n,a){return t?s!=="mentionShare"||n!=="non-brand"||!a?!1:t.keys.length>0&&t.keys.every(r=>a(r)==="branded"):!0}const jo=320;function No(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function wo(t){return t==="non-brand"?0:t==="branded"?1:2}function tx(t){const s=[];for(const n of t){const a=s.at(-1);a&&a.queryClass===n.queryClass?a.rows.push(n):s.push({queryClass:n.queryClass,rows:[n]})}return s}function sx(t){return t.phrase}function So(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 Co(t,s){if(s==="mentions")switch(t){case"cited":return"Mentioned";case"not-cited":return"Not Mentioned";case"pending":return"Pending";case"emerging":return"Newly Mentioned";case"lost":return"No Longer Mentioned"}switch(t){case"cited":return"Cited";case"not-cited":return"Not Cited";case"lost":return"Lost";case"emerging":return"Emerging";case"pending":return"Pending"}}function nx(t,s){return t.map(n=>jc(n,s))}function jc(t,s){return s==="citations"?t:{...t,citationState:So(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:So(n,s)}))}}function ko(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,l=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",c=l==="cited"||l==="emerging";return r==="lost"||l!==null&&c&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||l!==null&&!c&&i?{key:s,label:`New ${n}`,tone:"positive"}:l===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function ax(t){const s=ci(nx(t,"mentions")),n=ci(t);return[ko(s,"mentions"),ko(n,"citations")]}function rx({signal:t}){const s=t.tone==="positive"?"text-positive":t.tone==="negative"?"text-negative":t.tone==="pending"?"text-caution":"text-secondary";return e.jsx("span",{className:s,children:t.label})}function Ao({items:t}){return e.jsx("div",{className:"query-evidence-signals","aria-label":"Latest run mention and citation signals",children:ax(t).map(s=>e.jsx(rx,{signal:s},s.key))})}function Nc({queryClass:t,actions:s}){return e.jsxs(e.Fragment,{children:[s?e.jsx("div",{className:"query-evidence-toolbar",children:e.jsxs("div",{className:"query-evidence-actions",children:[!t&&e.jsx(Ml,{}),s]})}):null,t?e.jsx(Ll,{queryClass:t,manage:!!s}):null]})}function ix({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed",providerSelection:a,onProviderSelectionChange:r,addedQueries:l=[],actions:i,actionPanel:c}){const{openEvidence:d}=Ci(),m=o.useId(),[u,p]=o.useState(new Set),x=hd(),[h,y]=o.useState("mentions"),[f,b]=o.useState(n),[j,A]=o.useState("all"),[P,C]=o.useState(""),g=a??P,v=E=>{C(E),r?.(E)},S=o.useMemo(()=>[...new Set([...t.map(E=>E.provider).filter(Boolean),...g?[g]:[]])].sort(),[t,g]),L=o.useMemo(()=>{const E=new Map;for(const J of t){if(g&&J.provider!==g)continue;const k=J.query,H=J.queryClass??null,se=s?J.location??null:null,ne=JSON.stringify([k,H,se]),oe=E.get(ne)??{key:ne,phrase:k,queryClass:H,location:se,items:[],rawItems:[]};oe.items.push(jc(J,h)),oe.rawItems.push(J),E.set(ne,oe)}return[...E.values()].sort((J,k)=>wo(J.queryClass)-wo(k.queryClass))},[t,h,s,g]),M=o.useMemo(()=>L.filter(E=>j==="all"||(j==="unclassified"?E.queryClass===null:E.queryClass===j)),[L,j]),w=Nn({rows:M,getSearchText:sx}),U=o.useMemo(()=>{const E=new Map;for(const J of w.filteredRows){const k=E.get(J.queryClass)??new Set;k.add(J.phrase),E.set(J.queryClass,k)}return E},[w.filteredRows]),F=o.useMemo(()=>new Set(l.map(Un)),[l]),z=x?6:5,_=w.rows.map(E=>E.key),B=_.length>0&&_.every(E=>u.has(E)),te=E=>{p(J=>{const k=new Set(J);return k.has(E)?k.delete(E):k.add(E),k})},O=h==="mentions"?"mentioned":"cited",V=h==="mentions"?"Mention History":"Citation History",Q=h==="mentions"?"mentioned":"cited";return e.jsxs("div",{className:"query-evidence",children:[e.jsx(Nc,{queryClass:j,actions:i}),c,e.jsxs("div",{className:"query-evidence-view-row",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"query-evidence-tabs",role:"tablist","aria-label":"Citation tracking view",children:["mentions","citations"].map(E=>e.jsx("button",{id:`${m}-${E}`,type:"button",role:"tab","aria-controls":m,"aria-selected":h===E,tabIndex:h===E?0:-1,onClick:()=>y(E),onKeyDown:J=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(J.key))return;J.preventDefault();const k=J.key==="Home"?"mentions":J.key==="End"||E==="mentions"?"citations":"mentions";y(k),document.getElementById(`${m}-${k}`)?.focus()},children:E==="mentions"?"Mentions":"Citations"},E))}),e.jsx(Ge,{text:"Mentions track your brand or domain in answer text. Citations track your domain in source links. Each signal is measured independently."})]}),e.jsxs("div",{className:"query-evidence-display-controls",children:[e.jsxs("label",{className:"query-evidence-preview-toggle",children:[e.jsx("input",{type:"checkbox",checked:f==="detailed",onChange:E=>b(E.target.checked?"detailed":"compact")}),"Show answer previews"]}),e.jsx(T,{type:"button",variant:"ghost",className:"min-h-11",disabled:_.length===0,onClick:()=>{p(E=>{const J=new Set(E);for(const k of _)B?J.delete(k):J.add(k);return J})},children:B?"Collapse page":"Expand page"})]})]}),t.length>0||g?e.jsxs("div",{className:"query-evidence-filters",children:[e.jsx(Zs,{value:w.query,onChange:w.setQuery,label:"Find a query",placeholder:"Find a query",className:"query-evidence-search"}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Answer engine"}),e.jsxs("select",{value:g,onChange:E=>{v(E.target.value),w.setPage(1)},children:[e.jsx("option",{value:"",children:"All engines"}),S.map(E=>e.jsx("option",{value:E,children:ot(E)},E))]})]}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Query class"}),e.jsxs("select",{value:j,onChange:E=>{A(E.target.value),w.setPage(1)},children:[e.jsx("option",{value:"all",children:"All queries"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]})]}):null,e.jsxs("div",{id:m,role:"tabpanel","aria-labelledby":`${m}-${h}`,children:[e.jsx("div",{className:"query-evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table query-evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),x&&e.jsx("th",{scope:"col","aria-label":"Sentiment",children:e.jsxs("span",{className:"inline-flex items-center",children:["Sentiment",e.jsx(Ge,{text:"Branded query rows show the favorable share of judged answers. Non-brand rows show only their unfavorable and mixed answers. Expanded engine rows show each stored answer’s sentiment; factual and unmentioned answers are not judgments."})]})}),e.jsx("th",{scope:"col",children:V}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Answer"})})]})}),tx(w.rows).map(E=>e.jsxs("tbody",{children:[e.jsx("tr",{className:"query-evidence-group",children:e.jsxs("th",{scope:"rowgroup",colSpan:z,children:[No(E.queryClass)," (",U.get(E.queryClass)?.size??0,")"]})}),E.rows.map(({key:J,phrase:k,queryClass:H,location:se,items:ne,rawItems:oe})=>{const ke=u.has(J),X=_.indexOf(J),ue=`${m}-query-${X}`,fe=F.has(Un(k)),Z=ne.map(re=>re.citationState),ce=Z.includes("cited")?"cited":Z.includes("emerging")?"emerging":Z.includes("lost")?"lost":Z.every(re=>re==="pending")?"pending":"not-cited",G=[...new Set(oe.map(re=>re.queryId).filter(re=>!!re))],de=oe.map(re=>re.sourceSnapshotId).filter(re=>!!re),De=ci(ne),Re=ne.filter(re=>re.citationState===pd.cited||re.citationState==="emerging").length;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-row",onClick:()=>te(J),children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("button",{type:"button",className:"query-evidence-query","aria-label":k,"aria-describedby":ue,"aria-expanded":ke,onClick:re=>{re.stopPropagation(),te(J)},children:[e.jsx(oc,{size:16,"aria-hidden":"true",className:ke?"rotate-90":""}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{children:k}),e.jsxs("span",{id:ue,className:"query-evidence-meta",children:[e.jsx("span",{children:No(H)}),s&&e.jsx("span",{children:se??"No location"}),ne.filter(re=>re.provider).map(re=>e.jsx("span",{children:ot(re.provider)},re.id))]})]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ri,{state:ce,label:Co(ce,h),className:"rounded-none border-0 bg-transparent p-0 text-sm tracking-normal"}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums","aria-label":`${Re} of ${ne.length} engines ${Q}`,title:`${Re} of ${ne.length} engines ${Q}`,children:[Re,"/",ne.length]})]})}),x&&e.jsx("td",{children:e.jsx($l,{queryId:G.length===1?G[0]:null,sourceSnapshotIds:G.length>1?[]:de,queryClass:H,location:s?se:void 0})}),e.jsx("td",{children:e.jsx(yo,{history:De,signal:h})}),e.jsx("td",{className:"evidence-change-cell",children:fe?e.jsx("span",{className:"query-evidence-new",children:"new query"}):e.jsx(Ao,{items:oe})}),e.jsx("td",{})]}),ke&&ne.map((re,me)=>e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-engine-row",children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"text-sm text-secondary",children:re.provider?ot(re.provider):"Awaiting engine"})}),e.jsx("td",{children:e.jsx(ri,{state:re.citationState,className:"rounded-none border-0 bg-transparent p-0 text-sm tracking-normal",label:Co(re.citationState,h)})}),x&&e.jsx("td",{children:e.jsx(ql,{queryId:re.queryId,sourceSnapshotIds:re.sourceSnapshotId?[re.sourceSnapshotId]:[],queryClass:re.queryClass,provider:re.provider,location:re.location??null})}),e.jsx("td",{children:e.jsx(yo,{history:re.runHistory,signal:h})}),e.jsx("td",{className:"evidence-change-cell",children:fe?null:e.jsx(Ao,{items:[oe[me]??re]})}),e.jsx("td",{children:e.jsx(T,{variant:"ghost",className:"min-h-11",type:"button",title:`View ${re.provider?ot(re.provider):"saved"} answer for ${re.query}`,onClick:Ae=>{Ae.stopPropagation(),d(re.id)},children:"View"})})]}),f==="detailed"&&e.jsx("tr",{className:"query-evidence-preview-row",children:e.jsx("td",{colSpan:z,children:e.jsx(lx,{item:re,mode:h,onViewFull:()=>d(re.id)},h)})})]},re.id))]},J)})]},E.queryClass??"unclassified"))]})}),w.totalRows===0&&(w.hasQuery||j!=="all"||g)?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ks,{page:w.page,pageSize:w.pageSize,visibleRows:w.rows.length,totalRows:w.totalRows,onPageChange:w.setPage,itemLabel:w.hasQuery||j!=="all"||g?"matches":"queries"})]}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",O==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function ox(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=gd(t),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function hi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function lx({item:t,mode:s,onViewFull:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1);if(s==="mentions")return e.jsx(Ro,{item:t,onViewFull:n});const c=t.evidenceUrls.length>0?t.evidenceUrls.map(d=>({uri:d,title:t.groundingSources.find(m=>m.uri===d)?.title})):t.groundingSources;return e.jsxs("div",{className:"query-evidence-preview space-y-3",children:[e.jsx("p",{className:"text-[13px] font-medium text-secondary",children:t.evidenceUrls.length>0?"Cited sources":c.length>0?"Grounding sources":"Cited domains"}),c.length>0?e.jsx("ul",{className:"space-y-4",children:c.slice(0,l?void 0:6).map((d,m)=>e.jsxs("li",{className:"min-w-0",children:[e.jsx(ki,{url:d.uri,title:d.title}),hi(t,xd(d.uri)??"")&&e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:"Competitor source"})]},`${m}-${d.uri}`))}):t.citedDomains.length>0?e.jsx("ul",{className:"space-y-1 text-sm text-secondary",children:t.citedDomains.slice(0,l?void 0:6).map(d=>e.jsxs("li",{className:"[overflow-wrap:anywhere]",children:[d,hi(t,d)?" · competitor source":""]},d))}):e.jsx("p",{className:"text-sm text-secondary",children:"No cited sources captured for this run."}),(c.length>6||c.length===0&&t.citedDomains.length>6)&&e.jsx(T,{type:"button",variant:"ghost",className:"min-h-11","aria-expanded":l,onClick:()=>i(d=>!d),children:l?"Show fewer sources":"View all sources"}),t.answerSnippet.trim()?e.jsxs("details",{open:a,className:"border-t border-subtle pt-1",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:d=>{d.preventDefault(),r(m=>!m)},children:"Answer text"}),a&&e.jsx(Ro,{item:t,onViewFull:n,contextOnly:!0})]}):e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."})]})}function Ro({item:t,onViewFull:s,contextOnly:n=!1}){const{matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}=t,c=o.useMemo(()=>ox({matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}),[a,r,l,i]);if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."});const m=t.answerSnippet.length>jo;return e.jsxs("div",{className:"query-evidence-preview space-y-3",children:[!n&&e.jsx("p",{className:"text-[13px] font-medium text-secondary",children:"Answer text"}),e.jsx(Ti,{headingLevel:4,highlightGroups:c,previewLength:jo,children:t.answerSnippet}),(!n&&t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("dl",{className:"space-y-2 text-[13px] leading-6 text-secondary",children:[!n&&t.citedDomains.length>0&&e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Cited domains"}),e.jsxs("dd",{className:"flex flex-wrap gap-x-3 gap-y-1",children:[t.citedDomains.slice(0,6).map(u=>e.jsxs("span",{className:"[overflow-wrap:anywhere]",children:[u,hi(t,u)?" · competitor source":""]},`c-${u}`)),t.citedDomains.length>6&&e.jsxs("span",{children:["+",t.citedDomains.length-6," more"]})]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Competitors in answer"}),e.jsxs("dd",{className:"flex flex-wrap gap-x-3 gap-y-1",children:[t.mentionedCompetitorDomains.slice(0,4).map(u=>e.jsx("span",{className:"[overflow-wrap:anywhere]",children:u},`co-${u}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]})]}),m&&e.jsx(T,{type:"button",variant:"ghost",className:"min-h-11",onClick:u=>{u.stopPropagation(),s()},children:"View full answer"})]})}function Da({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}function pr({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:l=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(i=>e.jsx("button",{type:"button","aria-pressed":s===i,disabled:l,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>{i!==s&&fd("window"),n(i)},children:r?r(i):i},i))})}const Pr=lt[0],Ir=lt[1],Po=lt[2],Io=lt[3],cx=["both","server","ga4"],To={fontSize:11,paddingTop:6},Mo=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Lo=t=>typeof t=="number"?er(Math.round(t)):String(t),as=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function Tr(t,s){if(!t||s<2)return Array(s).fill(null);const n=t.endIndex-t.startIndex;if(n<=0)return Array(s).fill(null);const a=(t.end-t.start)/n;return Array.from({length:s},(r,l)=>l<t.startIndex||l>t.endIndex?null:t.start+(l-t.startIndex)*a)}function Mr({label:t,value:s,caption:n,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx(Ge,{text:a})]}),e.jsx("p",{className:"text-xl font-semibold text-primary tabular-nums",children:s}),e.jsx("p",{className:"text-xs text-muted mt-0.5",children:n})]})}function dx(t,s){return n=>{const{cx:a,cy:r,index:l,key:i}=n,c=l??-1;return!(t[c]!=null&&t[c-1]==null&&t[c+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function ux({projectName:t,sinceMinutes:s}){const[n,a]=o.useState(!0),[r,l]=o.useState(!0),[i,c]=o.useState("both"),d=tp(t,{sinceMinutes:s,granularity:"day",limit:1}),m=sp(t),p=qe({...El({client:Y,path:{name:t}}),enabled:!!t,staleTime:bn}).data?.connected===!0,x=qe({...Dl({client:Y,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&p,staleTime:bn}),h=o.useMemo(()=>d.data?.series?.points??[],[d.data]),y=o.useMemo(()=>{const L=x.data;return new Map((L?.days??[]).map(M=>[M.date,M.sessions]))},[x.data]),f=o.useMemo(()=>{const L=w=>w.measured!==!1;if(h.length===0||L(h[0]))return null;const M=h.findIndex(L)-1;return M<0?{from:h[0].bucket,to:h[h.length-1].bucket}:{from:h[0].bucket,to:h[M].bucket}},[h]),b=d.data?.series?.coverageStart??null,j=d.data?.series?.trends,A=o.useMemo(()=>{const L=Tr(j?.crawlerContentHits,h.length),M=Tr(j?.aiUserFetchHits,h.length),w=Tr(j?.aiReferralLandedHits,h.length);return h.map((U,F)=>({...U,crawlerContentHits:U.measured!==!1?as(U.crawlerContentHits):null,aiUserFetchHits:U.measured!==!1?as(U.aiUserFetchHits):null,aiReferralLandedHits:U.measured!==!1?as(U.aiReferralLandedHits):null,ga4Visits:y.get(U.bucket)??null,crawlTrend:L[F],fetchTrend:M[F],visitTrend:w[F]}))},[h,y,j]),P=d.data?.totals,C=P&&{crawlers:as(P.crawlerContentHits),fetches:as(P.aiUserFetchHits),visits:as(P.aiReferralLandedHits)},g=o.useMemo(()=>h.reduce((L,M)=>({crawlers:L.crawlers+as(M.crawlerContentHits),fetches:L.fetches+as(M.aiUserFetchHits),visits:L.visits+as(M.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[h]),v=C??g,S=v.crawlers>0||v.fetches>0||v.visits>0;if(d.isLoading)return e.jsx(ve,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(d.isError)return e.jsxs(ve,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!S){const L=m.data?.sources,M=L!==void 0&&L.length===0,w=!M&&b===null;return e.jsxs(ve,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:M?"No server-side traffic source connected yet.":w?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:M?"Connect a traffic source to see how AI engines read this site over time.":w?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(ve,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Mr,{label:"AI crawlers",value:er(v.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(Mr,{label:"AI page fetches",value:er(v.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(Mr,{label:"AI visitors",value:er(v.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),h.length>0&&e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-xs text-muted",children:[e.jsx("span",{className:"text-secondary font-semibold",children:"Latest day (UTC)"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(h[h.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(h[h.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(h[h.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:y.get(h[h.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(Ge,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:L=>a(L.target.checked),className:"accent-current"}),"Page fetches"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:L=>l(L.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(en,{width:"100%",height:206,children:e.jsxs(tn,{data:A,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(ba,{stroke:fa,vertical:!1}),e.jsx(sn,{dataKey:"bucket",tick:_t,stroke:ds,tickFormatter:wn,minTickGap:28}),e.jsx(nn,{tick:_t,stroke:ds,width:48,allowDecimals:!1}),e.jsx(an,{contentStyle:es.contentStyle,labelStyle:es.labelStyle,itemStyle:es.itemStyle,labelFormatter:Pt,formatter:Lo}),f&&e.jsx(ni,{x1:f.from,x2:f.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(or,{wrapperStyle:To,iconType:"plainline",iconSize:14,formatter:L=>Mo.has(L)?"":L}),e.jsx(Js,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Pr,fill:Pr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Js,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Ir,fill:Ir,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Fs,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Pr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Fs,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Ir,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(Ge,{text:"Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other."})]}),e.jsx(pr,{windows:cx,value:i,onChange:c,label:"Visit measurement source",formatOption:L=>L==="ga4"?"GA4":L==="both"?"Both":"Server"})]}),e.jsx(en,{width:"100%",height:176,children:e.jsxs(tn,{data:A,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(ba,{stroke:fa,vertical:!1}),e.jsx(sn,{dataKey:"bucket",tick:_t,stroke:ds,tickFormatter:wn,minTickGap:28}),e.jsx(nn,{tick:_t,stroke:ds,width:48,allowDecimals:!1}),e.jsx(an,{contentStyle:es.contentStyle,labelStyle:es.labelStyle,itemStyle:es.itemStyle,labelFormatter:Pt,formatter:Lo}),f&&e.jsx(ni,{x1:f.from,x2:f.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(or,{wrapperStyle:To,iconType:"plainline",iconSize:14,formatter:L=>Mo.has(L)?"":L}),i!=="ga4"&&e.jsx(Fs,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Po,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Fs,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Io,strokeWidth:1.8,strokeDasharray:"5 3",dot:dx(A.map(L=>L.ga4Visits),Io)}),r&&i!=="ga4"&&e.jsx(Fs,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Po,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const mx=6,Hn="__other__",Gn="_socialTotal";function hx(t,s=mx){const n=new Map;for(const u of t)n.set(u.source,(n.get(u.source)??0)+u.sessions);const a=[...n.entries()].sort((u,p)=>p[1]!==u[1]?p[1]-u[1]:u[0].localeCompare(p[0])),r=a.slice(0,s),l=new Set(r.map(([u])=>u)),i=Math.max(0,a.length-s),c=new Map;for(const u of t){let p=c.get(u.date);p||(p={date:u.date,[Gn]:0},c.set(u.date,p));const x=l.has(u.source)?u.source:Hn;p[x]=(p[x]??0)+u.sessions,p[Gn]=(p[Gn]??0)+u.sessions}const d=[...c.values()].sort((u,p)=>String(u.date).localeCompare(String(p.date))),m=r.map(([u])=>u);return i>0&&m.push(Hn),{data:d,sources:m,otherCount:i}}function _n(t){return t.replace(/\+/g," ")}function wc(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const $o="_totalSessions",qo="_organicSessions";function px(t,s){const n=new Map;for(const i of s)n.set(i.date,{[$o]:i.sessions,[qo]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[$o]:0,[qo]:0},n.set(i.date,c));for(const d of i.bySource)c[d.source]=(c[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([i],[c])=>i.localeCompare(c)).map(([i,c])=>({date:i,...c})),r=a.map(i=>i.date),l=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:l}}const xx=["7d","30d","90d"],gx={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Ys=lt,pi=us.textDim,Sc=us.textFaint,na=25;function fx(t){return ac(t.landingPage)}const yx=25,bx=10,Lr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Oa(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Cc(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function vx({projectName:t}){const{data:s,isLoading:n,isError:a}=np(t);if(n)return e.jsx(ve,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(ve,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!ie()&&e.jsx(Ts,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(ve,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ie()&&e.jsxs(e.Fragment,{children:[e.jsx(Ts,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(ve,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(l=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(je,{tone:ap(l.status),children:l.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:l.lastSyncedAt?Cc(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ie()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Ts,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function jx({projectName:t}){const[s,n]=o.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(vx,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(pr,{windows:xx,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(Nx,{projectName:t,window:s}),e.jsx(ux,{projectName:t,sinceMinutes:gx[s]})]})}function Nx({projectName:t,window:s}){const n=ms(),a=s??"30d",[r,l]=o.useState(null),[i,c]=o.useState(null),[d,m]=o.useState(!0),[u,p]=o.useState(!1),[x,h]=o.useState(!1),[y,f]=o.useState(null),[b,j]=o.useState(null),[A,P]=o.useState("sessions"),[C,g]=o.useState("desc"),[v,S]=o.useState("sessions"),[L,M]=o.useState("desc"),[w,U]=o.useState("sessions"),[F,z]=o.useState("desc"),[_,B]=o.useState("sessions"),[te,O]=o.useState("desc"),[V,Q]=o.useState(Lr),[E,J]=o.useState([]),[k,H]=o.useState([]),[se,ne]=o.useState(!1);async function oe(ee){m(!0),f(null);try{const Ee=await n.fetchQuery({...El({client:Y,path:{name:t}}),staleTime:bn});if(ee.current)return;if(l(Ee),!Ee.connected){c(null),Q(Lr),J([]),H([]),m(!1);return}const Te=a==="all"?void 0:a,Pe=await n.fetchQuery({...yd({client:Y,path:{name:t},query:Te?{window:Te}:void 0}),staleTime:bn}),Bt=Pe.windowStart||Pe.windowEnd?{...Pe.windowStart?{startDate:Pe.windowStart}:{},...Pe.windowEnd?{endDate:Pe.windowEnd}:{}}:void 0,[Wt,ht,Yt]=await Promise.all([n.fetchQuery({...Dl({client:Y,path:{name:t},query:Te?{window:Te}:void 0}),staleTime:bn}).catch(()=>Lr),n.fetchQuery({...bd({client:Y,path:{name:t},query:Te?{window:Te}:void 0}),staleTime:bn}).catch(()=>[]),n.fetchQuery({...vd({client:Y,path:{name:t},query:Bt}),staleTime:bn}).catch(()=>[])]);if(ee.current)return;c(Pe),Q(Wt),J(ht),H(Yt),m(!1)}catch(Ee){if(ee.current)return;f(Ee instanceof Error?Ee.message:"Failed to load GA4 data"),m(!1)}}o.useEffect(()=>{const ee={current:!1};return oe(ee),()=>{ee.current=!0}},[t,a,n]);async function ke(){p(!0),f(null),j(null);try{const ee=await Ol(t);j(`Synced ${ee.rowCount.toLocaleString()} page rows, ${ee.aiReferralCount.toLocaleString()} AI and ${ee.socialReferralCount.toLocaleString()} social referral rows (${ee.days} days)`),await Tt(n,"ga"),await oe({current:!1})}catch(ee){f(ee instanceof Error?ee.message:"Sync failed")}finally{p(!1)}}async function X(){h(!0),f(null),j(null);try{await jd(t),await Tt(n,"ga"),l({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),j("GA4 disconnected")}catch(ee){f(ee instanceof Error?ee.message:"Disconnect failed")}finally{h(!1)}}function ue(ee){G.setPage(1),A===ee?g(Ee=>Ee==="desc"?"asc":"desc"):(P(ee),g("desc"))}function fe(ee){v===ee?M(Ee=>Ee==="desc"?"asc":"desc"):(S(ee),M("desc"))}function Z(ee){w===ee?z(Ee=>Ee==="desc"?"asc":"desc"):(U(ee),z("desc"))}const ce=o.useMemo(()=>i?.topPages?[...i.topPages].sort((ee,Ee)=>{const Te=ee[A],Pe=Ee[A];return typeof Te=="string"&&typeof Pe=="string"?C==="asc"?Te.localeCompare(Pe):Pe.localeCompare(Te):C==="asc"?Te-Pe:Pe-Te}):[],[i?.topPages,A,C]),G=Nn({rows:ce,getSearchText:ee=>ac(ee.landingPage),pageSize:bx}),de=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((ee,Ee)=>{const Te=ee[v],Pe=Ee[v];return typeof Te=="string"&&typeof Pe=="string"?L==="asc"?Te.localeCompare(Pe):Pe.localeCompare(Te):L==="asc"?Te-Pe:Pe-Te}):[],[i?.aiReferrals,v,L]),De=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((ee,Ee)=>{const Te=ee[_],Pe=Ee[_];return typeof Te=="string"&&typeof Pe=="string"?te==="asc"?Te.localeCompare(Pe):Pe.localeCompare(Te):te==="asc"?Te-Pe:Pe-Te}):[],[i?.aiReferralLandingPages,_,te]),Re=Nn({rows:De,getSearchText:fx,pageSize:yx}),re=Re.totalRows>0?`${Re.totalRows.toLocaleString()} ${Re.hasQuery?Re.totalRows===1?"match":"matches":Re.totalRows===1?"row":"rows"}`:Re.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function me(ee){Re.setPage(1),_===ee?O(Ee=>Ee==="desc"?"asc":"desc"):(B(ee),O("desc"))}const Ae=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((ee,Ee)=>{const Te=ee[w],Pe=Ee[w];return typeof Te=="string"&&typeof Pe=="string"?F==="asc"?Te.localeCompare(Pe):Pe.localeCompare(Te):F==="asc"?Te-Pe:Pe-Te}):[],[i?.socialReferrals,w,F]),{socialChartData:st,socialChartSources:pe,socialOtherCount:D}=o.useMemo(()=>{const ee=hx(k);return{socialChartData:ee.data,socialChartSources:ee.sources,socialOtherCount:ee.otherCount}},[k]),{chartData:Oe,chartSources:I,dateRange:ye}=o.useMemo(()=>{const ee=px(V,E);return{chartData:ee.data,chartSources:ee.sources,dateRange:ee.dateRange}},[V,E]);if(d&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return ie()||Ms()?e.jsx(ve,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(wx,{projectName:t,onConnected:()=>{(async()=>(await Tt(n,"ga"),await oe({current:!1})))()}});const _e=i?.organicSharePctDisplay??"0%",ze=i?.channelBreakdown?.organic.sharePctDisplay??_e,Be=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,be=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,xt=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Ke=i?.paidAiSessionsBySession??0,Xe=i?.paidAiSharePctBySessionDisplay??"0%",ts=i?new Set(i.aiReferrals.map(ee=>ee.source.toLowerCase())).size:0,it=de[0]??null,nt=i?.totalDirectSessions??0,ut=i?.directSharePctDisplay??"0%",wt=i?.channelBreakdown?.direct.sessions??nt,Mt=i?.channelBreakdown?.direct.sharePctDisplay??ut,Ve=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,R=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Me=i?.socialSessions??0,we=i?.socialSharePctDisplay??"0%",Le=i?.channelBreakdown?.social.sessions??Me,At=i?.channelBreakdown?.social.sharePctDisplay??we,It=i?new Set(i.socialReferrals.map(ee=>ee.source.toLowerCase())).size:0,St=Ae[0]??null;return e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:y}),b&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:b}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!ie()&&!Ms()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(T,{variant:"outline",size:"sm",disabled:u,onClick:Je(ke),children:[e.jsx(ya,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(T,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Je(X),children:[e.jsx(Uh,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"mb-4 flex items-start justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Ge,{text:`Aggregated traffic metrics from Google Analytics 4.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]})}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx($r,{value:Oa(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx($r,{value:Oa(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${_e} of total`,tone:"positive"}),e.jsx($r,{value:i.totalUsers===null?"—":Oa(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!ie()&&!Ms()&&e.jsxs(T,{variant:"outline",size:"sm",disabled:u,onClick:Je(ke),children:[e.jsx(ya,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Ge,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),ye&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(ye.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(ye.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),Oe.length>0&&e.jsxs(ve,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:I.length>0?"AI vs. total sessions":"All sessions (baseline)"}),I.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),I.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:Oe,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(sn,{dataKey:"date",tick:_t,tickLine:!1,axisLine:{stroke:ds},tickFormatter:wn}),e.jsx(nn,{tick:_t,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...es,labelFormatter:Pt,formatter:(ee,Ee)=>{const Te=typeof ee=="number"?ee.toLocaleString():String(ee??0),Pe=String(Ee??"");return Pe==="_totalSessions"?[Te,"Total Sessions"]:Pe==="_organicSessions"?[Te,"Organic Sessions"]:[Te,Pe]}}),e.jsx(or,{wrapperStyle:{fontSize:11,color:us.text},formatter:ee=>ee==="_totalSessions"?"Total Sessions":ee==="_organicSessions"?"Organic Sessions":ee}),e.jsx(Js,{type:"monotone",dataKey:"_totalSessions",stroke:us.textFaint,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),I.map((ee,Ee)=>e.jsx(Js,{type:"monotone",dataKey:ee,stackId:"ai",stroke:Ys[Ee%Ys.length],fill:Ys[Ee%Ys.length],fillOpacity:.4,strokeWidth:1.5},ee))]})})})]}),e.jsxs(ve,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(ys,{label:"Organic",value:ze,hint:`${Be.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(ys,{label:"Social",value:At,hint:`${Le.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(ys,{label:"Direct",value:Mt,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(ys,{label:"Visitors from AI (at least)",value:xt,hint:Ke>0?`${be.toLocaleString()} sessions · ${Ke.toLocaleString()} paid`:`${be.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(ys,{label:"Other channels",value:R,hint:`${Ve.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."})]}),it&&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:it.source})," via ",it.medium,", accounting for ",it.sessions.toLocaleString()," sessions.",Ke>0&&e.jsxs("span",{children:[" Paid AI: ",Ke.toLocaleString()," sessions (",Xe,")."]})]})]}),e.jsxs(ve,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${ts} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(rs,{label:"Source",sortKey:"source",current:v,dir:L,onSort:fe,align:"left"}),e.jsx(rs,{label:"Medium",sortKey:"medium",current:v,dir:L,onSort:fe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:v,dir:L,onSort:fe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:de.map(ee=>e.jsx(Cx,{referral:ee},`${ee.source}:${ee.medium}:${ee.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(ve,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:re})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Zs,{value:Re.query,onChange:Re.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Re.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(rs,{label:"Landing Page",sortKey:"landingPage",current:_,dir:te,onSort:me,align:"left"}),e.jsx(rs,{label:"Source",sortKey:"source",current:_,dir:te,onSort:me,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:_,dir:te,onSort:me,align:"right"})]})}),e.jsx("tbody",{children:Re.rows.map(ee=>e.jsx(kx,{row:ee},`${ee.landingPage}:${ee.source}:${ee.medium}:${ee.sourceDimension}`))})]})}),e.jsx(Ks,{page:Re.page,pageSize:Re.pageSize,visibleRows:Re.rows.length,totalRows:Re.totalRows,onPageChange:Re.setPage,itemLabel:Re.hasQuery?"matches":"rows"})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No landing pages match this filter"}),e.jsx("button",{type:"button",onClick:()=>Re.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Ge,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(ve,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(ys,{label:"Social Sessions",value:Oa(Me),hint:`${Me.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(ys,{label:"Share of Traffic",value:we,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(ys,{label:"Platforms",value:String(It),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."})]}),St&&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:`${St.source} via ${St.medium}`,children:wc(_n(St.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:St.medium,children:["via ",_n(St.medium)," · ",St.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(ys,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(ys,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(ys,{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."})]})]})]}),st.length>0&&e.jsxs(ve,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),D>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",pe.length-1," sources · ",D," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:st,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(sn,{dataKey:"date",tick:_t,tickLine:!1,axisLine:{stroke:ds},tickFormatter:wn}),e.jsx(nn,{tick:_t,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...es,labelFormatter:Pt,formatter:(ee,Ee)=>{const Te=typeof ee=="number"?ee.toLocaleString():String(ee??0),Pe=String(Ee??"");if(Pe===Gn)return[Te,"Total Social"];if(Pe===Hn){const Bt=`Other (${D} source${D===1?"":"s"})`;return[Te,Bt]}return[Te,_n(Pe)]}}),e.jsx(Js,{type:"monotone",dataKey:Gn,stroke:Sc,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),pe.map((ee,Ee)=>{const Pe=ee===Hn?pi:Ys[Ee%Ys.length];return e.jsx(Js,{type:"monotone",dataKey:ee,stackId:"social",stroke:Pe,fill:Pe,fillOpacity:.4,strokeWidth:1.5},ee)})]})})}),e.jsx(Rx,{sources:pe,otherCount:D})]}),e.jsxs(ve,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Ae.length>na&&!se?`Top ${na} of ${Ae.length}`:`${Ae.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(rs,{label:"Source",sortKey:"source",current:w,dir:F,onSort:Z,align:"left"}),e.jsx(rs,{label:"Medium",sortKey:"medium",current:w,dir:F,onSort:Z,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:w,dir:F,onSort:Z,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(se?Ae:Ae.slice(0,na)).map(ee=>e.jsx(Ax,{referral:ee},`${ee.source}:${ee.medium}:${ee.channelGroup}`))})]})}),Ae.length>na&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>ne(ee=>!ee),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:se?`Show top ${na}`:`Show all ${Ae.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(Ge,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx(Zs,{value:G.query,onChange:G.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(rs,{label:"Landing Page",sortKey:"landingPage",current:A,dir:C,onSort:ue,align:"left"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:A,dir:C,onSort:ue,align:"right"}),e.jsx(rs,{label:"Organic",sortKey:"organicSessions",current:A,dir:C,onSort:ue,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:G.rows.map(ee=>e.jsx(Sx,{page:ee},ee.landingPage))})]})}),G.totalRows===0&&G.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Ks,{page:G.page,pageSize:G.pageSize,visibleRows:G.rows.length,totalRows:G.totalRows,onPageChange:G.setPage,itemLabel:G.hasQuery?"matches":"pages"})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${Cc(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function wx({projectName:t,onConnected:s}){const[n,a]=o.useState(""),[r,l]=o.useState(null),[i,c]=o.useState(null),[d,m]=o.useState(!1),[u,p]=o.useState(null),x=o.useRef(null),h=o.useCallback(f=>{const b=f.target.files?.[0];if(!b)return;p(null),l(b.name);const j=new FileReader;j.onload=()=>{const A=j.result;try{const P=JSON.parse(A);if(!P.client_email||!P.private_key){p("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),c(null);return}c(A)}catch{p("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},j.onerror=()=>{p("Failed to read file."),c(null)},j.readAsText(b)},[]);async function y(){if(p(null),!n.trim()){p("Property ID is required.");return}if(!i){p("Please upload a service account key file.");return}m(!0);try{await Nd(t,{propertyId:n.trim(),keyJson:i});try{await Ol(t)}catch{}s()}catch(f){p(f instanceof Error?f.message:"Failed to connect GA4")}finally{m(!1)}}return e.jsxs(ve,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),u&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:u}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:f=>a(f.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:x,type:"file",accept:".json,application/json",onChange:h,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>x.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(Bh,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(T,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:Je(y),children:d?"Connecting & syncing…":"Connect GA4"})]})}function rs({label:t,sortKey:s,current:n,dir:a,onSort:r,align:l}){const i=n===s;return e.jsx("th",{className:`py-1 ${l==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>r(s),"aria-label":`Sort by ${t}${i?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,i&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const kc={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function $r({value:t,label:s,subtitle:n,tone:a}){return e.jsxs("div",{className:"rounded-lg bg-surface border border-default px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${kc[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function ys({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Ge,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${kc[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Sx({page:t}){const s=tt(t.organicShare);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:s})]})}const Ac={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Rc={session:"Detected via GA4 sessionSource (referrer or utm_source for this session)",first_user:"Detected via GA4 firstUserSource (referrer from the user's first-ever visit)",manual_utm:"Detected via GA4 sessionManualSource (explicit utm_source parameter for the session)"};function Cx({referral:t}){const s=tt(t.share),n=Ac[t.sourceDimension]??t.sourceDimension,a=Rc[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",l=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:l,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:a,children:n})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:s})]})}function kx({row:t}){const s=Ac[t.sourceDimension]??t.sourceDimension,n=Rc[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(sr,{value:t.landingPage,className:"whitespace-nowrap"})}),e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()})]})}function Ax({referral:t}){const s=tt(t.share),n=t.channelGroup==="Paid Social"?"Paid":"Organic",a=_n(t.source),r=_n(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:a}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:n})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:s})]})}function Rx({sources:t,otherCount:s}){const n=[{key:Gn,color:Sc,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Hn)n.push({key:Hn,color:pi,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=_n(r);n.push({key:r,color:Ys[a%Ys.length]??pi,label:wc(l,32),tooltip:l})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function Px(t){const s=t.details;if(t.code!=="FORBIDDEN"||!s||s.reason!=="gsc-api-disabled")return null;const n=typeof s.projectNumber=="string"?s.projectNumber:void 0;return{title:"Enable the Search Console API",message:`Your Google Cloud project${n?` (${n})`:""} hasn't enabled the Search Console API. Enable the Search Console API and the Indexing API, wait ~2–5 minutes, then retry.`,enableUrl:typeof s.enableUrl=="string"?s.enableUrl:void 0,indexingApiUrl:typeof s.indexingApiUrl=="string"?s.indexingApiUrl:void 0,projectNumber:n}}const Ix="Search Console is not connected yet. Your Canonry team can set this up.",Tx=["7d","30d","90d","all"],Fa=500,Eo=[{key:"clicks",label:"Clicks",color:lt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:lt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Yn.caution,format:t=>tt(t)},{key:"position",label:"Avg position",color:lt[2],inverted:!0,format:t=>t.toFixed(1)}],Hs=25,Mx="canonry:google-oauth-complete";function Lx(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const i=t.prior[s],c=t.trailing[s];return i!==null&&c!==null&&i<=0&&c>0?`new in the last ${a}d`:i===null||i<=0?`no prior ${a}d to compare`:c===null?`no value in the last ${a}d`:"comparison unavailable"}return r===0?`→ no change vs prior ${a}d`:`${(n?r<0:r>0)?"↑":"↓"} ${tt(Math.abs(r))} vs prior ${a}d`}function $x(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,l=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,c=`${r.startDate} to ${r.endDate}`,d=`Tile percentages compare these ${s} ${l} (${c}) with the ${s} ${l} before them (${i}).`;return n!=="split-window"?d:`${d} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function Do(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Oo(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 Fo(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function qx({projectName:t,refreshNonce:s}){const n=ms(),{isAdmin:a}=rn(),r=Ms(),[l,i]=o.useState(!1),[c,d]=o.useState([]),[m,u]=o.useState([]),[p,x]=o.useState([]),[h,y]=o.useState(null),[f,b]=o.useState([]),[j,A]=o.useState([]),[P,C]=o.useState(null),[g,v]=o.useState(""),[S,L]=o.useState(""),[M,w]=o.useState("30"),[U,F]=o.useState(!1),[z,_]=o.useState("30d"),[B,te]=o.useState(["clicks","impressions"]),[O,V]=o.useState(!0),[Q,E]=o.useState(null),[J,k]=o.useState(0),[H,se]=o.useState({startDate:"",endDate:"",query:"",page:""}),[ne,oe]=o.useState(0),[ke,X]=o.useState(!1),[ue,fe]=o.useState(0),[Z,ce]=o.useState(!1),[G,de]=o.useState(""),[De,Re]=o.useState(!0),[re,me]=o.useState(!1),[Ae,st]=o.useState(!1),[pe,D]=o.useState(!1),[Oe,I]=o.useState(!1),[ye,_e]=o.useState(!1),[ze,Be]=o.useState(!1),[be,xt]=o.useState(null),[Ke,Xe]=o.useState(!1),[ts,it]=o.useState(!1),[nt,ut]=o.useState(null),[wt,Mt]=o.useState(null),[Ve,R]=o.useState([]),[Me,we]=o.useState(new Set),[Le,At]=o.useState({}),[It,St]=o.useState(new Set),[ee,Ee]=o.useState(""),[Te,Pe]=o.useState(null),[Bt,Wt]=o.useState(""),[ht,Yt]=o.useState(!1),[Ze,Xt]=o.useState(!1),[hs,$s]=o.useState(!1),[ps,Us]=o.useState(!1),[gt,qs]=o.useState("indexed"),[vt,ct]=o.useState(null),Lt=!!(H.query.trim()||H.page.trim()||vt),xs=vt!==null,bs=o.useMemo(()=>{if(!vt)return p;const{key:N,dir:W}=vt;return[...p].sort((le,Ne)=>{const at=N===vn.CTR?Number.isFinite(le.ctr)?le.ctr:0:le[N],et=N===vn.CTR?Number.isFinite(Ne.ctr)?Ne.ctr:0:Ne[N];return W==="asc"?at-et:et-at})},[p,vt]),$t=Nn({rows:bs,pageSize:Ds}),Ft=Z?$t.rows:bs,ft=Nn({rows:(nt??[]).filter(N=>N.path.toLowerCase().includes(ee.trim().toLowerCase())),pageSize:Ds}),[qt,Bs]=o.useState([]),[Ct,ss]=o.useState(null),[Jt,K]=o.useState(1),ae=o.useMemo(()=>{if(qt.length<2)return null;const N=qt[qt.length-1],W=qt[qt.length-2];return{indexed:N.indexed-W.indexed,notIndexed:N.notIndexed-W.notIndexed}},[qt]);o.useEffect(()=>{K(1)},[be,gt,Ct]);const Ce=o.useMemo(()=>Ct?(be?.reasonGroups??[]).find(N=>N.reason===Ct):void 0,[be,Ct]),he=o.useMemo(()=>be?gt==="indexed"?be.indexed:gt==="deindexed"?be.deindexed:gt==="notIndexed"?Ct?Ce?.urls??[]:(be.reasonGroups??[]).length===0?be.notIndexed:[]:[]:[],[be,gt,Ct,Ce]),Ie=Math.max(1,Math.ceil(he.length/Hs)),Qe=Math.min(Math.max(1,Jt),Ie),mt=(Qe-1)*Hs,jt=o.useMemo(()=>be?.indexed.slice(mt,mt+Hs)??[],[be,mt]),gs=o.useMemo(()=>be?.notIndexed.slice(mt,mt+Hs)??[],[be,mt]),q=o.useMemo(()=>be?.deindexed.slice(mt,mt+Hs)??[],[be,mt]),Se=o.useMemo(()=>(Ce?.urls??[]).slice(mt,mt+Hs),[Ce,mt]),[rt,Et]=o.useState(!1),[Zt,Ue]=o.useState(null),[yt,vs]=o.useState(null),[Vs,ns]=o.useState(null);function xr(N,W){const le=rp(N),Ne=Px(le);Ne?(vs(Ne),Ue(null)):(vs(null),Ue(le.message||W))}const Rt=c.find(N=>N.connectionType==="gsc"),fs=(Rt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),Cn=Ve.length>0?Ve:(nt??[]).map(N=>N.path),kn=Cn.filter(N=>nt?.some(W=>W.path===N&&W.isSitemapsIndex)).length,gr=kn===1?"Resubmit sitemap index":kn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Jn=p.length>0||f.length>0||j.length>0,Ra=wd(),Pa=Sd();async function An(N,W=!1){if(r){u([]);return}if(!N){u([]),v("");return}st(!0);try{const{sites:le}=await n.fetchQuery({...Fd({client:Y,path:{name:t}}),staleTime:W?0:zt});u(le),v(N.propertyId??le[0]?.siteUrl??""),vs(null)}catch(le){u([]),xr(le,"Failed to load Search Console properties")}finally{st(!1)}}async function on(N){I(!0);const W=N??ne;try{const le=Lt?Fa:Ds,Ne=Lt?0:W,at={limit:String(le)};H.startDate&&(at.startDate=H.startDate),H.endDate&&(at.endDate=H.endDate),H.query&&(at.query=H.query),H.page&&(at.page=H.page),Ne>0&&(at.offset=String(Ne)),z&&z!=="all"&&!H.startDate&&(at.window=z);const et=await n.fetchQuery({...Rd({client:Y,path:{name:t},query:at}),staleTime:zt}),Ye=et.rows;Lt?(X(!1),x(Ye),fe(Ye.length),ce(!0)):(X(Ne+Ye.length<et.totalMatching),x(Ye),fe(0),ce(!1))}catch(le){x([]),X(!1),fe(0),Ue(le instanceof Error?le.message:"Failed to load GSC performance data")}finally{I(!1)}}async function Qs(){try{const N={};H.startDate&&(N.startDate=H.startDate),H.endDate&&(N.endDate=H.endDate),z&&z!=="all"&&!H.startDate&&(N.window=z);const W=await n.fetchQuery({...Ad({client:Y,path:{name:t},query:N}),staleTime:zt});y(W)}catch{y(null)}}async function Es(N=!1){_e(!0);try{const W=G.trim()||void 0,le={limit:"20"};W&&(le.url=W);const[Ne,at]=await Promise.all([n.fetchQuery({...Dd({client:Y,path:{name:t},query:le}),staleTime:N?0:zt}),n.fetchQuery({...Od({client:Y,path:{name:t}}),staleTime:N?0:zt})]);b(Ne),A(at)}catch(W){b([]),A([]),Ue(W instanceof Error?W.message:"Failed to load GSC inspection history")}finally{_e(!1)}}async function Rn(N=!1){Xe(!0);try{const[W,le]=await Promise.all([n.fetchQuery({...Td({client:Y,path:{name:t}}),staleTime:N?0:zt}),n.fetchQuery({...Md({client:Y,path:{name:t}}),staleTime:N?0:zt}).catch(()=>[])]);xt(W),Bs(le)}catch(W){xt(null),Bs([]),Ue(W instanceof Error?W.message:"Failed to load coverage data")}finally{Xe(!1)}}async function Pn(N){Et(!0),Ue(null);try{const W=await to(t,{urls:N}),{succeeded:le,failed:Ne,total:at}=W.summary;Fe({title:"Indexing requested",detail:Ne===0?`${le} URL${le!==1?"s":""} submitted for indexing.`:`${le}/${at} submitted successfully, ${Ne} failed.`,tone:Ne===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(W){Ue(W instanceof Error?W.message:"Failed to request indexing")}finally{Et(!1)}}async function Xn(){Et(!0),Ue(null);try{const N=await to(t,{urls:[],allUnindexed:!0}),{succeeded:W,failed:le,total:Ne}=N.summary;Fe({title:"Indexing requested",detail:le===0?`${W} unindexed URL${W!==1?"s":""} submitted for indexing.`:`${W}/${Ne} submitted successfully, ${le} failed.`,tone:le===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(N){Ue(N instanceof Error?N.message:"Failed to request indexing")}finally{Et(!1)}}async function ln(){it(!0),Ue(null);try{const N=await Nr(t);n.setQueryData(Ld({client:Y,path:{name:t}}),N),ut(N.sitemaps),Mt(N.summary),R(N.preferredSubmissionUrls),we(new Set),At({}),N.sitemaps.length===0&&ns("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(N){Ue(N instanceof Error?N.message:"Failed to list sitemaps")}finally{it(!1)}}async function Ia(N){const W=Me.has(N);if(we(le=>{const Ne=new Set(le);return W?Ne.delete(N):Ne.add(N),Ne}),!(W||Le[N])){St(le=>new Set(le).add(N));try{const le=await Nr(t,N);At(Ne=>({...Ne,[N]:le.sitemaps}))}catch(le){Ue(le instanceof Error?le.message:"Failed to load sitemap files")}finally{St(le=>{const Ne=new Set(le);return Ne.delete(N),Ne})}}}async function zs(N){if(!fs||N.length===0)return;const W=[...new Set(N)];Xt(!0),Ue(null),Pe({completed:0,total:W.length});let le=0,Ne=0,at=0,et=null;try{for(let Dt=0;Dt<W.length;Dt+=50){const dt=W.slice(Dt,Dt+50);try{const $e=await $d(t,dt);le+=$e.summary.accepted,Ne+=$e.summary.failed,at+=dt.length,Pe({completed:at,total:W.length})}catch($e){at+=dt.length;const js=dt.length,un=W.length-at,In=$e instanceof Error?$e.message:"The batch request failed",Ns=`${le} accepted, ${Ne} failed, ${js} unconfirmed, ${un} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;et=`Sitemap submission stopped after a batch request failed. ${Ns} ${In}`,Ue(et),Fe({title:"Sitemap resubmission partially completed",detail:Ns,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const Ye=W.length;Fe({title:Ne===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:Ne===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${le}/${Ye} sitemap submissions; ${Ne} failed. Indexing is not guaranteed.`,tone:Ne===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Wt("")}catch(Ye){Ue(Ye instanceof Error?Ye.message:"Failed to submit sitemap to Google")}finally{Xt(!1),Pe(null),await ln(),et&&Ue(et)}}async function fr(){Xt(!0);const N=nt??[];try{const W=N.filter(Ne=>Ne.isSitemapsIndex),le=[];for(let Ne=0;Ne<W.length;Ne+=4)(await Promise.all(W.slice(Ne,Ne+4).map(async et=>{const Ye=Le[et.path];if(Ye)return Ye;const Dt=await Nr(t,et.path);return At(dt=>({...dt,[et.path]:Dt.sitemaps})),Dt.sitemaps}))).forEach((et,Ye)=>{le.push(...et.length>0?et.map(Dt=>Dt.path):[W[Ne+Ye].path])});await zs([...N.filter(Ne=>!Ne.isSitemapsIndex).map(Ne=>Ne.path),...le])}catch(W){Ue(W instanceof Error?W.message:"Failed to load sitemap files"),Xt(!1)}}async function yr(N){Yt(!0),Ue(null);try{await qd(t,"gsc",N),await Tt(n,"google"),d(W=>W.map(le=>le.connectionType==="gsc"?{...le,sitemapUrl:N}:le)),Fe({title:"Default sitemap updated",detail:N,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(W){Ue(W instanceof Error?W.message:"Failed to set the default sitemap")}finally{Yt(!1)}}async function cn(N){try{await Pa.mutateAsync({projectName:t,projectLabel:t,opts:N?{sitemapUrl:N}:void 0})}catch{}}async function Zn(){Re(!0),Ue(null);try{const[N,W]=await Promise.all([r||!a?Promise.resolve(null):Fl().catch(()=>null),n.fetchQuery({...Ai({client:Y,path:{name:t}}),staleTime:zt}).catch(()=>[])]);i(!!N?.google?.configured),d(W);const le=W.find(Ne=>Ne.connectionType==="gsc");await Promise.all([r?Promise.resolve():An(le),on(),Qs(),Es(),Rn(),!r&&le?.propertyId?ln():Promise.resolve()])}finally{Re(!1)}}o.useEffect(()=>{Zn()},[t,s,a]),o.useEffect(()=>{oe(0),E(null),se(N=>N.startDate||N.endDate?{...N,startDate:"",endDate:""}:N),k(N=>N+1),Qs()},[z]);const ea=o.useRef(!1);o.useEffect(()=>{if(!ea.current){ea.current=!0;return}oe(0),$t.setPage(1),on(0)},[J]);function ta(N){const W=Q===N?null:N;E(W),se(le=>({...le,startDate:W??"",endDate:W??""})),k(le=>le+1)}const dn=o.useRef(!1);o.useEffect(()=>{if(!dn.current){dn.current=!0;return}oe(0),on(0)},[xs]);async function sa(){if(!l){Ue("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}me(!0),Ue(null),ns(null);try{let N=function($e){if($e.source!==Ne||$e.origin!==at||!$e.data||typeof $e.data!="object")return;const js=$e.data;js.type!==Mx||js.connectionType!=="gsc"||dt(!0)};const{authUrl:W,redirectUri:le}=await Id(t,"gsc");if(!W.startsWith("https://accounts.google.com/")){Ue("Unexpected OAuth redirect URL. Please try again.");return}const Ne=window.open(W,"_blank","width=600,height=700");if(!Ne){window.location.assign(W);return}const at=le?new URL(le).origin:window.location.origin;let et=!1,Ye=null;const Dt=()=>{Ye!==null&&window.clearInterval(Ye),window.removeEventListener("message",N)},dt=async $e=>{if(!et){et=!0,Dt(),ns($e?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Tt(n,"google"),await Zn()}finally{ns(null)}}};window.addEventListener("message",N),ns("Finish the Google consent flow in the popup. This page will refresh automatically."),Ye=window.setInterval(()=>{Ne.closed&&dt(!1)},1e3)}catch(N){Ue(N instanceof Error?N.message:"Failed to start OAuth flow")}finally{me(!1)}}async function br(){Ue(null),ns(null);try{await Pd(t,"gsc"),await Tt(n,"google"),d(N=>N.filter(W=>W.connectionType!=="gsc")),u([]),v("")}catch(N){Ue(N instanceof Error?N.message:"Failed to disconnect")}}async function vr(){if(g){D(!0),Ue(null);try{await Kd(t,"gsc",g),await Tt(n,"google"),d(N=>N.map(W=>W.connectionType==="gsc"?{...W,propertyId:g}:W)),Fe({title:"GSC property updated",detail:`${t} is now linked to ${g}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(N){Ue(N instanceof Error?N.message:"Failed to save GSC property")}finally{D(!1)}}}async function Ta(){Ue(null),ns(null);try{await Ra.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(M,10)||void 0,full:U||void 0}}),await Tt(n,"gsc")}catch{}}async function Ma(){if(S.trim()){Be(!0),Ue(null),ns(null);try{const N=await Ed(t,S.trim());await Tt(n,"gsc"),C(N),L(""),await Es()}catch(N){Ue(N instanceof Error?N.message:"Failed to inspect URL")}finally{Be(!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"})]})}),yt&&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:yt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:yt.message}),(Tn(yt.enableUrl)||Tn(yt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Tn(yt.enableUrl)&&e.jsx("a",{href:Tn(yt.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 ↗"}),Tn(yt.indexingApiUrl)&&e.jsx("a",{href:Tn(yt.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:()=>vs(null),children:"×"})]})}),Zt&&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:[Zt,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Ue(null),children:"×"})]}),Vs&&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:[Vs,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>ns(null),children:"×"})]}),De?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Rt?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:Rt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",be?.lastInspectedAt?Ht(be.lastInspectedAt):"never"]}),!r&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Je(br),children:"Disconnect"})]}):a?e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(je,{tone:l?"caution":"negative",children:l?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:l?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[l?e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:re,onClick:Je(sa),children:re?"Opening…":"Connect Google Search Console"}):e.jsx(T,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ts,{to:"/settings",children:"Open Settings"})}),!l&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}):e.jsx(ve,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:Ix})}),(Rt||Jn)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Ge,{text:`${$x(h?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${Fa.toLocaleString()} matching rows while the table shows ${Ds} per page.`})]}),h?.window?.startDate&&h.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[h.window.startDate," to ",h.window.endDate,(h.window.daysSinceLatestData??0)>0&&` · latest data ${h.window.daysSinceLatestData} day${h.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{windows:Tx,value:z,onChange:N=>{_(N),oe(0),$t.setPage(1)},label:"Search Console time period",formatOption:N=>N==="all"?"All":N}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:Oe,onClick:()=>{oe(0),$t.setPage(1),on(0),Qs()},children:Oe?"Loading…":"Apply filters"})]})]}),h&&h.daily.length>0&&(()=>{const{totals:N,daily:W,trends:le,periodComparison:Ne}=h,et=Eo.filter($e=>B.includes($e.key)).map($e=>({dataKey:$e.key,label:$e.label,color:$e.color,axisId:$e.key,inverted:$e.inverted,formatValue:$e.format,trend:O?le?.[$e.key]??null:null})),Ye=$e=>N[$e]??null,Dt=new Map(W.map($e=>[$e.date,$e])),dt=W.length===0?[]:Cd(W[0].date,W[W.length-1].date).map($e=>Dt.get($e)??{date:$e});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Eo.map($e=>{const js=B.includes($e.key),un=Ye($e.key),In=un===null;return e.jsxs("button",{type:"button","aria-pressed":js,disabled:In,className:`rounded-md border px-3 py-2 text-left transition-colors ${js?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${In?"cursor-not-allowed opacity-50":""}`,onClick:()=>{te(Ns=>Ns.includes($e.key)?Ns.length===1?Ns:Ns.filter(La=>La!==$e.key):[...Ns,$e.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:js?$e.color:"transparent",border:`1px solid ${$e.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:$e.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:un===null?"—":$e.format(un)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Lx(Ne,$e.key,$e.inverted)})]},$e.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:O,onChange:$e=>V($e.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(ic,{data:dt,xKey:"date",series:et,xTickFormatter:wn,labelFormatter:Pt,onSelectX:ta,selectedX:Q})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:W.map($e=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":Q===$e.date,onClick:()=>ta($e.date),children:[Pt($e.date),": ",$e.clicks," clicks, ",$e.impressions," impressions"]},$e.date))}),Q&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Pt(Q)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>ta(Q),children:["Show all ",N.days," days"]})]}),N.position!==null&&(N.positionDays??N.days)<N.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",N.positionDays," of ",N.days," days. The rest have no property-level position recorded."]}),(N.position===null||N.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:H.startDate,onChange:N=>se(W=>({...W,startDate:N.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:H.endDate,onChange:N=>se(W=>({...W,endDate:N.target.value}))}),e.jsx(Zs,{value:H.query,onChange:N=>se(W=>({...W,query:N})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Zs,{value:H.page,onChange:N=>se(W=>({...W,page:N})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),p.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(vn).map(N=>e.jsx("th",{className:"text-right","aria-sort":vt?.key===N?vt.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:()=>{$t.setPage(1),ct(W=>W?.key===N?W.dir==="desc"?{key:N,dir:"asc"}:null:{key:N,dir:"desc"})},children:[kd[N],vt?.key===N?vt.dir==="desc"?" ↓":" ↑":""]})},N))]})}),e.jsx("tbody",{children:Ft.map((N,W)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:N.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:N.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(sr,{value:N.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:N.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.impressions.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:tt(N.ctr)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.position.toFixed(1)})]},`${N.date}:${N.query}:${N.page}:${W}`))})]})}),e.jsx(Ks,{page:Z?$t.page:Math.floor(ne/Ds)+1,pageSize:Ds,visibleRows:Ft.length,totalRows:Z?ue:void 0,hasNextPage:Z?void 0:ke,disabled:Oe,itemLabel:Z?"matches":"rows",onPageChange:N=>{if(Z){$t.setPage(N);return}const W=(N-1)*Ds;oe(W),on(W)}}),Z&&ue>=Fa?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Fa.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Ge,{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:[be&&be.notIndexed.length>0&&e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:rt,onClick:()=>{Xn()},children:rt?"Requesting…":`Request indexing (${be.notIndexed.length})`}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:Ke,onClick:()=>{Rn(!0)},children:Ke?"Loading…":"Reload saved coverage"})]})]}),be&&be.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const N=be.summary.indexedShare??0,W=be.summary.notIndexedShare??0,le=54,Ne=2*Math.PI*le,at=Ne*(1-N),et=Ne*W,Ye=Ne*N;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:le,fill:"none",stroke:us.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:le,fill:"none",stroke:Yn.positiveDeep,strokeWidth:"14",strokeDasharray:Ne,strokeDashoffset:at,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),be.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:le,fill:"none",stroke:us.textFaint,strokeWidth:"14",strokeDasharray:`${et} ${Ne-et}`,strokeDashoffset:-Ye,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-3xl font-bold tabular-nums text-primary",children:tt(be.summary.indexedShare)}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:be.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:be.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(be.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(be.reasonGroups??[]).length," ",(be.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),be.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:be.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(N=>{const W=N==="indexed"?be.indexed.length:N==="notIndexed"?be.notIndexed.length:be.deindexed.length,le=N==="indexed"?"Indexed":N==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":gt===N,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${gt===N?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{qs(N),ss(null)},children:[le," (",W,")"]},N)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[gt==="indexed"&&be.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:jt.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.crawlTime?N.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:N.isMobileFriendly===!0?"Yes":N.isMobileFriendly===!1?"No":"—"})]},N.id))})]}),gt==="notIndexed"&&!Ct&&(be.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:(be.reasonGroups??[]).map(N=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>ss(N.reason),onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),ss(N.reason))},tabIndex:0,role:"button","aria-label":`View ${N.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:N.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.count})]},N.reason))})]}),gt==="notIndexed"&&!Ct&&(be.reasonGroups??[]).length===0&&be.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:gs.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.coverageState??"Unknown"})]},N.id))})]}),gt==="notIndexed"&&Ct&&(()=>{const N=(be.reasonGroups??[]).find(W=>W.reason===Ct);return N?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>ss(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:N.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[N.count," affected page",N.count!==1?"s":""]})]}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:rt,onClick:()=>{Pn(N.urls.map(W=>W.url))},children:rt?"Requesting…":`Request indexing (${N.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Se.map(W=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:W.url}),e.jsx("td",{className:"text-secondary",children:W.crawlTime?W.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:rt,onClick:()=>{Pn([W.url])},title:"Request indexing",children:"Index"})})]},W.id))})]})]}):null})(),gt==="deindexed"&&be.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:q.map((N,W)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.previousState}),e.jsx("td",{className:"text-secondary",children:N.currentState}),e.jsx("td",{className:"text-secondary",children:N.transitionDate.split("T")[0]})]},`${N.url}-${W}`))})]}),(gt==="indexed"&&be.indexed.length===0||gt==="notIndexed"&&!Ct&&be.notIndexed.length===0||gt==="deindexed"&&be.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ks,{page:Qe,pageSize:Hs,visibleRows:Math.min(Hs,he.length-mt),totalRows:he.length,onPageChange:K,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":ps,onClick:()=>Us(N=>!N),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:ps?"Hide snapshots":qt.length>0?`View ${qt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",be.summary.indexed.toLocaleString()," indexed, ",be.summary.notIndexed.toLocaleString()," not indexed.",ae&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ae.indexed>=0?"+":"",ae.indexed.toLocaleString()," indexed, ",ae.notIndexed>=0?"+":"",ae.notIndexed.toLocaleString()," not indexed."]})]}),ps&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:qt.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:qt.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:N.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:N.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:N.notIndexed.toLocaleString()})]},N.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:Ke?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),!r&&e.jsxs(e.Fragment,{children:[e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Ge,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:ts||!Rt?.propertyId,onClick:()=>{ln()},children:ts?"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:Bt,onChange:N=>Wt(N.target.value),onKeyDown:N=>N.key==="Enter"&&void zs([Bt.trim()])}),e.jsx(T,{type:"button",size:"sm",disabled:!fs||Ze||!Bt.trim(),onClick:()=>{zs([Bt.trim()])},children:Ze?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(T,{type:"button",size:"sm",variant:"outline",disabled:!fs||Ze||Cn.length===0,onClick:()=>{zs(Cn)},children:Ze?"Resubmitting…":gr}),e.jsx(T,{type:"button",size:"sm",variant:"outline",disabled:!fs||Ze||!nt?.length,onClick:()=>{fr()},children:"Resubmit all files"}),wt&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",wt.indexes," index",wt.indexes===1?"":"es",", ",wt.files," file",wt.files===1?"":"s"]}),Te&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Te.completed,"/",Te.total]})]}),!fs&&Rt&&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:Je(sa),children:"Reconnect"})]}),nt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:nt.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Zs,{value:ee,onChange:N=>{Ee(N),ft.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:ft.rows.flatMap(N=>{const W=Do(N),le=Oo(N),Ne=Fo(N),at=Le[N.path]??[],et=Me.has(N.path),Ye=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(sr,{value:N.path})}),e.jsx("td",{className:"text-secondary",children:N.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":et,"aria-label":`${et?"Collapse":"Expand"} files in ${N.path}`,onClick:()=>{Ia(N.path)},children:It.has(N.path)?"Loading…":`${et?"▾":"▸"} Index${Le[N.path]?` (${at.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:Ne}),e.jsx("td",{className:"text-secondary",children:N.lastSubmitted?N.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:N.lastDownloaded?N.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:W.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:le||"—"}),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:!fs||Ze,onClick:()=>{zs([N.path])},children:N.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Rt?.sitemapUrl===N.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:ht,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{yr(N.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Pa.isPending,onClick:()=>{cn(N.path)},children:"Inspect URLs"})]})})]},N.path),Dt=N.isSitemapsIndex&&et?at.map(dt=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(sr,{value:dt.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Fo(dt)}),e.jsx("td",{className:"text-secondary",children:dt.lastSubmitted?dt.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:dt.lastDownloaded?dt.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Do(dt).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Oo(dt)||"—"}),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:!fs||Ze,onClick:()=>{zs([dt.path])},children:"Resubmit"}),Rt?.sitemapUrl===dt.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:ht,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{yr(dt.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Pa.isPending,onClick:()=>{cn(dt.path)},children:"Inspect URLs"})]})})]},`${N.path}:${dt.path}`)):[];return[Ye,...Dt]})})]}),e.jsx(Ks,{page:ft.page,pageSize:Ds,visibleRows:ft.rows.length,totalRows:ft.totalRows,onPageChange:ft.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(ve,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:S,onChange:N=>L(N.target.value),onKeyDown:N=>N.key==="Enter"&&void Ma()}),e.jsx(T,{type:"button",size:"sm",disabled:ze||!Rt?.propertyId||!S.trim(),onClick:Je(Ma),children:ze?"Inspecting…":"Inspect URL"})]}),P&&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:P.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:P.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:eo(P.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Ht(P.crawlTime)})]})]})]})]}),e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:ye,onClick:()=>{Es(!0)},children:ye?"Loading…":"Refresh history"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:G,onChange:N=>de(N.target.value)}),e.jsx(T,{type:"button",size:"sm",variant:"outline",disabled:ye,onClick:()=>{Es(!0)},children:"Apply filter"})]}),f.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Coverage"}),e.jsx("th",{className:"text-left",children:"Mobile"}),e.jsx("th",{className:"text-left",children:"Inspected"})]})}),e.jsx("tbody",{children:f.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-neutral",children:N.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:N.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:eo(N.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Ht(N.inspectedAt)})]},N.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(ve,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),j.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:j.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:N.url}),e.jsx("td",{className:"text-secondary",children:N.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:N.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ht(N.transitionDate)})]},`${N.url}:${N.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Rt&&!r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>$s(N=>!N),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${hs?"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"})]})}),hs&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(ve,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Ge,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:g,disabled:Ae||m.length===0,onChange:N=>v(N.target.value),children:m.length===0?e.jsx("option",{value:"",children:Ae?"Loading properties…":"No properties available"}):m.map(N=>e.jsxs("option",{value:N.siteUrl,children:[N.siteUrl," · ",N.permissionLevel]},N.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(T,{type:"button",size:"sm",variant:"outline",disabled:Ae,onClick:()=>{An(Rt,!0)},children:Ae?"Refreshing…":"Refresh properties"}),e.jsx(T,{type:"button",size:"sm",disabled:!g||pe,onClick:Je(vr),children:pe?"Saving…":"Save property"})]})]})]}),e.jsxs(ve,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:M,onChange:N=>w(N.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:U,onChange:N=>F(N.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(T,{type:"button",size:"sm",disabled:Ra.isPending||!Rt.propertyId,onClick:Je(Ta),children:Ra.isPending?"Queueing…":"Queue sync"}),!Rt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Ex=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Dx({projectName:t,projectId:s}){const n=ms(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),m=qe(Ai({client:Y,path:{name:t}})),u=m.data?.find(X=>X.connectionType==="gbp"),p=!!u,x=a?{locationName:a}:void 0,h=qe({...Gd({client:Y,path:{name:t}}),enabled:p}),y=qe({..._d({client:Y,path:{name:t},query:x}),enabled:p}),f=qe({...Ud({client:Y,path:{name:t},query:x}),enabled:p}),b=qe({...Bd({client:Y,path:{name:t},query:x}),enabled:p}),j=qe({...Vd({client:Y,path:{name:t},query:x}),enabled:p}),A=qe({...Qd({client:Y,path:{name:t},query:x}),enabled:p}),P=qe({queryKey:["gbp-section-insights",t],queryFn:()=>zd(t),enabled:p});function C(){Tt(n,"gbp")}const g=Ot({...Hd(),onSuccess:X=>{Kl({id:X.runId,projectId:s,kind:_s["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Fe({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=o.useSyncExternalStore(Gl,ar,ar),S=Object.values(v.runs).some(X=>X.kind===_s["gbp-sync"]&&X.projectId===s),L=g.isPending||S,M=Ot({...Wd(),onSuccess:()=>C()});if(o.useEffect(()=>{if(!a||!h.data)return;const X=h.data.locations.filter(ue=>ue.selected);(X.length<=1||!X.some(ue=>ue.locationName===a))&&r(null)},[a,h.data]),o.useEffect(()=>{if(!l||!h.data)return;(a?[a]:h.data.locations.filter(ue=>ue.selected).map(ue=>ue.locationName)).includes(l)||i(null)},[l,h.data,a]),m.isLoading)return null;if(!u){const X=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(ve,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:X.map((ue,fe)=>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:fe+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ue.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-bg-elevated/80 px-2 py-1 font-mono text-xs text-neutral",children:ue.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ue.note})]})]},ue.title))})]})})}const w=y.data,U=h.data?.locations??[],F=U.filter(X=>X.selected),z=f.data?.keywords??[],_=b.data?.lodging??[],B=j.data?.placeActions??[],te=A.data?.places??[],O=U.length>0?U[0].accountName:u.domain,V=a?U.find(X=>X.locationName===a)?.displayName??null:null,Q=a?U.filter(X=>X.locationName===a):F,E=new Set(Q.map(X=>X.locationName)),J=_.filter(X=>E.has(X.locationName)),k=B.filter(X=>E.has(X.locationName)),H=te.filter(X=>E.has(X.locationName)),se=new Set(F.map(X=>X.locationName)),ne=a?z:z.filter(X=>se.has(X.locationName)),oe=!a&&F.length>1,ke=(P.data??[]).filter(X=>!X.dismissed&&Ex.has(X.type)&&(!V||X.query===V||X.query===a||X.title.startsWith(V)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Ge,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:L,onClick:()=>g.mutate({client:Y,path:{name:t},body:{}}),children:L?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[O?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:O})," · "]}):null,h.data?`${h.data.totalSelected} of ${h.data.totalDiscovered} locations tracked`:"Loading locations…"]}),F.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:X=>r(X.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),F.map(X=>e.jsx("option",{value:X.locationName,children:X.displayName},X.id))]})]}),F.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[ke.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),ke.map(X=>e.jsx("div",{className:["insight-card",Yx(X.severity),"rounded-r-lg border border-default bg-surface p-3 pl-4"].filter(Boolean).join(" "),children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-strong",children:[X.title,X.recommendation?.reason&&e.jsx(Ge,{text:X.recommendation.reason})]})},X.id))]}),w&&e.jsx(eg,{performance:w.performance,freshness:w.freshness,timeseries:w.timeseries}),w?.profileCompleteness&&e.jsx(Ox,{summary:w.profileCompleteness}),Q.length>0&&e.jsx(Fx,{locations:Q,lodging:J,places:H,placeActions:k,expandedLocation:l,onToggleExpanded:X=>{i(ue=>ue===X?null:X)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),f.data&&f.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[tt(f.data.thresholdedPct,Wn.percent)," privacy-thresholded"]})]}),ne.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No keyword impressions stored yet."}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Search term"}),oe&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:ne.slice(0,25).map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:X.keyword}),oe&&e.jsx("td",{className:"text-muted",children:U.find(ue=>ue.locationName===X.locationName)?.displayName??X.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:X.valueCount!==null?X.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",X.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[X.periodStart,"–",X.periodEnd]})]},`${X.locationName}:${X.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>d(X=>!X),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",U.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:U.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!ie()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:U.map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:X.displayName}),e.jsx("td",{className:"text-muted",children:X.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(je,{tone:X.selected?"positive":"neutral",children:X.selected?"Tracked":"Not tracked"})}),!ie()&&e.jsx("td",{className:"text-right",children:e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:M.isPending,onClick:()=>M.mutate({client:Y,path:{name:t,locationName:X.locationName},body:{selected:!X.selected}}),children:X.selected?"Untrack":"Track"})})]},X.id))})]})})]})]})})}function Ox({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:aa(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:aa(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:aa(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:aa(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:aa(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(Ge,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${Wx(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Fx({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:l}){const i=new Map(s.map(m=>[m.locationName,m])),c=new Map(n.map(m=>[m.locationName,m])),d=new Map;for(const m of a){const u=d.get(m.locationName)??[];u.push(m),d.set(m.locationName,u)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Ge,{text:ie()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(m=>{const u=i.get(m.locationName)??null,p=c.get(m.locationName)??null,x=d.get(m.locationName)??[],h=r===m.locationName;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:m.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:m.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(je,{tone:m.selected?"positive":"neutral",children:m.selected?"Tracked":"Not tracked"}),m.openStatus&&m.openStatus!=="OPEN"&&e.jsx(je,{tone:m.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Pc(m.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Gx,{location:m})}),e.jsx("td",{children:e.jsx(_x,{lodging:u})}),e.jsx("td",{children:e.jsx(Bx,{place:p,mapsUri:m.mapsUri})}),e.jsx("td",{children:e.jsx(Qx,{actions:x})}),e.jsx("td",{className:"text-right",children:e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:()=>l(m.locationName),children:h?"Hide":"Details"})})]}),h&&e.jsx("tr",{className:"bg-mono-950/35 hover:bg-mono-950/35",children:e.jsx("td",{colSpan:6,className:"px-4 py-4",children:e.jsx(Hx,{location:m,lodging:u,place:p,placeActions:x})})})]},m.id)})})]})})]})}function Kx(t){return[{label:"Description",tone:yn(t.description)?"positive":"neutral",value:yn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:yn(t.primaryPhone)?"positive":"neutral",value:yn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:yn(t.websiteUri)?"positive":"neutral",value:yn(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 Gx({location:t}){const s=Kx(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(je,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function _x({lodging:t}){return e.jsx(Li,{...Ux(t)})}function Ux(t){return t?t.populatedGroupCount===0?{tone:"neutral",label:"0 groups returned",detail:"Lodging API returned no readable groups; verify Hotel details."}:{tone:"positive",label:`${t.populatedGroupCount} group${t.populatedGroupCount===1?"":"s"} returned`,detail:"Owner lodging attributes."}:{tone:"neutral",label:"No Lodging API snapshot",detail:"Not returned for this scoped location."}}function Bx({place:t,mapsUri:s}){return e.jsx(Li,{...Vx(t,s)})}function Vx(t,s){if(!t)return{tone:"neutral",label:"Public listing not checked",detail:s?"Maps link available.":"No Places snapshot."};const n=t.amenities.length;return{tone:n>0?"positive":"neutral",label:n>0?`${n} signal${n===1?"":"s"} detected`:"0 supported signals detected",detail:`Places tier: ${t.tier}`}}function Qx({actions:t}){return e.jsx(Li,{...zx(t)})}function zx(t){if(t.length===0)return{tone:"neutral",label:"No CTAs stored",detail:"No placeActionLinks returned."};const s=t.filter(n=>n.providerType==="MERCHANT").length;return s===0?{tone:"neutral",label:`${t.length} aggregator CTA${t.length===1?"":"s"}`,detail:"No merchant-owned CTA returned."}:{tone:"positive",label:`${s} merchant CTA${s===1?"":"s"}`,detail:`${t.length} total returned.`}}function Li({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(je,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Hx({location:t,lodging:s,place:n,placeActions:a}){const r=s?Xx(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(qr,{title:"Owner profile · Business Information",children:[e.jsx(Vt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Vt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Vt,{label:"Description",value:yn(t.description)?t.description:"Not returned"}),e.jsx(Vt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Vt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Vt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Vt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Vt,{label:"Open status",value:Pc(t.openStatus)}),e.jsx(Vt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(qr,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Vt,{label:"Last checked",value:Ko(s.syncedAt)}),e.jsx(Vt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Vt,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(qr,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Vt,{label:"Places tier",value:n.tier}),e.jsx(Vt,{label:"Last checked",value:Ko(n.syncedAt)}),e.jsx(Vt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(l=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[cr(l.placeActionType),l.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[cr(l.providerType),l.uri?` · ${Jx(l.uri)}`:""]})]},l.placeActionLinkName))})})]})]})}function qr({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Vt({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function aa(t,s,n){return t===s?"positive":t===0?n:"caution"}function Wx(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Yx(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function yn(t){return typeof t=="string"&&t.trim().length>0}function Pc(t){return t?cr(t):"Not returned"}function cr(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Jx(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Ko(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Xx(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Zx(n)).map(([s])=>cr(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Zx(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function eg({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Yd.filter(y=>(a[y]??0)>0),l=Jd.filter(y=>(a[y]??0)>0),i=Object.keys(a).filter(y=>(a[y]??0)>0&&Xd(y)==="other").sort((y,f)=>(a[f]??0)-(a[y]??0)),c=Object.keys(a).filter(y=>(a[y]??0)===0).sort(),d=n.map(y=>{const f={date:y.date};for(const[b,j]of Object.entries(y.metrics))f[b]=j;return f}),m=n.find(y=>y.pending)?.date,u=n.length>0?n[n.length-1].date:void 0,p=d.length>0,x=s.dataThroughDate?`Data through ${Pt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,h=[...r,...i];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),x&&e.jsx("span",{className:"text-[11px] text-muted",children:x})]}),!p||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Go,{data:d,metrics:r,kind:"line",firstPending:m,lastDate:u}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:h.map(y=>e.jsxs("span",{className:"text-sm text-secondary",children:[rr(y)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[y]??0).toLocaleString()})]},y))})]})]}),p&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Go,{data:d,metrics:l,kind:"area",firstPending:m,lastDate:u})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(y=>rr(y)).join(", ")]})]})}function Go({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ba,{stroke:fa,vertical:!1}),e.jsx(sn,{dataKey:"date",tick:_t,tickLine:!1,axisLine:{stroke:ds},tickFormatter:wn,minTickGap:24}),e.jsx(nn,{tick:_t,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...es,labelFormatter:Pt,formatter:(l,i)=>[typeof l=="number"?l.toLocaleString():String(l??0),rr(String(i??""))]}),e.jsx(or,{wrapperStyle:{fontSize:11,color:us.text},formatter:l=>rr(l)}),a&&r&&e.jsx(ni,{x1:a,x2:r,fill:us.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:us.textDim,fontSize:10}}),s.map((l,i)=>n==="line"?e.jsx(Fs,{type:"monotone",dataKey:l,stroke:lt[i%lt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx(Js,{type:"monotone",dataKey:l,stackId:"reach",stroke:lt[i%lt.length],fill:lt[i%lt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},l))]})})})}function tg(t){return Fh(Ut(String(t)))}function sg(t){return wa(Ut(String(t)))}function Er({children:t,label:s="More info",placement:n="top",className:a}){const r=o.useId(),[l,i]=o.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":l?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:e.jsx(Wh,{className:"h-3.5 w-3.5","aria-hidden":!0})}),l&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Ka=Ds;function Mn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Dr(t){return t.toLocaleString()}function ng(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function ag(t){const s=t.filter(n=>n.kind===_s["backlink-extract"]&&!_l(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function rg(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const r=Math.floor(a/60),l=a%60;return l===0?`${r}m`:`${r}m ${l}s`}function ig({projectName:t}){const s=Ms(),[n,a]=o.useState(null),[r,l]=o.useState(null),[i,c]=o.useState([]),[d,m]=o.useState(null),[u,p]=o.useState(null),[x,h]=o.useState(null),[y,f]=o.useState(Date.now()),[b,j]=o.useState(0),[A,P]=o.useState(!0),[C,g]=o.useState(!1),[v,S]=o.useState(null),L=o.useCallback(async()=>{P(!0),S(null);try{const[V,Q,E,J,k]=await Promise.all([Zd().catch(()=>null),eu(t,{excludeCrawlers:!0}).catch(()=>null),tu(t,{limit:Ka,offset:b,excludeCrawlers:!0}).catch(se=>{if(se instanceof Bn&&se.code==="NOT_FOUND")return null;throw se}),su(t).catch(()=>[]),nu(t).catch(()=>[])]);m(V),a(Q),l(E),c(J);const H=ag(k);p(H)}catch(V){S(V instanceof Error?V.message:"Failed to load backlinks")}finally{P(!1)}},[t,b]);o.useEffect(()=>{L()},[L]),o.useEffect(()=>{if(!u)return;const V=u.id;let Q=!1;const E=async()=>{try{const k=await ti(V);if(Q)return;_l(k.status)?(p(null),h(k),await L()):p(H=>H?.id===k.id?{...H,...k}:H)}catch{}},J=window.setInterval(()=>{E()},3e3);return()=>{Q=!0,window.clearInterval(J)}},[u,L]),o.useEffect(()=>{if(!u)return;const V=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(V)},[u]),o.useEffect(()=>{if(!x||x.status==="failed")return;const V=window.setTimeout(()=>h(null),1e4);return()=>window.clearTimeout(V)},[x]);async function M(){g(!0),S(null);try{const V=await ru(t);p(V)}catch(V){V instanceof Bn&&V.code==="MISSING_DEPENDENCY"?S("DuckDB is not installed. Visit the Backlinks admin page to install it."):S(V instanceof Error?V.message:"Failed to trigger extract")}finally{g(!1)}}const w=o.useMemo(()=>i.slice().sort((V,Q)=>V.queriedAt.localeCompare(Q.queriedAt)).map(V=>({date:V.queriedAt,linkingDomains:V.totalLinkingDomains})),[i]),U=r?.rows??[],F=r?.total??0,z=n?.excludedLinkingDomains??0,_=Math.floor(b/Ka)+1;return o.useEffect(()=>{b>0&&b>=F&&j(0)},[b,F]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),v&&e.jsx(ve,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:v})}),u&&e.jsx(ve,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Vh,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(je,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[rg(u.startedAt??null,u.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",y]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),x&&!u&&e.jsx(ve,{className:`surface-card p-4 mb-4 ${x.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(Qh,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${x.status==="failed"?"text-negative":"text-positive"}`,children:x.status==="failed"?"Extract failed":"Extract complete"}),x.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:au(x.error)}):x.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),B()]});function B(){return A?e.jsx(ve,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):te()}function te(){const V=n!==null&&n.totalLinkingDomains>0,Q=x?.status==="failed",E=n!==null&&n.totalLinkingDomains===0&&!Q,J=d?.status==="ready",k=d?.status==="failed",H=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return V?O(e.jsxs(e.Fragment,{children:[!ie()&&!s&&e.jsxs(e.Fragment,{children:[e.jsxs(T,{type:"button",variant:"outline",size:"sm",disabled:C||u!==null,onClick:Je(M),children:[e.jsx(Hh,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":C?"Queuing…":"Re-run extract"]}),e.jsx(Er,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ie()&&!s&&e.jsx(T,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Mn("/backlinks"),children:"Open admin"})})]})):e.jsx(ve,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(zh,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!d&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!ie()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(T,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Mn("/backlinks"),children:"Set up backlinks"})})})]}),H&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",d.status,d.phaseDetail?` — ${d.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!ie()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(T,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Mn("/backlinks"),children:"View sync status"})})})]}),k&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:d.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!ie()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(T,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Mn("/backlinks"),children:"Go to Backlinks admin"})})})]}),J&&!H&&!E&&!Q&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:d.release})," is ready. Run an extract for this project."]}),!ie()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(T,{type:"button",size:"sm",disabled:C||u!==null,onClick:Je(M),children:[e.jsx(ir,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":C?"Queuing…":"Run extract"]}),e.jsx(Er,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),Q&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!ie()&&!s&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(T,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Mn("/backlinks"),children:"Go to Backlinks admin"})})})]}),E&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",n.targetDomain,". Try a newer release or re-run this extract."]}),!ie()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(T,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Mn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(T,{type:"button",variant:"outline",size:"sm",disabled:C||u!==null,onClick:Je(M),children:[e.jsx(ir,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":C?"Queuing…":"Re-run extract"]}),e.jsxs(Er,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:n.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function O(V){if(!n)return null;const Q="Linking hosts",E="linking hosts",J="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Dr(n.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",n.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",E]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Dr(n.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",E," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:tt(Number(n.top10HostsShare))})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",E," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",J," ",e.jsx("code",{className:"text-secondary",children:n.release})," · queried ",ng(n.queriedAt),z>0&&e.jsxs(e.Fragment,{children:[" · ",z," excluded domain",z===1?"":"s"]})]}),w.length>=2&&e.jsxs(ve,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:w,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:lt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:lt[0],stopOpacity:0})]})}),e.jsx(sn,{dataKey:"date",tick:_t,stroke:ds,tickFormatter:tg}),e.jsx(nn,{tick:_t,stroke:ds,allowDecimals:!1}),e.jsx(an,{contentStyle:es.contentStyle,labelStyle:es.labelStyle,itemStyle:es.itemStyle,labelFormatter:sg}),e.jsx(Js,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:lt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(ve,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:Q})]})}),e.jsxs("tbody",{children:[U.map(k=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:k.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Dr(k.numHosts)})]},k.linkingDomain)),U.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:z>0&&F===0?`Every referring domain in this ${J} was a crawler/proxy host (${z} hidden).`:`No referring domains in this ${J}.`})})]})]})}),e.jsx(Ks,{page:_,pageSize:Ka,visibleRows:U.length,totalRows:F,onPageChange:k=>j((k-1)*Ka)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:V})]})}}const og=["non-brand","branded","unclassified"],_o={"non-brand":"Non-brand",branded:"Branded",unclassified:"Unclassified"};function lg(t,s){return s<=0?"neutral":t/s*100>=70?"positive":"caution"}function cg(t,s){const n=[...new Set(t.byQuery.flatMap(i=>i.providers.map(c=>c.provider)))].sort(),a=new Map,r=i=>{const c=s(i)??"unclassified";let d=a.get(c);return d||(d={key:c,queries:0,unanswered:0,engines:n.map(m=>({provider:m,answered:0,mentioned:0,cited:0})),answers:0,competitorCited:0,competitorGaps:[],citedAndNamed:0,citedNotNamed:0,namedNotCited:0,neither:0},a.set(c,d)),d},l=new Map;for(const i of t.byQuery){const c=r(i.query);if(i.providers.length===0){c.unanswered++;continue}c.queries++;for(const u of i.providers){l.set(`${i.queryId}::${u.provider}`,i.query);const p=c.engines.find(x=>x.provider===u.provider);p.answered++,u.mentioned&&p.mentioned++,u.cited&&p.cited++,c.answers++}const d=i.providers.some(u=>u.cited),m=i.providers.some(u=>u.mentioned);d&&m?c.citedAndNamed++:d?c.citedNotNamed++:m?c.namedNotCited++:c.neither++}for(const i of t.competitorGaps){const c=l.get(`${i.queryId}::${i.provider}`);if(c===void 0)continue;const d=r(c);d.competitorCited++,d.competitorGaps.push({query:c,provider:i.provider,competitors:i.citingCompetitors})}return og.map(i=>a.get(i)).filter(i=>i!==void 0&&i.queries>0)}function dg(t){const s=new Map(t.byQuery.map(n=>[n.queryId,n]));return t.competitorGaps.flatMap(n=>{const a=s.get(n.queryId);return a?.providers.some(r=>r.provider===n.provider)?[]:[{query:n.query,provider:n.provider,competitors:n.citingCompetitors,reason:a?"engine":"query"}]})}const ug={engine:"engine no longer configured",query:"query no longer tracked"},Uo={"non-brand":"non-brand queries",branded:"branded queries",unclassified:"unclassified queries"},mg="Each engine's latest answer to each query, spot checks left out. Mentioned: the answer names you. Cited: its sources link to your site. Competitor cited instead of you: answers that cite a tracked competitor's site and not yours.";function Ln(t,s,n){return t===1?s:n}function hg({projectName:t,classify:s,hasCompetitors:n,providerScores:a=[]}){const r=o.useId(),[l,i]=o.useState("non-brand"),c=qe({...iu({client:Y,path:{name:t}}),staleTime:Ri}),d=c.data??null,m=d?.status==="ready"?cg(d,s):[],u=m.find(f=>f.key===l)??m.at(0);let p;c.isError?p=e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Could not load engine results: ",Nt(c.error)]}),e.jsx(T,{type:"button",size:"sm",variant:"outline",onClick:()=>{c.refetch()},children:"Retry"})]}):d?d.status==="no-data"?p=e.jsx("p",{className:"text-sm text-secondary",children:d.reason==="no-queries"?"Add queries to start tracking AI citations.":cs()?Vn:"Engine results appear after the first AI Visibility sweep."}):u||(p=e.jsx("p",{className:"text-sm text-secondary",children:"No engine answers yet."})):p=e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine results…"});const x=[];if(u&&d?.status==="ready"){const f=Ln(u.queries,"query","queries");x.push(e.jsxs(e.Fragment,{children:["Cited and named: ",e.jsxs("strong",{children:[u.citedAndNamed," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Cited but not named: ",e.jsxs("strong",{children:[u.citedNotNamed," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Named but not cited: ",e.jsxs("strong",{children:[u.namedNotCited," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Not cited or named: ",e.jsxs("strong",{children:[u.neither," of ",u.queries]})," ",f]}));for(const P of u.engines)P.answered<u.queries&&x.push(e.jsxs(e.Fragment,{children:[ot(P.provider),": answered ",e.jsxs("strong",{children:[P.answered," of ",u.queries]})," ",f]}));u.unanswered>0&&x.push(e.jsxs(e.Fragment,{children:["No answers yet: ",e.jsx("strong",{children:u.unanswered})," ",Ln(u.unanswered,"query","queries")]}));const{providersCiting:b,providersMentioning:j,providersConfigured:A}=d.summary;x.push(e.jsxs(e.Fragment,{children:["All queries: cited by ",e.jsxs("strong",{children:[b," of ",A]})," ",Ln(A,"engine","engines"),", named by ",e.jsxs("strong",{children:[j," of ",A]})]}));for(const P of a)x.push(e.jsxs(e.Fragment,{children:[ot(P.provider),P.model?` (${P.model})`:""," citation rate:"," ",e.jsx("strong",{children:tt(P.score,Wn.percent)}),", ",e.jsxs("strong",{children:[P.cited," of ",P.total]})," ",Ln(P.total,"answer","answers"),", all queries"]}));for(const P of u.competitorGaps)x.push(`"${P.query}" (${ot(P.provider)}): ${P.competitors.join(", ")} cited instead of you`);for(const P of dg(d))x.push(`"${P.query}" (${ot(P.provider)}): ${P.competitors.join(", ")} cited instead of you, not counted (${ug[P.reason]})`)}const h=d?.status==="ready"?d.summary.latestRunAt:null,y=(f,b)=>u?.key==="non-brand"?xa[lg(f,b)]:"text-primary";return e.jsxs("section",{className:"overview-brief","aria-labelledby":r,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:r,className:"av-card-title",children:"By engine"}),u&&e.jsx(Ge,{text:mg})]}),h||u?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[h?e.jsxs("p",{className:"av-card-meta",children:["Latest run ",hr(h)]}):null,m.length>1?e.jsx(ha,{label:"Query type",className:"flex-wrap",options:m.map(f=>({value:f.key,label:_o[f.key]})),value:u.key,onChange:i}):u?e.jsx("span",{className:"mention-share-class",children:_o[u.key]}):null]}):null]}),e.jsx("div",{className:"av-card-body",children:p??(u&&e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":`By engine, ${Uo[u.key]}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsxs("th",{scope:"col",children:["Of ",u.queries," ",Ln(u.queries,"query","queries")]}),u.engines.map(f=>e.jsx("th",{scope:"col",children:ot(f.provider)},f.provider))]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Mentioned"}),u.engines.map(f=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(f.mentioned,f.answered)}`,children:f.mentioned})},f.provider))]}),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Cited"}),u.engines.map(f=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(f.cited,f.answered)}`,children:f.cited})},f.provider))]})]})]}),e.jsxs("p",{className:"av-card-line",children:[e.jsx("span",{className:"av-card-line-label",children:"Competitor cited instead of you"}),n?e.jsxs("span",{children:[e.jsx("span",{className:"av-n-sm text-primary",children:u.competitorCited})," ",e.jsxs("span",{className:"av-of",children:["of ",u.answers," ",Ln(u.answers,"answer","answers")]}),e.jsxs("span",{className:"sr-only",children:[" · ",Uo[u.key]]})]}):e.jsx("span",{className:"text-[13px] text-secondary",children:"No competitors tracked"})]})]}))}),e.jsx(Sa,{items:x})]})}const pg={[Is.queued]:{word:"queued",tone:"text-secondary"},[Is.running]:{word:"running",tone:"text-info-300"},[Is.completed]:{word:"completed",tone:"text-secondary"},[Is.partial]:{word:"partial",tone:"text-caution-400"},[Is.failed]:{word:"failed",tone:"text-negative-400"},[Is.cancelled]:{word:"cancelled",tone:"text-secondary"}};function xg({runs:t,collapsed:s=!1}){const n=o.useId(),{openRun:a}=Ci(),r=new Set(t.map(c=>c.location??"")).size>1,l=t.some(c=>c.kind!==_s["answer-visibility"]),i=t.map(c=>`${c.startedAt}: ${c.summary}.${c.statusDetail?` ${c.statusDetail}`:""}`);return e.jsx("section",{className:"overview-brief","aria-labelledby":n,children:e.jsxs("details",{className:"av-history",open:!s||void 0,children:[e.jsxs("summary",{className:"av-card-head",children:[e.jsx("h2",{id:n,className:"av-card-title",children:"Past sweeps"}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t.length>0?e.jsxs("span",{className:"av-card-meta",children:[t.length," recent"]}):null,e.jsx(Qn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"av-card-body",children:t.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No sweeps yet."}):e.jsxs("table",{className:"av-grid av-grid-dense av-grid-sweeps","aria-labelledby":n,children:[e.jsx("thead",{className:"sr-only",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Started"}),l?e.jsx("th",{scope:"col",children:"Type"}):null,e.jsx("th",{scope:"col",children:"Trigger"}),r?e.jsx("th",{scope:"col",children:"Location"}):null,e.jsx("th",{scope:"col",children:"Duration"}),e.jsx("th",{scope:"col",children:"Status"})]})}),e.jsx("tbody",{children:t.map(c=>{const d=pg[c.status],m=c.status===Is.partial||c.status===Is.failed;return e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label tabular-nums",children:e.jsx("button",{type:"button",className:"av-link",onClick:()=>a(c.id),"aria-label":`View the ${c.startedAt} sweep`,children:c.startedAt})}),l?e.jsx("td",{className:"text-[13px] text-secondary",children:c.kindLabel}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.triggerLabel}),r?e.jsx("td",{className:"text-[13px] text-secondary",children:c.location??"No location"}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.duration}),e.jsxs("td",{children:[e.jsx("span",{className:`av-status ${d.tone}`,children:d.word}),m&&c.statusDetail?e.jsx("span",{className:"ml-2 text-[13px] text-secondary",children:c.statusDetail}):null]})]},c.id)})})]})}),e.jsx(Sa,{items:i})]})})}const gg=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],Bo="Measured answers",fg="Close answers",Rs={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},yg={"non-brand":"non-brand queries",branded:"branded queries",unknown:"unclassified queries"},ls={up:t=>`Up ${t} pts`,down:t=>`Down ${t} pts`,none:"No change",previousUnavailable:"No earlier value",comparedWith:t=>`vs ${t} sweep`,noPreviousRun:"No earlier sweep to compare",definitionChanged:t=>t===null?"Not compared: setup changed":`Not compared: setup changed since ${t}`,modelChanged:t=>t===null?"Not compared: engines or models changed":`Not compared: engines or models changed since ${t}`,legacyUnknown:"Not compared: older sweep lacks comparison details",partialRun:"Not compared: a sweep was incomplete",scopedRun:"Not compared: this sweep covered part of the project",explanation:"Change compares this sweep with the sweep before it when both completed and used the same setup, engines and models."},ra={simpleMention:"Mentioned counts answers naming your brand in the answer text, not in the source links.",simpleCitation:"Cited counts answers linking to your site in the sources behind the answer, not in the answer text.",advancedMention:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned. An answer that could not be tied to one property is left out of the rate, never counted as not mentioned.",advancedCitation:"An answer counts when it cites a matching URL for any assigned property. This does not mean every property was cited. An answer whose sources could not be checked is left out of the rate, as neither cited nor not cited, and counted on its own line.",propertyReach:"Selected properties named in at least one measured answer, out of the selected properties that have a name to match on. It counts properties, not answers, and shows no rate while any of those properties is unmeasured."},bg="Counts properties, not answers. The buckets do not overlap and add up to the total. Cited only means the engine used the property's page as a source without naming it in the answer. Not measured covers a property with no eligible completed measurement, and one where only one of the two signals was measured: calling that mentioned but not cited would assert an absence nothing measured. Neither signal means both were measured and neither was found. One verified mention or citation stands, and a later uncertain answer cannot erase it.",dr="min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400";function vg(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function Ic(t){return t.reason==="identity-ambiguous"?zl.ambiguous:t.reason==="not-applicable"?"Not applicable":"Not measured"}function Sn({value:t,signal:s}){if(t.rate===null)return e.jsx("span",{className:"text-sm text-secondary",children:Ic(t)});const n=Pi(t,s);return e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:tt(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator]}),n?e.jsx("span",{className:"text-sm tabular-nums text-secondary",children:n}):null]})}function Vo({value:t}){return t.rate===null?null:e.jsx("span",{className:"report-rate-bar","aria-hidden":"true",children:e.jsx("span",{className:"report-rate-bar-fill progress-fill-neutral",style:{width:`${t.rate*100}%`}})})}function Or(t,s){if(!t||t.state==="unavailable")return null;const n=t[s];if(n.state==="unavailable")switch(n.reason){case wr["previous-unavailable"]:return{text:ls.previousUnavailable,tone:"text-secondary"};case wr["current-unavailable"]:case wr["not-applicable"]:return null}const{direction:a,magnitude:r}=Bl(n.delta);switch(a){case"up":return{text:ls.up(r),tone:"text-positive"};case"down":return{text:ls.down(r),tone:"text-negative"};case"none":return{text:ls.none,tone:"text-secondary"}}}function Qo(t,s){const n=Ut(t);return s!==null&&ho(n)===ho(Ut(s))?_h(n):wa(n)}function jg(t,s){return(t.run.id===null?void 0:s.trend.find(a=>a.runId===t.run.id))?.createdAt??t.measurement.completedAt??s.trend.at(-1)?.createdAt??null}function Ng(t,s){if(!t)return null;if(t.state==="unavailable"){const n=t.previousRun?Qo(t.previousRun.createdAt,s):null;switch(t.reason){case mn["no-selected-run"]:return null;case mn["no-previous-run"]:return ls.noPreviousRun;case mn["definition-changed"]:return ls.definitionChanged(n);case mn["model-changed"]:return ls.modelChanged(n);case mn["legacy-unknown"]:return ls.legacyUnknown;case mn["partial-run"]:return ls.partialRun;case mn["scoped-run"]:return ls.scopedRun}}return ls.comparedWith(Qo(t.previousRun.createdAt,s))}function wg(t,s){const n=`${t.queryCount} ${t.queryCount===1?"query":"queries"} · ${t.answerCount} ${t.answerCount===1?"answer":"answers"}`;return s===null?n:`${n} · ${s}`}function Fr({label:t,help:s,value:n,signal:a,unit:r,classNoun:l,change:i}){const c=e.jsx("span",{className:"sr-only",children:` · ${l}`}),d=Pi(n,a);return e.jsxs("div",{className:"report-headline-tile",children:[e.jsxs("dt",{className:"flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:t}),e.jsx(Ge,{text:s})]}),n.rate===null?e.jsxs("dd",{className:"text-lg text-secondary",children:[Ic(n),c]}):e.jsxs(e.Fragment,{children:[e.jsxs("dd",{className:"report-headline-value",children:[e.jsx("span",{className:"text-3xl font-semibold tabular-nums text-heading",children:tt(n.rate)}),c,i?e.jsx("span",{className:`text-sm ${i.tone}`,children:i.text}):null]}),e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:`${n.numerator} of ${n.denominator} ${r}`}),d?e.jsx("dd",{className:"text-sm tabular-nums text-secondary",children:d}):null]})]})}const Sg={otherQueries:"Other queries"},Ga={retiredScope:"This saved scope is unavailable for this measurement. Show the whole site to choose another.",retiredMarket:"This saved market is unavailable for this measurement. Show all markets to choose another.",showWholeSite:"Show whole site",showAllMarkets:"Show all markets"};function Cg(t,s){const n=new Map;for(const r of t){const l=n.get(r.queryKey);l?l.rows.push(r):n.set(r.queryKey,{queryKey:r.queryKey,query:r.query,rows:[r]})}const a=[...n.values()];if(!s||!t.some(r=>r.marketKeys?.length))return a;for(const r of a){const l=[...new Set(r.rows.flatMap(i=>i.marketKeys??[]))].sort();r.marketLabel=l.map(i=>s.get(i)??i).join(" · ")||Sg.otherQueries}return a.sort((r,l)=>r.marketLabel.localeCompare(l.marketLabel)||r.query.localeCompare(l.query))}function zo({value:t,signal:s,singleAnswer:n}){if(n&&t.denominator===1&&t.unattributed===void 0&&t.unchecked===void 0&&(t.rate===0||t.rate===1)){const a=t.rate===1;return e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm ${a?"text-positive":"text-secondary"}`,children:[a?e.jsx(Jh,{size:16,"aria-hidden":"true"}):e.jsx(Xh,{size:16,"aria-hidden":"true"}),a?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Sn,{value:t,signal:s}),t.reason==="evidence-incomplete"?e.jsx(Ge,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function Ho({targetKeys:t,labels:s}){return t.length===0?e.jsx("span",{children:"No assigned properties"}):t.length===1?e.jsx("span",{children:s.get(t[0])??t[0]}):e.jsxs("details",{children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[t.length," properties"]}),e.jsx("ul",{className:"max-h-48 space-y-2 overflow-y-auto pb-3",children:t.map(n=>e.jsx("li",{children:s.get(n)??n},n))})]})}function kg({group:t,queryClass:s,advanced:n,targetLabels:a,marketHeading:r,onViewAnswers:l}){const i=t.rows[0],c=p=>JSON.stringify([...p.targetKeys].sort()),d=t.rows.every(p=>c(p)===c(i)),m=t.rows.every(p=>p.location===i.location),u=p=>p===null?"No location requested":`Requested search location: ${p}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[r?e.jsx("tr",{children:e.jsx("th",{colSpan:4,className:"border-t border-default py-4 text-left",children:e.jsx("h3",{className:"text-base font-semibold text-heading",children:r})})}):null,e.jsx("tr",{className:"measurement-result-heading",children:e.jsxs("th",{scope:"rowgroup",colSpan:4,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"break-words text-base font-medium text-heading",children:t.query}),e.jsx("div",{className:"text-sm font-normal",children:e.jsx($l,{showLabel:!0,queryId:i.queryId,sourceSnapshotIds:t.rows.flatMap(p=>p.sourceSnapshotIds??[]),queryClass:s==="unknown"?null:s,location:m?i.location:void 0})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 text-sm font-normal text-secondary",children:[n&&d?e.jsx(Ho,{targetKeys:i.targetKeys,labels:a}):null,m?e.jsx("span",{children:u(i.location)}):null]})]})}),t.rows.map(p=>e.jsxs("tr",{className:"measurement-engine-result",children:[e.jsxs("td",{className:"measurement-result-engine",children:[e.jsx("span",{className:"font-medium text-heading",children:ot(p.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:p.model??"Model not recorded"}),n&&!d?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(Ho,{targetKeys:p.targetKeys,labels:a})}):null,m?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:u(p.location)}),e.jsx(ql,{showLabel:!0,showSubjects:n,queryId:p.queryId,sourceSnapshotIds:p.sourceSnapshotIds??[],queryClass:s==="unknown"?null:s,provider:p.provider,model:p.model,location:p.location})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(zo,{value:p.mentionCoverage,signal:"mentioned",singleAnswer:p.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(zo,{value:p.citationCoverage,signal:"cited",singleAnswer:p.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(T,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${p.query} · ${p.provider}`,onClick:x=>l(p,x.currentTarget),children:[p.answerCount===1?"View answer":"View answers",e.jsx(oc,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([p.provider,p.model,p.location])))]})}const Ag="Cited counts only answers whose sources could be checked.",Wo=[{key:"mentioned",label:"Mentioned",color:lt[1],dashed:!1},{key:"cited",label:"Cited",color:Yn.positive,dashed:!0}],Yo="var(--chart-tooltip-bg)";function Rg({population:t}){const s=o.useId(),[n,a]=o.useState({mentioned:!0,cited:!0}),r=Wo.filter(x=>n[x.key]).map(x=>x.key),l=x=>a(h=>{const y={...h,[x]:!h[x]};return y.mentioned||y.cited?y:h});let i=0;const c=t.trend.map((x,h)=>(h>0&&x.continuity.state!=="comparable"&&(i+=1),{createdAt:Date.parse(x.createdAt),[`mentioned-${i}`]:x.mentionCoverage.rate,[`cited-${i}`]:x.citationCoverage.rate})),d=Array.from({length:i+1},(x,h)=>h),m=new Set(t.trend.slice(1).map(x=>x.continuity.state)),u=[...c.length===1?["First measurement. A trend appears after another comparable run."]:[],...m.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...m.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...m.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(x=>x.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[],...t.trend.some(x=>x.citationCoverage.unchecked!==void 0)?[Ag]:[]];if(c.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const p=t.trend.some(x=>x.mentionCoverage.rate!==null||x.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[p?e.jsxs(e.Fragment,{children:[e.jsxs("fieldset",{className:"flex flex-wrap gap-x-5 py-1 text-sm text-secondary",children:[e.jsx("legend",{className:"sr-only",children:"Trend legend"}),Wo.map(x=>e.jsxs("label",{className:"flex min-h-11 items-center gap-2",children:[e.jsx("input",{type:"checkbox",className:"size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",checked:n[x.key],disabled:n[x.key]&&r.length===1,onChange:()=>l(x.key)}),e.jsxs("svg",{"aria-hidden":"true",className:"shrink-0",width:"24",height:"10",viewBox:"0 0 24 10",children:[e.jsx("line",{x1:"0",y1:"5",x2:"24",y2:"5",stroke:x.color,strokeWidth:"2",strokeDasharray:x.dashed?"6 4":void 0}),e.jsx("circle",{cx:"12",cy:"5",r:"3",fill:x.dashed?Yo:x.color,stroke:x.color,strokeWidth:"2"})]}),x.label]},x.key))]}),u.length>0&&e.jsx("p",{id:s,className:"pb-3 text-sm text-secondary",children:u.join(" ")}),e.jsx("div",{className:"visibility-trend-chart",role:"img","data-visible-series":r.join(" "),"aria-describedby":u.length>0?s:void 0,"aria-label":`${Rs[t.queryClass]} mention and citation trend`,children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:c,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ba,{stroke:fa,vertical:!1}),e.jsx(sn,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:_t,tickLine:!1,axisLine:{stroke:ds},tickFormatter:x=>new Date(Number(x)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(nn,{domain:[0,1],tick:_t,tickLine:!1,axisLine:!1,width:48,tickFormatter:x=>tt(Number(x))}),e.jsx(an,{...es,formatter:x=>typeof x=="number"?tt(x):"Not measured",labelFormatter:x=>new Date(Number(x)).toLocaleDateString()}),d.map(x=>e.jsxs(o.Fragment,{children:[n.mentioned?e.jsx(Fs,{type:"linear",dataKey:`mentioned-${x}`,name:"Mentioned",stroke:lt[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:lt[1]}}):null,n.cited?e.jsx(Fs,{type:"linear",dataKey:`cited-${x}`,name:"Cited",stroke:Yn.positive,strokeWidth:2,strokeDasharray:"6 4",connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:Yo,strokeDasharray:"none"}}):null]},x))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:p?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${Rs[t.queryClass]} trend data`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"}),e.jsx("th",{children:"Comparison"})]})}),e.jsx("tbody",{children:t.trend.map(x=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(x.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(Sn,{value:x.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(Sn,{value:x.citationCoverage,signal:"cited"})}),e.jsx("td",{children:x.continuity.state.replaceAll("-"," ")})]},x.runId))})]})})]})}function xi(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function $i(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,l=t.populations.find(m=>m.queryClass===r);if(l)return l;const i=xi(a,s)??xi(t,s),c=t.populations.find(m=>m.queryClass===i?.queryClass);if(c)return c;const d=["non-brand","branded","unknown"].map(m=>t.populations.find(u=>u.queryClass===m));return d.find(m=>m&&(m.summary.queryCount>0||m.trend.some(u=>u.queryCount>0)))??d.find(m=>m!==void 0)??t.populations[0]}const kt={queryType:"Query type",filters:t=>t===0?"Filters":`Filters · ${t}`,panel:"Visibility filters",clearFilters:"Clear filters",manageQueries:"Manage queries",removeFilter:t=>`Remove filter ${t}`,engine:t=>`Engine: ${t}`,model:t=>`Model: ${t}`,location:t=>`Requested search location: ${t}`,noLocation:"No location requested",dateRange:(t,s)=>`${t} to ${s} (UTC)`,dateFrom:t=>`From ${t} (UTC)`,dateThrough:t=>`Through ${t} (UTC)`,resultsFrom:t=>`Results from: ${t}`,resultsFromSelectedSweep:"Results from: selected sweep"},Pg={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},Ig="min-h-11 rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400";function Tg(t,s){return t&&s?kt.dateRange(t.slice(0,4)===s.slice(0,4)?Gh(t):Pt(t),Pt(s)):t?kt.dateFrom(Pt(t)):s?kt.dateThrough(Pt(s)):null}function Mg(t,s){const n=[];t.provider&&n.push({key:"engine",label:kt.engine(t.provider),patch:{measurementProvider:void 0}}),t.model&&n.push({key:"model",label:kt.model(t.model),patch:{measurementModel:void 0}}),t.location&&n.push({key:"location",label:t.location==="none"?kt.noLocation:kt.location(t.location),patch:{measurementLocation:void 0}});const a=Tg(t.from,t.to);if(a&&n.push({key:"dates",label:a,patch:{measurementFrom:void 0,measurementTo:void 0}}),t.measurementRunId){const r=s.populations.flatMap(l=>l.trend).find(l=>l.runId===t.measurementRunId);n.push({key:"run",label:r?kt.resultsFrom(wa(Ut(r.createdAt))):kt.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function _a(t,s,n){return s===""||t.some(a=>a.value===s)?t:[...t,{value:s,label:n}]}function Lg({report:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}){const[l,i]=o.useState(!1),c=o.useRef(null),d=o.useId(),m=`${d}-filters`,{filterOptions:u,selection:p}=t,x=p.measurement,h=$i(t,s.queryKey,s.answer),y=s.queryClass==="all"?h.queryClass:s.queryClass,f=Mg(s,t),b=s.measurementScope==="property"?s.measurementScopeKey:void 0,j=b?r?.({id:b,label:ai(t.scopeOptions,s)?.label??b}):null,A=s.provider??"",P=s.model??"",C=s.location??"",g=s.measurementRunId??"",v=()=>c.current?.focus(),S=(M,w,U,F,z)=>e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1",children:[e.jsx("label",{htmlFor:`${d}-${w}`,className:"text-sm font-medium text-heading",children:M}),z?e.jsx(Ge,{text:z}):null]}),e.jsx("select",{id:`${d}-${w}`,className:dr,value:U,onChange:_=>n({[w]:_.target.value||void 0,measurementQueryKey:void 0}),children:F.map(_=>e.jsx("option",{value:_.value,children:_.label},_.value))})]}),L=(M,w,U,F)=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("label",{htmlFor:`${d}-${w}`,className:"mb-1 block text-sm font-medium text-heading",children:M}),e.jsx("input",{id:`${d}-${w}`,type:"date",className:dr,value:U?.slice(0,10)??"",onChange:z=>n({[w]:z.target.value?`${z.target.value}${F}`:void 0})})]});return e.jsxs("div",{className:"visibility-filter-container",children:[e.jsxs("div",{className:"visibility-results-toolbar",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:kt.queryType}),e.jsxs("select",{"aria-label":kt.queryType,className:Ig,value:y,onChange:M=>n({queryClass:M.target.value,measurementQueryKey:void 0}),children:[e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"unknown",children:"Unclassified"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{tone:x.state==="measured"?"positive":"neutral",children:x.state==="measured"?"Complete":x.state==="partial"?"Partial":"Not measured"}),x.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:wa(Ut(x.completedAt))}):null]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[e.jsx(T,{ref:c,type:"button",variant:"outline",className:"min-h-11","aria-expanded":l,"aria-controls":m,onClick:()=>i(M=>!M),children:kt.filters(f.length)}),f.map(M=>e.jsxs(T,{type:"button",variant:"outline",className:"visibility-filter-token min-h-11 rounded-md text-sm","aria-label":kt.removeFilter(M.label),onClick:()=>{n(M.patch),v()},children:[e.jsx("span",{className:"min-w-0 truncate",children:M.label}),e.jsx(Yh,{size:16,className:"shrink-0","aria-hidden":"true"})]},M.key)),j,a?e.jsx(T,{type:"button",variant:"outline",className:"min-h-11",onClick:a,children:kt.manageQueries}):null]})]}),e.jsxs("div",{id:m,role:"group","aria-label":kt.panel,hidden:!l,className:"border-b border-default",onKeyDown:M=>{M.key==="Escape"&&(M.target instanceof HTMLElement&&M.target.getAttribute("aria-expanded")==="true"||(i(!1),v()))},children:[e.jsxs("div",{className:"visibility-report-filters",children:[S("Answer engine","measurementProvider",A,_a([{value:"",label:"All engines"},...u.providers.map(M=>({value:M,label:M}))],A,A)),S("Requested search location","measurementLocation",C,_a([{value:"",label:"All requested locations"},...u.locations.flatMap(M=>M.kind==="exact"?[{value:M.value,label:M.value}]:M.kind==="none"?[{value:"none",label:kt.noLocation}]:[])],C,C==="none"?kt.noLocation:C)),S("AI model","measurementModel",P,_a([{value:"",label:"All models"},...Array.from(new Set(u.models.filter(M=>!s.provider||M.provider===s.provider).map(M=>M.model))).map(M=>({value:M,label:M}))],P,P),"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),L("Start date (UTC)","measurementFrom",s.from,"T00:00:00.000Z"),L("End date (UTC)","measurementTo",s.to,"T23:59:59.999Z"),S("Results from","measurementRunId",g,_a([{value:"",label:"Latest saved sweep"},...[...h.trend].reverse().map(M=>({value:M.runId,label:new Date(M.createdAt).toLocaleString()}))],g,"Selected sweep"),"Choose a saved AI sweep to view its results. No new sweep starts.")]}),e.jsx("div",{className:"flex justify-end pb-3",children:e.jsx(T,{type:"button",variant:"ghost",className:"min-h-11",disabled:f.length===0,onClick:()=>{n({...Pg}),v()},children:kt.clearFilters})})]})]})}function $g({report:t,isRefreshing:s=!1,onSelectionChange:n,onPage:a,onSearch:r,search:l="",queryKey:i,answerSelection:c,evidenceReport:d,isEvidenceLoading:m=!1,evidenceError:u,onRetryEvidence:p,onEvidencePage:x}){const h=o.useRef(null),y=o.useRef(void 0),f=o.useRef(null),b=$i(t,i,c,d),j=d??t,A=j.populations.filter(w=>[...w.queries.items,...w.evidence.items].some(U=>U.queryKey===i)),P=c?[c.queryClass]:(A.length?A:m?[]:[b]).map(w=>w.queryClass),C=i?JSON.stringify([c??i,P]):void 0;o.useEffect(()=>{if(!C){s||(y.current=void 0);return}if(y.current===C)return;const w=h.current?.querySelectorAll(`[aria-label="${Bo}"]`);if(w?.length){for(const U of w){const F=U.closest("details[data-query-results]");F&&(F.open=!0)}w[0].focus({preventScroll:!0}),w[0].scrollIntoView?.({block:"start"}),y.current=C}},[C,s]);const{selection:g}=t,v=vg(g.scope),S=new Map(t.scopeOptions.filter(w=>w.kind==="property").map(w=>[w.id,w.label])),L=w=>{const U=j.populations.find(F=>F.queryClass===w.queryClass)?.evidence;return{items:U?.items.filter(F=>F.queryKey===i&&(!c||F.provider===c.provider&&F.model===c.model&&F.location===c.location&&(c.runId===null||F.runId===c.runId)))??[],nextCursor:U?.nextCursor}},M=()=>{y.current=void 0;const w=f.current;w!==null&&w.row.queryKey===i&&(!c||w.row.provider===c.provider&&w.row.model===c.model&&w.row.location===c.location)&&w?.element.isConnected?w.element.focus():h.current?.querySelector(`details[data-query-results="${b.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})};return e.jsxs("section",{ref:h,className:"visibility-report","aria-label":"AI visibility results",children:[g.provenance.kind==="legacy-simple"&&g.queryClass!=="unknown"&&g.queryClass!=="all"?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default py-3 text-sm text-secondary",children:[e.jsx("p",{children:"These saved results aren't separated by query type."}),e.jsx(T,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,[b].map(w=>{const U=Cg(w.queries.items,g.scope.kind==="property"&&!g.market&&w.queryClass==="non-brand"?new Map(t.scopeOptions.filter(O=>O.kind==="market").map(O=>[O.id,O.label])):void 0),F=L(w),z=F.items[0]?.query??w.queries.items.find(O=>O.queryKey===i)?.query,_=g.mode==="advanced"&&g.scope.kind!=="property",B=yg[w.queryClass],te=Ng(w.comparison,jg(g,w));return e.jsxs("section",{"aria-label":Rs[w.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head flex-wrap items-center",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("h2",{children:Rs[w.queryClass]}),e.jsx(Ge,{text:w.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":w.queryClass==="branded"?"Queries that name the measured identity.":"These queries were not labeled as branded or non-brand when measured. Their saved results remain available here, separate from branded and non-brand rates."})]}),e.jsxs("div",{className:"report-headline-caption",children:[e.jsx("span",{className:"tabular-nums",children:wg(w.summary,te)}),e.jsx(Ge,{text:ls.explanation})]})]}),e.jsxs("dl",{className:"report-headline mt-3","data-columns":_?3:2,"aria-label":`${Rs[w.queryClass]} headline results`,children:[e.jsx(Fr,{label:_?"Answers mentioning a property":"Mentioned answers",help:g.mode==="advanced"?ra.advancedMention:ra.simpleMention,value:w.summary.mentionCoverage,signal:"mentioned",unit:"answers",classNoun:B,change:Or(w.comparison,"mentionCoverage")}),e.jsx(Fr,{label:_?"Answers citing a property":"Cited answers",help:g.mode==="advanced"?ra.advancedCitation:ra.simpleCitation,value:w.summary.citationCoverage,signal:"cited",unit:"answers",classNoun:B,change:Or(w.comparison,"citationCoverage")}),_?e.jsx(Fr,{label:"Properties mentioned",help:ra.propertyReach,value:w.summary.propertyReach,signal:"mentioned",unit:"properties",classNoun:B,change:Or(w.comparison,"propertyReach")}):null]}),e.jsx(Ll,{queryClass:g.queryClass,manage:!0}),e.jsx(Rg,{population:w}),_&&(w.breakdown.groups.length>0||w.breakdown.properties.length>0)?e.jsx(qg,{population:w,scope:g.scope,scopeOptions:t.scopeOptions,marketKey:g.market?.id,onSelectionChange:n},`${g.scope.kind}:${g.scope.id}`):null,g.mode==="advanced"?e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Rs[w.queryClass]} property outcomes`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Property outcomes"}),e.jsxs("span",{className:"visibility-disclosure-meta",children:[w.summary.outcomes.total," ",w.summary.outcomes.total===1?"property":"properties"]})]}),e.jsxs("div",{className:"visibility-disclosure-panel flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-x-8 gap-y-3",children:[["bothSignals","mentioned and cited"],["mentionedOnly","mentioned only"],["citedOnly","cited only"],["neither","neither signal"],["notMeasured","not measured"]].map(([O,V])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:w.summary.outcomes[O]}),e.jsx("span",{className:"text-sm text-secondary",children:V})]},O))}),e.jsx(Ge,{text:bg})]})]}):null,e.jsxs("details",{className:"visibility-disclosure","data-query-results":w.queryClass,"aria-label":`${Rs[w.queryClass]} query results`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Query results"}),e.jsxs("span",{className:"visibility-disclosure-meta",children:[w.queries.total," ",w.queries.total===1?"result":"results"," · ",v]})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-3",children:[r?e.jsx("input",{type:"search","aria-label":`Search ${Rs[w.queryClass]}`,placeholder:"Search queries",className:`${dr} max-w-sm`,value:l,onChange:O=>r(O.target.value)}):null,e.jsx(Ge,{text:g.mode==="advanced"?"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, property scope, and answer counts. Mentioned and Cited count answers matching any assigned property, not the percentage of properties found.":"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, and answer counts. Mentioned counts answers naming your brand. Cited counts answers linking to your site."})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table measurement-results-table","aria-label":`${Rs[w.queryClass]} engine results`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Answer engine"}),e.jsx("th",{scope:"col",children:"Mentioned"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),U.map((O,V)=>e.jsx(kg,{group:O,queryClass:w.queryClass,marketHeading:O.marketLabel!==U[V-1]?.marketLabel?O.marketLabel:void 0,advanced:g.mode==="advanced",targetLabels:S,onViewAnswers:(Q,E)=>{f.current={row:Q,element:E},n({measurementQueryKey:Q.queryKey,measurementAnswer:JSON.stringify({queryKey:Q.queryKey,queryClass:w.queryClass,provider:Q.provider,model:Q.model,location:Q.location,runId:g.run.id,revision:g.revision})})}},O.queryKey))]})}),w.queries.items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:"No measured queries match this selection."}):e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:[U.length," ",U.length===1?"query":"queries"," · ",w.queries.items.length," ",w.queries.items.length===1?"engine result":"engine results"," shown of ",w.queries.total," results"]}),w.queries.nextCursor&&a?e.jsx(T,{variant:"outline",onClick:()=>a(w.queries.nextCursor),children:"Next queries"}):null,i&&P.includes(w.queryClass)?e.jsxs("section",{tabIndex:-1,className:"scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-label":Bo,"aria-busy":m,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("h3",{className:"min-w-0 flex-1 text-base font-semibold text-heading [overflow-wrap:anywhere]",children:z??"Answers"}),e.jsx(T,{variant:"ghost",className:"min-h-11",onClick:M,children:fg})]}),m?e.jsx("p",{role:"status",className:"py-4 text-sm text-secondary",children:"Loading saved answers…"}):u?e.jsxs("div",{role:"alert",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["Saved answers unavailable: ",u]}),p?e.jsx(T,{variant:"outline",onClick:p,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[F.items.map(O=>e.jsxs("article",{className:"border-b border-default py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsx("strong",{className:"text-sm text-heading",children:O.provider}),O.model?e.jsx("span",{className:"text-[13px] text-secondary",children:O.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:O.location===null?kt.noLocation:kt.location(O.location)}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(O.createdAt).toLocaleDateString()}),e.jsx(je,{tone:"neutral",children:O.mentioned===null?O.mentionUnavailableReason==="identity-ambiguous"?zl.ambiguous:"Mention not checked":O.mentioned?"Mentioned":"Not mentioned"}),e.jsx(je,{tone:"neutral",children:O.cited===null?"Citation not checked":O.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Ti,{headingLevel:4,copyable:!!O.answerText?.trim(),children:O.answerText??"Answer text unavailable."})}),O.sources.length>0?e.jsxs("details",{className:"mt-2","data-answer-sources":!0,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[Eh," (",O.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:O.sources.map(V=>e.jsx("li",{className:"min-w-0",children:e.jsx(ki,{url:V})},V))})]}):null]},O.answerId)),L(w).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:L(w).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,L(w).nextCursor&&x?e.jsx(T,{variant:"outline",onClick:()=>x(L(w).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Rs[w.queryClass]} competitors`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Competitors"}),e.jsx("span",{className:"visibility-disclosure-meta",children:w.competitorAvailability.state==="unavailable"?"Not available":`${w.competitors.length} measured`})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[w.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):w.competitors.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No measured competitors in this selection."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Competitor"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:w.competitors.map(O=>e.jsxs("tr",{children:[e.jsx("td",{children:O.domain}),e.jsx("td",{children:e.jsx(Sn,{value:O.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(Sn,{value:O.citationCoverage,signal:"cited"})})]},O.domain))})]})}),w.observedCompetitors.length>0?e.jsxs("details",{className:"mt-4 text-sm",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-heading",children:"Other names in answers"}),e.jsx("ul",{className:"divide-y divide-default",children:w.observedCompetitors.map(O=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:O.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[O.answerCount," ",O.answerCount===1?"answer":"answers"]})]},O.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},w.queryClass)})]})}function qg({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const l=new Map(n.filter(p=>p.kind==="group").map(p=>[p.id,p])),i=[...l.values()].some(p=>p.parentGroupIds?.length),c=t.breakdown.groups.filter(p=>{const x=l.get(p.id)?.parentGroupIds??[];return s.kind==="project"?x.length===0:s.kind==="group"&&i?x.includes(s.id):!0}),[d,m]=o.useState(()=>s.kind==="project"&&c.length>0?"groups":"properties"),u=Nn({rows:d==="groups"?c:t.breakdown.properties,getSearchText:p=>p.label});return e.jsxs("section",{className:"border-t border-default py-5","aria-label":"Scope breakdown",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsx("div",{className:"flex gap-2",children:["groups","properties"].map(p=>e.jsx(T,{variant:d===p?"secondary":"ghost",onClick:()=>{m(p),u.setPage(1)},children:p==="groups"?"Groups":"Properties"},p))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:u.query,onChange:p=>u.setQuery(p.target.value),className:`${dr} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:d==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:u.rows.map(p=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("button",{className:"min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>r({measurementScope:d==="groups"?"group":"property",measurementScopeKey:p.id,measurementMarketKey:a}),children:p.label})}),e.jsx("td",{children:p.queryCount}),e.jsxs("td",{children:[e.jsx(Sn,{value:p.mentionCoverage,signal:"mentioned"}),e.jsx(Vo,{value:p.mentionCoverage})]}),e.jsxs("td",{children:[e.jsx(Sn,{value:p.citationCoverage,signal:"cited"}),e.jsx(Vo,{value:p.citationCoverage})]})]},p.id))})]})}),u.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",d," match this search."]}):null,e.jsx(Ks,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:d,onPageChange:u.setPage})]})}function Tc(t,s,{enabled:n}){return qe({...tr({client:Y,path:{name:t},query:si(s)}),enabled:n,staleTime:Ul,retry:!1,placeholderData:wi})}function Mc(t,s){return s&&t.selection.mode==="simple"&&t.selection.measurement.state==="not-measured"}function Eg({projectName:t,selection:s,onSelectionChange:n,fallback:a,showUnmeasuredFallback:r=!1}){const[l,i]=o.useState(),[c,d]=o.useState(""),[m,u]=o.useState(),p=ms(),x=o.useMemo(()=>({scope:s.measurementScope,scopeKey:s.measurementScopeKey,marketKey:s.marketKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId}),[s.measurementScope,s.measurementScopeKey,s.marketKey,s.queryClass,s.provider,s.model,s.location,s.from,s.to,s.revision,s.measurementRunId]),h=qe({...tr({client:Y,path:{name:t},query:{...si(s),cursor:l,search:c||void 0}}),staleTime:Ul,retry:!1,placeholderData:wi}),y={...x,queryKey:s.queryKey,queryClass:s.answer?.queryClass??s.queryClass,provider:s.answer?.provider??s.provider,model:s.answer?s.answer.model??void 0:s.model,location:s.answer?s.answer.location??"none":s.location,runId:s.answer?.runId??h.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??h.data?.selection.revision??s.revision,limit:50},f=JSON.stringify(y),b=qe({...tr({client:Y,path:{name:t},query:{...y,cursor:m?.selection===f?m.cursor:void 0}}),enabled:!!s.queryKey&&!!h.data&&!h.isPlaceholderData,retry:!1});if(o.useEffect(()=>{if(s.queryClass!=="all"||!h.data||h.isPlaceholderData||h.isFetching||h.isError||h.data.selection.availability.state==="unsupported"||h.data.populations.length===0||s.queryKey&&!s.answer&&!xi(h.data,s.queryKey)&&!b.data)return;const j=$i(h.data,s.queryKey,s.answer,b.data);if(!l&&!c){const{queryKey:A}=tr({client:Y,path:{name:t},query:si({...s,queryClass:j.queryClass})});p.setQueryData(A,{...h.data,selection:{...h.data.selection,queryClass:j.queryClass},populations:[j]},{updatedAt:h.dataUpdatedAt})}n({queryClass:j.queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}},{replace:!0})},[s.queryClass,s.queryKey,s.answer,h.data,h.dataUpdatedAt,h.isPlaceholderData,h.isFetching,h.isError,b.data,n,p,t,x,l,c]),h.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:a});if(h.data&&Mc(h.data,r))return e.jsx(e.Fragment,{children:a});if(h.error){const j=Vl(Ql(h.error)),A=j?.reason===cu["retired-market"];return e.jsxs("section",{className:"page-section-divider",role:"alert",children:[e.jsx("h2",{children:"AI visibility unavailable"}),e.jsx("p",{className:"my-3 text-sm text-secondary",children:A?Ga.retiredMarket:j?Ga.retiredScope:ga(h.error)}),A?e.jsx(T,{variant:"outline",onClick:()=>{i(void 0),n({measurementMarketKey:void 0})},children:Ga.showAllMarkets}):j?e.jsx(T,{variant:"outline",onClick:()=>{i(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:Ga.showWholeSite}):e.jsx(T,{variant:"outline",onClick:()=>{i(void 0),h.refetch()},children:"Retry"})]})}return h.data?e.jsx("div",{"aria-busy":h.isFetching,children:e.jsx($g,{report:h.data,isRefreshing:h.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:b.data,isEvidenceLoading:b.isFetching||!!s.queryKey&&b.isPending,evidenceError:b.error?ga(b.error):void 0,onRetryEvidence:()=>{b.refetch()},onEvidencePage:b.isFetching?void 0:j=>u({selection:f,cursor:j}),search:c,onSearch:j=>{d(j),i(void 0)},onPage:h.isFetching?void 0:i,onSelectionChange:j=>{(!("measurementQueryKey"in j)||Object.keys(j).some(A=>A!=="measurementQueryKey"&&A!=="measurementAnswer"))&&i(void 0),u(void 0),n(j)}})}):e.jsx("section",{className:"page-section-divider",role:"status","aria-label":"Loading AI visibility",children:e.jsx("div",{className:"h-64 animate-pulse rounded-md bg-surface"})})}function Dg({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,fallback:l,showUnmeasuredFallback:i=!1}){const c=Tc(t,s,{enabled:!0}),d=c.error?void 0:c.data,m=!c.isPlaceholderData&&d?.selection.availability.state==="available"?d.selection.run.id:null;lu(m,null);const u=!!(d&&d.selection.availability.state==="available"&&!Mc(d,i));return e.jsxs(e.Fragment,{children:[u?e.jsx(Lg,{report:d,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}):null,!u&&(d||c.error)?e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsx(Ml,{})}):null,e.jsx(Eg,{projectName:t,selection:s,onSelectionChange:n,fallback:l,showUnmeasuredFallback:i},`${t}:${JSON.stringify({...s,queryKey:void 0,answer:void 0})}`)]})}const Og=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Fg=[{value:"mentioned",label:"Mentioned",description:"Your brand or domain appears in the answer text."},{value:"cited",label:"Cited",description:"Your domain appears in source or grounding links."},{value:"mentionShare",label:"Mention share",description:"Your share of the answer-text brand mentions for you and tracked competitors, in non-brand answers, or in all answers when queries cannot be split by brand."}],qi=lt[2],Kg=lt[4],Gg="var(--chart-tooltip-bg)",_g={up:"text-positive-400",down:"text-negative-400",none:"text-muted"};function Lc({direction:t,magnitude:s}){switch(t){case"up":return`up ${s} points`;case"down":return`down ${s} points`;case"none":return"no change"}}function Ug(t){return t.direction==="none"?"no change over the period":`${Lc(t)} over the period`}function Bg(t){return t===Ca||t===ka||t===Gs}function $c(t){return t===Ca?"Cited":t===ka?"Mentioned":t===Gs?"Mention share":ot(t)}function la(t,s){return t===Ca?Yn.positive:t===ka?lt[1]:t===Gs?qi:Kh(ja(t),s)}function Ei(t){return t==="non-brand"?"non-brand answers":"all answers"}function gi(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function Di(t,s){return t==="mentionShare"?`Mention share in ${Ei(s)}`:gi(t)}function Vg(t){return`Mentioned = share of answers that name you. Cited = share that link to your site. Mention share = your share of tracked-brand mentions in ${t==="non-brand"?"non-brand answers":"all answers"}.`}function qc(t){return t==="cited"?"citationRate":"mentionRate"}function Oi(t,s){return s==="cited"?t.cited:t.mentionedCount}function Ec(t,s,n){const a=t.byProvider[s];return a?{count:n==="cited"?a.cited:a.mentionedCount,total:a.total,rate:n==="cited"?a.citationRate:a.mentionRate}:null}function Qg(t,s){if(s==="mentionShare"){const{projectMentionSnapshots:n,competitorMentionSnapshots:a}=t.mentionShare;return`${n} of ${n+a} tracked-brand mentions`}return`${Oi(t,s)} of ${t.total} answers`}function zg(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Dc(t){const s=xc(t);return s===null?[]:Object.entries(s).sort(([n],[a])=>ja(n).localeCompare(ja(a))).map(([n,a])=>`${ot(n)}: ${Na(a)}`)}function Oc(t,s){return new Date(t).toDateString()===new Date(s).toDateString()}function Jo(t){return`${t} ${t===1?"query":"queries"}`}function Fi(t){const{added:s,removed:n}=t;return[...s.length>0?[`${Jo(s.length)} added`]:[],...n.length>0?[`${s.length>0?n.length:Jo(n.length)} removed`]:[]].join(", ")}function Fc(t,s){const n=Ls(t),a=Aa(t),r=vc(t,s);if(!n||!a||!r)return null;const l=ex(r.moves),i=Oc(n.start,n.end),c=d=>hr(d,i?n.start:null);return n.sweepCount===2?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes the ",e.jsx("strong",{children:c(n.start)})," sweep and the ",e.jsx("strong",{children:c(n.end)})," sweep, with ",l," between them"]}):r.moves.added.length+r.moves.removed.length>0?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes sweeps with ",l," between them"]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point pools ",e.jsx("strong",{children:n.sweepCount})," sweeps, with ",l," between the first and last"]})}function Hg(t,s,n){const a=Fc(s,n);return a?e.jsxs(e.Fragment,{children:["Not the same queries: ",a]}):t.changes.length>0?e.jsxs(e.Fragment,{children:["Not the same queries: ",t.changes.map((r,l)=>e.jsxs(o.Fragment,{children:[l>0?", ":"",Fi(r)," ",e.jsx("strong",{children:va(Ut(r.at))})]},r.at)),"; first and latest points cover different queries"]}):e.jsxs(e.Fragment,{children:["Not the same queries: first and latest points have answers for ",e.jsx("strong",{children:t.firstCount})," and ",e.jsx("strong",{children:t.latestCount})," queries"]})}function Xo(t){return t.replace(/ /g," ")}function ur({state:t,from:s=!1}){return e.jsx("span",{className:s?"av-model av-model-from":"av-model",children:Na(t)})}function Wg(t,s){return t.reroute?"Same preset, answered with a different model.":lr(t.provider,t.to)?t.served?`Preset picks its own model. Answered with ${Na(t.served.to)} (was ${Na(t.served.from)}).`:s&&s.length>0?`Preset picks its own model. Answered with ${s.join(", ")}.`:"Preset picks its own model.":null}function Yg({buckets:t,queryChanges:s,modelRows:n,served:a,pointerNotices:r,truncated:l,incompleteHistory:i,queryName:c,sweepTimes:d}){const m=t.at(-1),u=g=>va(g),p=new Map;for(const[g,v]of r){const S=n.find(L=>L.provider===g&&!L.reroute&&L.to.status==="known"&&v.modelIds.includes(L.to.model));S&&p.set(g,S)}const x=[];s.length>0&&x.push({key:"queries",label:"Queries",rows:s.map(g=>({key:`queries-${g.at}`,at:g.at,onOrBefore:!1,from:null,to:e.jsx("span",{className:"text-strong",children:Fi(g)}),toHelp:null}))});const h=[...new Set(n.map(g=>g.provider))].sort((g,v)=>ot(g).localeCompare(ot(v)));for(const g of h){const S=a[g]?.latestServedModelIds??null,L=n.filter(M=>M.provider===g);x.push({key:g,label:ot(g),rows:L.map((M,w)=>{const U=p.get(g)===M?r.get(g).text:null,F=[Wg(M,w===0?S:null),U].filter(Boolean).join(" ");return{key:`${g}-${M.at}-${M.reroute?"served":"set"}`,at:M.at,onOrBefore:M.onOrBefore,from:e.jsx(ur,{state:M.from,from:!0}),to:e.jsx(ur,{state:M.to}),toHelp:F||null}})})}const y=x.reduce((g,v)=>g+v.rows.length,0),f=[];for(const g of s)g.added.length>0&&f.push(e.jsxs(e.Fragment,{children:["Added ",e.jsx("strong",{children:u(g.at)}),": ",g.added.map(c).join(", ")]})),g.removed.length>0&&f.push(e.jsxs(e.Fragment,{children:["Removed ",e.jsx("strong",{children:u(g.at)}),": ",g.removed.map(c).join(", ")]}));const b=m?Aa(m):null;for(const[g,v]of Object.entries(m?xc(m)??{}:{}).sort(([S],[L])=>S.localeCompare(L)))v.status==="mixed"&&b&&f.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:b})," point mixes ",ot(g)," models: ",Ep(v)]}));const j=new Map;for(const g of n.filter(v=>v.onOrBefore)){const v=g.anchorAt?u(g.anchorAt):"";j.set(v,[...new Set([...j.get(v)??[],ot(g.provider)])])}for(const[g,v]of j)f.push(g?e.jsxs(e.Fragment,{children:["Changed before this date range, after the ",e.jsx("strong",{children:g})," sweep: ",pa(v)]}):`Changed before this date range: ${pa(v)}`);for(const g of l)f.push(`${ot(g.provider)}: most recent ${g.shown} of ${g.total} changes`);for(const g of i)f.push(`${ot(g)}: may be missing older changes`);for(const[g,v]of r)p.has(g)||f.push(e.jsxs("span",{className:"inline-flex items-center gap-1",children:[ot(g),": no model updates on record",e.jsx(Ge,{text:v.text})]}));if(y===0&&f.length===0)return null;for(const[g,v]of Object.entries(a).sort(([S],[L])=>ot(S).localeCompare(ot(L)))){const S=v.latestServedModelIds??[],L=S.length>0?S.join(", "):Na(v.latestObservation.state);f.push(e.jsxs(e.Fragment,{children:[ot(g)," last answered with ",e.jsx("strong",{children:L})," on ",e.jsx("strong",{children:u(Ut(v.latestObservation.observedAt))})]}))}const A=x.flatMap(g=>g.rows.map(v=>v.at));let P="First sweep on the new model or query set.";if(A.length>0){const g=u(A.reduce((U,F)=>Date.parse(F)>Date.parse(U)?F:U)),v=[...new Set(A.filter(U=>u(U)===g))].sort(),S=v.map(U=>hr(U,U));P+=` ${g} = the ${pa(S)} ${S.length===1?"sweep":"sweeps"}.`;const L=n.flatMap(U=>U.anchorAt?[U.anchorAt]:[]),M=L.length>0?L.reduce((U,F)=>Date.parse(F)>Date.parse(U)?F:U):null,w=Yp(v[0],d,t,M);w&&(P+=` Sweep before: ${u(w)}.`)}const C=Wp({latest:m,queryChanges:s,modelRows:n})??"No changes in this date range";return e.jsxs("details",{className:"av-wc",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"av-card-title",children:"What changed"}),e.jsx("span",{className:"av-wc-summary av-wc-when-closed",children:C}),e.jsxs("span",{className:"av-wc-toggle",children:[e.jsxs("span",{className:"av-wc-when-closed",children:[y>0?`Show all ${y}`:"Details"," ",e.jsx("span",{"aria-hidden":"true",children:"▸"})]}),e.jsxs("span",{className:"av-wc-when-open",children:["Hide ",e.jsx("span",{"aria-hidden":"true",children:"▴"})]})]})]}),e.jsx("div",{className:"av-wc-body",children:y>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"av-change-table",children:[e.jsx("caption",{className:"sr-only",children:"Query and model changes, newest first"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Changed"})}),e.jsx("th",{scope:"col","aria-label":"Date",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:["Date",e.jsx(Ge,{text:P})]})}),e.jsx("th",{scope:"col",children:"From"}),e.jsx("th",{scope:"col",children:"To"})]})}),x.map(g=>e.jsx("tbody",{children:g.rows.map((v,S)=>e.jsxs("tr",{children:[S===0?e.jsx("th",{scope:"row",className:"av-engine",children:g.label}):e.jsx("td",{className:"av-engine",children:e.jsx("span",{className:"sr-only",children:g.label})}),e.jsx("td",{className:"av-date",children:v.onOrBefore?`on or before ${Xo(u(v.at))}`:Xo(u(v.at))}),v.from===null?null:e.jsx("td",{children:v.from}),e.jsx("td",{colSpan:v.from===null?2:void 0,children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[v.to,v.toHelp?e.jsx(Ge,{text:v.toHelp}):null]})})]},v.key))},g.key))]})}),e.jsx(Sa,{items:f})]}):e.jsx("ul",{className:"av-details-list",children:f.map((g,v)=>e.jsx("li",{children:g},v))})})]})}function Jg({substitutions:t}){return t.length===0?null:e.jsx("ul",{className:"space-y-3","aria-label":"Model substitutions",children:t.map(({provider:s,mismatch:n})=>e.jsxs("li",{className:"av-amber-row border border-caution-800/60 bg-caution-950/20",children:[e.jsx("span",{className:"av-engine",children:ot(s)}),e.jsxs("span",{className:"text-secondary",children:["selected ",e.jsx(ur,{state:n.configured})," · answered ",e.jsx(ur,{state:n.served})]}),e.jsx("span",{className:"av-status text-caution-400",children:"substituted"})]},s))})}function Xg({active:t,label:s,payload:n,metric:a,mode:r,buckets:l,basketChanges:i}){if(!t)return null;const c=zg(l,s);if(!c)return null;const d=Ls(c),m=d!==null&&Oc(d.start,d.end)?d.start:null,u=yc(c,i),p=Dc(c),x=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-tooltip-label",children:Mi(c)}),u.map(f=>e.jsxs("p",{className:"trend-tooltip-detail trend-tooltip-note",children:[Fi(f)," ",hr(f.at,m)]},f.at))]}),h=p.length>0&&e.jsx("p",{className:"trend-tooltip-detail trend-tooltip-models",children:p.map((f,b)=>e.jsxs(o.Fragment,{children:[b>0?"; ":"",e.jsx("span",{className:"whitespace-nowrap",children:f})]},b))});if(a==="mentionShare"){const f=c.mentionShare.projectMentionSnapshots,b=c.mentionShare.competitorMentionSnapshots,j=f+b;return e.jsxs("div",{className:"trend-tooltip",children:[x,e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:qi},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Di("mentionShare",c.mentionShare.scope)}),e.jsx("span",{className:"trend-tooltip-value",children:tt(c.mentionShare.rate)})]}),e.jsx("p",{className:"trend-tooltip-detail",children:j>0?`You ${f} of ${j} tracked-brand mentions. Competitors ${b}.`:"No tracked-brand mentions in this point"}),h]})}const y=r==="byProvider"?(n??[]).filter(f=>f.dataKey!==void 0):[{dataKey:a==="cited"?Ca:ka}];return e.jsxs("div",{className:"trend-tooltip",children:[x,y.map((f,b)=>{const j=String(f.dataKey??f.name??""),A=r==="byProvider"?Ec(c,j,a):null,P=A?.count??Oi(c,a),C=A?.total??c.total,g=A?A.rate:c[qc(a)],v=f.color??la(j,b);return e.jsx("div",{className:"trend-tooltip-block",children:e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:v},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:$c(j)}),e.jsx("span",{className:"trend-tooltip-value",children:tt(g)}),e.jsxs("span",{className:"trend-tooltip-count",children:[P," of ",C]})]})},`${j}-${b}`)}),h]})}function Zg({buckets:t,metric:s,mode:n,series:a,mentionShareScope:r}){return e.jsx("div",{className:"sr-only",children:e.jsxs("table",{children:[e.jsxs("caption",{children:[Di(s,r)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Point"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(l=>{let i;if(s==="mentionShare"){const d=l.mentionShare.projectMentionSnapshots,m=l.mentionShare.competitorMentionSnapshots,u=d+m,p=Ei(l.mentionShare.scope);i=u>0?`${tt(l.mentionShare.rate)} mention share in ${p}, ${d} of ${u} tracked-brand mentions were you`:`mention share undefined in ${p}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(d=>{const m=Ec(l,d,s);return m?`${ot(d)} ${tt(m.rate)} ${gi(s).toLowerCase()}, ${m.count} of ${m.total} answers`:`${ot(d)} no data`}).join("; "):i=`${tt(l[qc(s)])} ${gi(s).toLowerCase()}, ${Oi(l,s)} of ${l.total} answers`;const c=Dc(l);return c.length>0&&(i+=`; models: ${c.join("; ")}`),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Mi(l)}),e.jsx("td",{children:i})]},l.startDate)})})]})})}function ef({projectName:t,competitorDomains:s=[],competitorAliases:n,analyticsRevision:a="none",queryTexts:r=[],classifyQuery:l,sweepTimes:i=[]}){const[c,d]=o.useState("all"),[m,u]=o.useState("mentioned"),[p,x]=o.useState("byProvider"),h=o.useId(),y=o.useMemo(()=>Pp(s,n),[s,n]),f=qe({queryKey:["analytics-metrics",t,c,y,a],queryFn:()=>ou(t,c),staleTime:Ri}),b=f.data??null,j=f.error,A=m==="mentionShare"?"overall":p,P=o.useMemo(()=>b?Gp(b,m,A):null,[b,m,A]),C=b?Mp(b):null,g=o.useMemo(()=>Op(C??{}),[C]),v=o.useMemo(()=>Fp(C??{}),[C]),S=o.useMemo(()=>Object.entries(C??{}).filter(([,me])=>me.anchorUnavailable).map(([me])=>me).sort(),[C]),L=o.useMemo(()=>b?Lp(b):{},[b]),M=o.useMemo(()=>b?Vp($p(b)):[],[b]),w=o.useMemo(()=>b?fc(b):[],[b]),U=o.useMemo(()=>b?Qp(b):[],[b]),F=o.useMemo(()=>Hp(C??{},L),[C,L]),z=o.useMemo(()=>b?qp(b):{},[b]),_=o.useMemo(()=>so(z,{engineName:ot}),[z]),B=o.useMemo(()=>{const me=new Map;for(const[Ae,st]of Object.entries(z).sort(([pe],[D])=>pe.localeCompare(D))){const pe=so({[Ae]:st},{engineName:ot});pe?.kind==="no-known-change"&&me.set(Ae,{text:`${pe.text} ${pe.detail}`,modelIds:st.modelIds??[]})}return me},[z]),te=o.useMemo(()=>{const me=new Map(r.map(Ae=>[Un(Ae),Ae]));return Ae=>me.get(Un(Ae))??Ae},[r]),O=m!=="mentionShare"&&A==="byProvider",V=b?.buckets??[],Q=V[V.length-1]?.mentionShare.scope??b?.mentionShareScope??"pooled",E=Di(m,Q),J=O?us.textDim:m==="cited"?Yn.positive:m==="mentionShare"?qi:lt[1],k=o.useMemo(()=>{const me=new Map(V.map(Ae=>[Ae.startDate,Rp(Ae)]));return Ae=>me.get(String(Ae))??""},[V]),H=m==="mentionShare"?V.filter(me=>typeof me.mentionShare.rate=="number"&&Number.isFinite(me.mentionShare.rate)):V,se=H.at(-1),oe=(b?_p(b,m):[]).at(-1)??null,ke=b?Up(b,m):null,X=Zp(H,w),ue=vo(X,m,Q,l),fe=oe!==null&&ke!==null?Bl(ke.delta):null,Z=fe!==null&&!ue,ce=s.length,G=[];if(se&&ke!==null&&X&&!ue&&G.push(Hg(X,se,w)),se&&H.length===1){const me=Fc(se,w);me&&!vo(vc(se,w),m,Q,l)&&G.push(me)}if(fe!==null&&H[0]){const me=Aa(H[0]);me&&G.push(e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:me})," point"]}))}O&&oe!==null&&G.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:tt(oe)})," pools all answers; not an average of engines"]}));const de=[...new Set([...g.buckets.map(me=>me.bucketStartDate),...V.filter(me=>yc(me,w).length>0).map(me=>me.startDate)])].sort(),De=oe!==null&&se&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:J},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:E}),e.jsx("span",{className:"visibility-trend-current-value",children:tt(oe)}),fe!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${Z?"text-muted":_g[fe.direction]}`,children:[Lc(fe),Z?" (not the same queries)":""]}),e.jsxs("span",{className:"visibility-trend-current-detail",children:["· ",Qg(se,m)]})]}),Re=e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(ha,{options:Fg,value:m,onChange:u,label:"Metric",className:"visibility-trend-metric-control"}),m!=="mentionShare"&&e.jsx(ha,{options:Og,value:p,onChange:x,label:"Series"}),e.jsx(ha,{options:gg,value:c,onChange:d,label:"Time window",className:"sm:ml-auto"})]});let re;if(j)re=e.jsx("p",{className:"text-sm text-negative-400",children:ga(j)});else if(f.isLoading&&!b)re=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(m==="mentionShare"&&ce===0)re=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!b||!P)re=null;else{const{rows:me,series:Ae,hasData:st}=P;if(!st)re=e.jsx("p",{className:"text-sm text-secondary",children:m==="mentionShare"?`No answer-text brand mentions for you or tracked competitors in ${Ei(Q)} in this window yet.`:cs()?Vn:"Run a sweep to start tracking citations and mentions over time."});else if(O&&Ae.length===0)re=e.jsxs("p",{className:"text-sm text-secondary",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-strong",children:"All engines"})," to see the trend."]});else{const pe=`${E} rate across ${me.length} ${me.length===1?"sweep":"sweeps"}. Latest ${tt(oe)}${fe!==null?`, ${Ug(fe)}${Z?", not the same queries":""}`:""}.`;re=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:pe}),e.jsx(Zg,{buckets:V,metric:m,mode:A,series:Ae,mentionShareScope:Q}),O&&Ae.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:Ae.map((D,Oe)=>{const I=Bp(b,D,m);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:la(D,Oe)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:$c(D)}),I!==null&&e.jsx("span",{className:"trend-legend-value",children:tt(I)})]},D)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${E} trend chart over ${me.length} ${me.length===1?"point":"points"}`,children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:me,margin:{top:8,right:20,bottom:0,left:0},children:[e.jsx(ba,{stroke:fa,vertical:!1}),e.jsx(sn,{dataKey:"date",tick:_t,tickLine:!1,axisLine:{stroke:ds},tickFormatter:k,minTickGap:24}),e.jsx(nn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:D=>tt(D,Wn.percent),tick:_t,tickLine:!1,axisLine:!1,width:40}),e.jsx(an,{cursor:{stroke:ds,strokeWidth:1},content:e.jsx(Xg,{metric:m,mode:A,buckets:V,basketChanges:w})}),de.map(D=>e.jsx(ip,{x:D,stroke:Kg,strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`setup-change-${D}`)),Ae.map((D,Oe)=>e.jsx(Fs,{type:"monotone",dataKey:D,name:D,stroke:la(D,Oe),strokeDasharray:D===Gs?"5 4":void 0,strokeWidth:Bg(D)?2.5:2,dot:D===Gs?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:la(D,Oe),strokeWidth:1.5}:{r:2.5,fill:la(D,Oe),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Gg},connectNulls:D!==Gs,isAnimationActive:!1},D))]})})}),de.length>0&&e.jsxs("p",{className:"visibility-trend-key",children:[e.jsx("span",{className:"visibility-trend-key-swatch","aria-hidden":"true"}),"Setup changed"]})]})}}return e.jsxs("div",{className:"visibility-trend-stack",children:[e.jsxs("section",{className:"visibility-trend","aria-labelledby":h,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:h,className:"av-card-title",children:"AI answers over time"}),e.jsx(Ge,{text:Vg(Q)})]}),se?e.jsx("p",{className:"av-card-meta",children:Mi(se)}):null]}),e.jsxs("div",{className:"visibility-trend-body",children:[_?.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:_.text}),De,Re,re]}),e.jsx(Sa,{items:G})]}),b&&!j?e.jsxs(e.Fragment,{children:[e.jsx(Yg,{buckets:V,queryChanges:U,modelRows:F,served:L,pointerNotices:B,truncated:v,incompleteHistory:S,queryName:te,sweepTimes:i}),e.jsx(Jg,{substitutions:M})]}):null]})}const Zo=new Set([ma.queued,ma.running]),Gt={queryPlaceholder:"Write one research query per line",runAction:"Run queries",historyTitle:"Research history",historyMore:"Load older runs",historyLoading:"Loading older runs…",historyMoreError:"Could not load older research. Try again.",resultsTitle:"Research results",emptyHistory:"No saved research.",resultsEmpty:"Choose a saved run.",methodologySummary:"How matching works",methodology:"Brand-name matches use configured project names or domains in answer text. Project-domain citations use source links. Neither verifies property identity.",refreshPreview:"Regenerate preview",templateProvenance:"Query pattern details",brandedQuery:"Branded",discoveryQuery:"Discovery",unclassifiedQuery:"Unclassified"};function el({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d=[],viewerResearchConfig:m=null}){const u=ms(),{account:p,canWrite:x}=rn(),h=p?.role==="viewer"&&m!==null,y=!x,f=Ms(),[b,j]=o.useState(""),[A,P]=o.useState(""),[C,g]=o.useState(null),[v,S]=o.useState([]),L=o.useRef(null),M=o.useRef(!1),[w,U]=o.useState(0),F=qe({...du({client:Y,path:{name:t}}),staleTime:6e4}),z=qe({...uu({client:Y}),enabled:!y&&!f,staleTime:6e4}),_={client:Y,path:{name:t},query:{limit:20}},B=Tl({...mu(_),initialData:void 0,initialPageParam:_,getNextPageParam:G=>G.nextCursor?{path:_.path,query:{..._.query,cursor:G.nextCursor}}:void 0,refetchInterval:G=>G.state.data?.pages.some(de=>de.runs.some(De=>Zo.has(De.status)))?3e3:!1}),te=B.isError&&!B.isFetchNextPageError,O=B.data?.pages.at(-1),V=te?[]:[...new Map((B.data?.pages.flatMap(G=>G.runs)??[]).map(G=>[G.id,G])).values()],Q=O?.access?.canRun??(x||h),E=O?.access?O.access.dailyRunLimit:h?m.viewerDailyRunLimit:null;o.useEffect(()=>{!C&&V[0]&&g(V[0].id)},[V,C]);const J=V.find(G=>G.id===C)??null,k=qe({...hu({client:Y,path:{name:t,runId:C??""}}),enabled:!te&&!!C,refetchInterval:J&&Zo.has(J.status)?3e3:!1}),H=te||k.isError?null:k.data??null,se=F.data?.locations??[],ne=o.useMemo(()=>{if(y)return(O?.providers??[]).map(de=>({...de,catalog:de}));const G=new Map((z.data?.providerCatalog??[]).map(de=>[de.name,de]));return(z.data?.providers??[]).filter(de=>de.configured&&G.get(de.name)?.mode==="api").map(de=>({...de,catalog:{...G.get(de.name),defaultModel:de.model||G.get(de.name).defaultModel}}))},[y,O?.providers,z.data]),oe=!(y?B.isPending:z.isPending)&&ne.length===0,ke=ne.find(G=>G.name===b)??null;o.useEffect(()=>{if(!b&&F.data&&!F.isError&&!z.isError){const G=F.data.providers.find(de=>ne.some(De=>De.name===de));j(G??ne[0]?.name??"")}},[b,ne,F.data,F.isError,z.isError]);const X=ke?.catalog.modelConfigurable??!1,ue=y?ke?.catalog.defaultModel:(ke?F.data?.providerModels[ke.name]:"")||ke?.catalog.defaultModel,fe=(X?A.trim():"")||ue,Z=ke?[...new Map([{id:ke.catalog.defaultModel,displayName:ke.catalog.defaultModel},...A.trim()?[{id:A.trim(),displayName:A.trim()}]:[],...ke.catalog.knownModels].map(G=>[G.id,G])).values()]:[],ce=Ot({...pu(),onSuccess:async G=>{L.current=null,U(de=>de+1),S(G.runs),g(G.runs[0]?.id??null),await uf(u),Fe({title:"Research batch saved",detail:`${G.runs.length} ${G.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${G.runs.map(de=>de.id).join(":")}`,dedupeMode:"replace"})},onError:G=>{Fe({title:"Could not start research",detail:G instanceof Error?G.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{M.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[f?e.jsx(ve,{className:"surface-card min-w-0",children:e.jsx("p",{className:"text-sm text-secondary",children:"This public demo shows saved research results. Running research is unavailable."})}):e.jsxs(e.Fragment,{children:[e.jsx(tf,{projectName:t,canWrite:x,researchAllowed:Q&&!te,limitedAccess:y,isEmbed:ie(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d,locations:se,defaultLocation:F.data?.defaultLocation??null,providerOptions:ne,provider:b,onProviderChange:G=>{j(G),P("")},resolvedModel:fe,visibilityModel:ue,configurableModel:X,model:A,onModelChange:P,modelOptions:Z,settingsReady:y?!B.isPending&&!te:!z.isPending&&!z.isError&&!z.isFetching,projectReady:!F.isPending&&!F.isError&&!F.isFetching,isPending:ce.isPending,errorMessage:ce.isError?"The request could not be confirmed.":void 0,onSubmit:(G,de)=>{!Q||te||ie()||M.current||(L.current?.fingerprint!==de&&(L.current={fingerprint:de,key:crypto.randomUUID()}),M.current=!0,ce.mutate({client:Y,path:{name:t},body:{...G,idempotencyKey:L.current.key}}))}},`${t}:${w}`),E!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",E," destination runs per project per day."]}),!y&&z.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(T,{variant:"outline",onClick:()=>{z.refetch()},children:"Retry providers"})]}):null,F.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(T,{variant:"outline",onClick:()=>{F.refetch()},children:"Retry locations"})]}):null,!(y?te:z.isError)&&oe&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:y?"No research engines are available. Ask your Canonry team to configure one.":"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."}),v.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",v.map((G,de)=>e.jsxs("span",{children:[de>0?", ":"",e.jsxs("a",{href:`#research-run-${G.id}`,className:"text-link underline",onClick:()=>g(G.id),children:[G.scope?.label??"Whole site",G.location?`, ${G.location.label}`:", No location"]})]},G.id))]})]}),e.jsxs(ve,{className:"surface-card min-w-0",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsx("div",{children:e.jsx("h3",{children:Gt.historyTitle})}),B.isFetching&&e.jsx(je,{tone:"neutral",children:"Loading"})]}),te?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(T,{variant:"outline",onClick:()=>{B.refetch()},children:"Retry history"})]}):B.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):V.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:Gt.emptyHistory}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Destination"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:V.map(G=>e.jsxs("tr",{className:C===G.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>g(G.id),children:lf(G.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:G.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:G.requestedModel??G.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:G.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:G.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[G.completedQueries+G.failedQueries,"/",G.totalQueries]}),e.jsx("td",{children:e.jsx(je,{tone:Kc(G.status),children:G.status})})]},G.id))})]})}),B.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:Gt.historyMoreError}),B.hasNextPage&&e.jsx(T,{className:"mt-3",variant:"outline",disabled:B.isFetching,onClick:()=>{B.fetchNextPage()},children:B.isFetchingNextPage?Gt.historyLoading:Gt.historyMore})]})]}),!te&&k.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(T,{variant:"outline",onClick:()=>{k.refetch()},children:"Retry results"})]}):te?null:e.jsx(rf,{detail:H,isLoading:k.isFetching,onReviewForTracking:f?void 0:s})]})}const Ps="mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50",On="__none__";function tf(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:l}=t,i=ms(),[c,d]=o.useState("once"),[m,u]=o.useState(""),[p,x]=o.useState(""),[h,y]=o.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[f,b]=o.useState(null),[j,A]=o.useState([]),[P,C]=o.useState(""),[g,v]=o.useState({}),[S,L]=o.useState(null),[M,w]=o.useState([]),[U,F]=o.useState(null),[z,_]=o.useState(!1),[B,te]=o.useState(!1),[O,V]=o.useState(""),[Q,E]=o.useState(""),J=o.useRef(null),k=o.useRef(!1),H=o.useRef(null),se=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";o.useEffect(()=>{y(se),L(null)},[se]);const ne=t.scopeOptions.filter(R=>R.kind==="market"||R.kind==="property"),oe=c==="markets"?"market":"property",ke=ne.filter(R=>R.kind===oe),X=R=>({kind:R.kind,key:R.id,label:R.label,planRevision:l??t.initialScope?.planRevision??0}),ue=R=>R===On?null:n.find(Me=>Me.label===R),fe=f??t.defaultLocation??On,Z=ne.find(R=>`${R.kind}:${R.id}`===h),ce=Z?X(Z):null,G=c==="once"?[{scope:ce,location:ue(fe)}]:c==="locations"?j.map(R=>({scope:null,location:ue(R)})):j.map(R=>ke.find(Me=>`${Me.kind}:${Me.id}`===R)).map(R=>R?{scope:X(R),location:ue(g[`${R.kind}:${R.id}`]??On)}:null),de=[...new Map([...M,...t.templates].map(R=>[R.id,R])).values()],De=S?de.find(R=>R.id===S.id):null,Re=S!==null&&De?.version!==S.version,re=c==="once"?m:p,me=re.split(/\r?\n/).filter(R=>R.trim()),Ae=no(me),st=[...new Set([...p.matchAll(/\{([^{}]+)\}/g)].map(R=>R[1]))],pe=/[{}]/.test(p.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),D=[];me.length||D.push(c==="once"?"Enter at least one query.":"Enter at least one query pattern."),me.some(R=>R.length>4e3)&&D.push("Keep each query under 4,001 characters."),c!=="once"&&pe&&D.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),G.length||D.push(c==="locations"?"Select at least one location.":"Select at least one destination."),G.some(R=>!R||R.location===void 0)&&D.push("A selected destination or location is no longer available. Update your selection.");const Oe=c==="once"&&h!=="project"||c==="markets"||c==="properties";Oe&&(t.scopePending||t.scopeError||!l||G.some(R=>!R?.scope))&&D.push("Load the current published markets and properties before running scoped research.");const I=(c==="once"?Ae.length:me.length)*G.length;if(G.length>$a&&D.push(`Select at most ${$a} destinations.`),I>Cr&&D.push(`${I} queries selected. Reduce the selection to ${Cr} or fewer.`),Re&&D.push("This saved pattern changed. Select its current version from Saved patterns."),c!=="once"&&!pe){for(const R of G)if(!(!R||R.location===void 0))try{Sr(S??{pattern:p,variables:st},R.scope,R.location)}catch{D.push(`Choose a location for {location}, or use only variables available for ${c==="markets"?"markets":c==="properties"?"properties":"locations"}.`);break}}const ye=JSON.stringify({mode:c,source:re,contexts:G,provider:a,resolvedModel:r,template:S,...Oe?{planRevision:l}:{}}),_e=U!==null&&U.signature!==ye,ze=c==="once"?Ae.map((R,Me)=>({id:String(Me),query:R,scope:ce,location:G[0]?.location??null})):U?.rows??[],Be=af(ze),be=[];c!=="once"&&U&&(_e&&be.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),ze.some(R=>!R.query.trim()||R.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(R.query))&&be.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),ze.some(R=>R.location&&!n.some(Me=>JSON.stringify(Me)===JSON.stringify(R.location)))&&be.push("A preview location changed. Regenerate the preview."),Be.some(R=>no(R.queries).length!==R.queries.length)&&be.push("Remove duplicate queries within each destination and location."),Be.length>$a&&be.push(`The preview exceeds ${$a} runs.`));const xt=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!D.length&&!be.length&&(c==="once"||U!==null),Ke=()=>({runs:Be.map(R=>({queries:R.queries,provider:a,model:r,location:R.location,...R.scope?{scope:{kind:R.scope.kind,key:R.scope.key,expectedPlanRevision:R.scope.planRevision}}:{},...R.template?{template:R.template}:{}}))}),Xe=()=>{if(_(!0),D.length)return;const R=G.flatMap((Me,we)=>me.map((Le,At)=>({id:`${we}:${At}`,scope:Me.scope,location:Me.location,...S?{template:{templateId:S.id,templateVersion:S.version,bindingLocation:Me.location}}:{},query:Sr({pattern:Le,variables:[...new Set([...Le.matchAll(/\{([^{}]+)\}/g)].map(It=>It[1]))]},Me.scope,Me.location).output})));F({signature:ye,rows:R})},ts=R=>{d(R),A([]),L(null),C(""),_(!1)},it=R=>{if(E(""),c==="once")try{u(Sr(R,ce,ue(fe)).output)}catch{E("Select a matching market, property, or location before using this pattern.");return}else x(R.pattern);L(R)},nt=R=>{const Me=H.current,we=Me?.selectionStart??p.length,Le=Me?.selectionEnd??we;x(`${p.slice(0,we)}{${R}}${p.slice(Le)}`),L(null),requestAnimationFrame(()=>{Me?.focus(),Me?.setSelectionRange(we+R.length+2,we+R.length+2)})},ut=Ot({...gu(),onSuccess:async R=>{const Me={id:R.id,version:R.updatedAt,label:R.name,pattern:R.pattern,variables:R.variables};w(we=>[...we.filter(Le=>Le.id!==R.id),Me]),L(Me),te(!1),V(""),E(""),J.current=null,await i.invalidateQueries({queryKey:xu({client:Y,path:{name:s}})}),Fe({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>E("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{k.current=!1}}),wt=()=>{if(!t.canWrite||t.isEmbed||k.current)return;const R=c==="once"?m:p,Me=c==="once"?[]:st;if(!O.trim()||!R.trim()||R.length>4e3||c!=="once"&&pe){E("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const we={name:O.trim(),pattern:R,variables:Me},Le=JSON.stringify(we);J.current?.fingerprint!==Le&&(J.current={fingerprint:Le,id:crypto.randomUUID()}),k.current=!0,ut.mutate({client:Y,path:{name:s,templateId:J.current.id},body:we})},Mt=[...new Set([...z||re.trim()?D:[],...be])],Ve=de.filter(R=>{const Me=c==="once"?ao(ce,ue(fe)):ao(c==="markets"?{kind:"market",label:"Market"}:c==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return R.variables.every(we=>Me[we]!==void 0)});return e.jsxs(ve,{className:"surface-card min-w-0",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Test queries"}),e.jsx("p",{className:"mt-1 max-w-prose text-sm text-secondary",children:"See how an answer engine responds. Results are saved separately from tracked queries and AI Visibility metrics."})]})}),e.jsxs("fieldset",{"aria-label":"Research setup",className:"mt-5 min-w-0 space-y-5",disabled:t.isPending||ut.isPending,children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Run mode"}),e.jsxs("select",{className:Ps,value:c,disabled:t.isPending,onChange:R=>ts(R.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!ne.some(R=>R.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!ne.some(R=>R.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),c==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(ne.length>0||h!=="project")&&e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Save results under"}),e.jsxs("select",{className:Ps,value:h,onChange:R=>{y(R.target.value),L(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),h!=="project"&&!Z&&e.jsx("option",{value:h,disabled:!0,children:"Selected destination unavailable"}),ne.map(R=>e.jsxs("option",{value:`${R.kind}:${R.id}`,children:[R.label," (",R.kind,")"]},`${R.kind}:${R.id}`))]})]}),e.jsx(fi,{label:"Answer engine location",value:fe,locations:n,onChange:R=>{b(R),L(null)}})]}),c!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:c==="locations"?"Select locations":`Select ${c}`}),e.jsx("p",{className:"text-sm text-secondary",children:"Choose each destination explicitly. Each selected destination gets its own saved research run."}),e.jsx("input",{type:"search","aria-label":"Search destinations",className:Ps,placeholder:`Search ${c}`,value:P,onChange:R=>C(R.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(c==="locations"?n.map(R=>({key:R.label,label:R.label})):ke.map(R=>({key:`${R.kind}:${R.id}`,label:R.label}))).filter(R=>R.label.toLocaleLowerCase().includes(P.toLocaleLowerCase())).map(R=>{const Me=j.includes(R.key);return e.jsxs("div",{className:"grid items-center gap-2 border-b border-default pb-2 sm:grid-cols-[minmax(0,1fr)_16rem]",children:[e.jsxs("label",{className:"flex min-h-11 items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:Me,onChange:()=>A(we=>Me?we.filter(Le=>Le!==R.key):[...we,R.key])}),R.label]}),Me&&c!=="locations"&&e.jsx(fi,{label:`Answer engine location for ${R.label}`,value:g[R.key]??On,locations:n,onChange:we=>v(Le=>({...Le,[R.key]:we}))})]},R.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[j.length," selected. A market or property name changes query text, not the answer engine's location."]})]}),t.scopeError&&e.jsxs("p",{className:"text-sm text-caution",children:["Markets and properties could not load. Whole-site and location research remain available. ",e.jsx(T,{variant:"outline",onClick:t.onRetryScope,children:"Retry destinations"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block",htmlFor:"research-query-editor",children:e.jsx("span",{className:"text-sm font-medium text-heading",children:c==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:c==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${c==="markets"?"market":c==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:H,className:`${Ps} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:re,placeholder:c==="once"?Gt.queryPlaceholder:c==="markets"?"Best apartments in {market}":c==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:R=>{c==="once"?u(R.target.value):(x(R.target.value),L(null))}}),c!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(T,{size:"sm",variant:"outline",onClick:()=>nt(c==="markets"?"market":c==="properties"?"property":"location"),children:["Insert ",c==="markets"?"market":c==="properties"?"property":"location"," name"]}),e.jsx("span",{className:"self-center text-sm text-secondary",children:"One pattern per line."})]}),e.jsxs("p",{id:"research-query-count",className:"mt-2 text-sm text-secondary",children:[I," / ",Cr," queries",c==="once"?"":` across ${G.length} destinations`]})]}),c!=="once"&&e.jsxs("details",{className:"border-t border-default pt-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading focus-visible:outline focus-visible:outline-2",children:["Saved patterns ",e.jsx("span",{className:"font-normal text-secondary",children:"(optional)"})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries."}),Ve.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:Ve.map(R=>e.jsx(T,{size:"sm",variant:"outline",onClick:()=>it(R),children:R.label},R.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),S&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",S.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(T,{size:"sm",variant:"outline",onClick:()=>te(!B),children:B?"Cancel save":"Save as a pattern"}),B&&e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("label",{className:"min-w-48 flex-1 text-sm text-heading",children:["Pattern name",e.jsx("input",{className:Ps,value:O,maxLength:120,onChange:R=>V(R.target.value)})]}),e.jsx(T,{size:"sm",disabled:ut.isPending||!O.trim()||!re.trim(),onClick:wt,children:ut.isPending?"Saving…":"Save pattern"})]})]}),Q&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:Q})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Answer engine",e.jsxs("select",{className:Ps,value:a,onChange:R=>t.onProviderChange(R.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose an answer engine"}),t.providerOptions.map(R=>e.jsx("option",{value:R.name,children:R.displayName??R.name},R.name))]})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Model",t.limitedAccess?e.jsxs("select",{className:Ps,value:t.model,disabled:!a||!t.configurableModel,onChange:R=>t.onModelChange(R.target.value),children:[e.jsxs("option",{value:"",children:["Use AI Visibility model · ",t.visibilityModel]}),t.modelOptions.map(R=>e.jsx("option",{value:R.id,children:R.displayName},R.id))]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{"aria-label":"Model",className:Ps,list:"research-known-models",placeholder:r??"Choose an answer engine",value:t.model,disabled:!a||!t.configurableModel,onChange:R=>t.onModelChange(R.target.value)}),e.jsx("datalist",{id:"research-known-models",children:t.modelOptions.map(R=>e.jsx("option",{value:R.id,children:R.displayName},R.id))})]})]})]}),Mt.length>0&&e.jsx(nf,{errors:Mt}),c!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(T,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:Xe,children:[e.jsx(ya,{size:14}),U?Gt.refreshPreview:"Preview queries"]}),U&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Queries to run"}),e.jsxs("p",{className:"text-sm text-secondary",children:[ze.length," query executions in ",Be.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(sf,{rows:ze,locations:n,onChange:(R,Me)=>F(we=>we&&{...we,rows:we.rows.map(Le=>Le.id===R?{...Le,...Me}:Le)})})]})]}),t.errorMessage&&e.jsxs("p",{role:"alert",className:"text-sm text-negative",children:[t.errorMessage," Your entries are preserved. Retry unchanged entries to avoid duplicate work."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!t.isEmbed&&e.jsxs(T,{size:"sm",disabled:!xt,onClick:()=>{if(xt){const R=Ke();t.onSubmit(R,JSON.stringify({projectName:s,...R}))}},children:[e.jsx(ir,{size:14}),t.isPending?"Starting…":Gt.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[c==="once"?`${Ae.length} queries`:`${ze.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function fi({label:t,value:s,locations:n,onChange:a}){return e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:t}),e.jsxs("select",{className:Ps,value:s,onChange:r=>a(r.target.value),children:[e.jsx("option",{value:On,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function sf({rows:t,locations:s,onChange:n}){return e.jsx("ol",{className:"divide-y divide-default",children:t.map((a,r)=>e.jsxs("li",{className:"grid gap-3 py-4 md:grid-cols-[10rem_minmax(0,1fr)_15rem]",children:[e.jsxs("div",{className:"text-sm",children:[e.jsxs("span",{className:"block text-secondary",children:["Query ",r+1]}),e.jsx("span",{className:"font-medium text-heading",children:a.scope?.label??a.location?.label??"Whole site"}),a.scope&&e.jsx("span",{className:"block text-secondary",children:a.scope.kind})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Query",e.jsx("textarea",{className:`${Ps} min-h-20`,"aria-label":`Query ${r+1} for ${a.scope?.label??a.location?.label??"Whole site"}`,value:a.query,onChange:l=>n(a.id,{query:l.target.value})})]}),e.jsx(fi,{label:`Location for query ${r+1}`,value:a.location?.label??On,locations:s,onChange:l=>n(a.id,{location:s.find(i=>i.label===l)??null})})]},a.id))})}function nf({errors:t}){return e.jsx("div",{role:"alert",className:"text-sm text-negative",children:e.jsx("ul",{className:"list-disc space-y-1 pl-5",children:t.map(s=>e.jsx("li",{children:s},s))})})}function af(t){const s=new Map;for(const n of t){const a=JSON.stringify({scope:n.scope,location:n.location,template:n.template}),r=s.get(a)??{scope:n.scope,location:n.location,queries:[],...n.template?{template:n.template}:{}};r.queries.push(n.query),s.set(a,r)}return[...s.values()]}function rf({detail:t,isLoading:s,onReviewForTracking:n}){const[a,r]=o.useState(null);o.useEffect(()=>{r(t?.queries[0]?.id??null)},[t?.id]);const l=t?.queries.find(i=>i.id===a)??t?.queries[0]??null;return e.jsxs(ve,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":Gt.resultsTitle,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Results"}),e.jsx("h3",{children:t?`Research run ${cf(t.id)}`:Gt.resultsEmpty})]}),t&&e.jsx(je,{tone:Kc(t.status),children:t.status})]}),t&&e.jsxs("div",{className:"mt-3 space-y-3 text-sm text-secondary",children:[e.jsxs("dl",{className:"flex flex-wrap gap-x-6 gap-y-2 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Answer engine"}),e.jsx("dd",{children:t.provider})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Requested model"}),e.jsx("dd",{className:"font-mono",children:t.requestedModel??t.resolvedModel})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Location"}),e.jsx("dd",{children:t.location?.label??"No location"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Destination"}),e.jsx("dd",{children:t.scope?.label??"Whole site"})]})]}),t.template&&e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:Gt.templateProvenance}),e.jsxs("dl",{className:"mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Saved pattern"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.template})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Names used"}),e.jsx("dd",{children:Object.entries(t.template.bindings).map(([i,c])=>`${i}: ${c}`).join(" · ")||"No variables"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Original resolved text"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.output})]})]}),e.jsx("p",{className:"mt-2",children:"The queries below are the final text sent to the answer engine, including any edits."}),e.jsxs("p",{className:"mt-2 font-mono text-xs",children:[t.template.templateId," · ",t.template.templateVersion]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:Gt.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:Gt.methodology})]})]}),t?e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Class"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Brand-name match"}),e.jsx("th",{children:"Project domain cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:l?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>r(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(je,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?Gt.brandedQuery:i.queryClass==="non-brand"?Gt.discoveryQuery:Gt.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(je,{tone:df(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(je,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===jn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===jn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(je,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===jn.failed?"negative":"caution",children:i.citationState===null?i.status===jn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(of,{query:l,scope:t.scope??null,isLoading:s,onReviewForTracking:n})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved run to inspect each answer and its source links."})]})}function of({query:t,isLoading:s,scope:n,onReviewForTracking:a}){return t?e.jsxs("div",{className:"min-w-0 space-y-4 border-t border-default pt-4 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),!ie()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(We,{type:"button",size:"sm",onClick:()=>a({researchRunQueryId:t.id,scope:n}),children:"Review for tracking"}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Only this saved query text enters tracking review. Its answer remains research evidence."})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("div",{className:"mt-1",children:e.jsx(Ti,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===jn.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r},r))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r.replace(/^www\./,"")},r))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-3",children:t.groundingSources.map((r,l)=>e.jsx("li",{className:"min-w-0",children:e.jsx(ki,{url:r.uri,title:r.title})},`${r.uri}-${l}`))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function lf(t){const s=new Date(t);return Number.isNaN(s.valueOf())?t:new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(s)}function cf(t){return t.length>8?t.slice(0,8):t}function Kc(t){return t===ma.completed?"positive":t===ma.partial?"caution":t===ma.failed?"negative":"neutral"}function df(t){return t===jn.completed?"positive":t===jn.failed?"negative":"neutral"}async function uf(t){await Tt(t,"researchRuns")}const yi=new Set(["queued","seeding","probing"]);function mf({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:l={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d}){const{account:m}=rn(),[u,p]=o.useState("tracked"),[x,h]=o.useState("find"),[y,f]=o.useState(null),b=m?.role==="viewer"?Hl():null,j=cc(m?.role,b),P=dc(s??u,j),C=a??x,g=L=>{s===void 0&&p(L),n?.(L)},v=L=>{a===void 0&&h(L),r?.(L)},S=(L,M)=>{const w=M===void 0?{...l}:{...l,measurementScope:M?.kind??"project",measurementScopeKey:M?.key};f({...L,trackingSelection:w}),M!==void 0&&i?.({measurementScope:w.measurementScope,measurementScopeKey:w.measurementScopeKey}),g("tracked")};return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"queries-heading",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"queries-heading",children:"Queries"})}),e.jsxs("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Query workspace",children:[e.jsx(mr,{active:P==="tracked",label:"Tracked",onClick:()=>g("tracked")}),j?e.jsx(mr,{active:P==="research",label:"Research",onClick:()=>g("research")}):null]}),e.jsx("div",{className:"mt-4",children:P==="tracked"?e.jsx(Mf,{projectName:t,selection:l,onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d,pendingTrackingSource:y,onPendingTrackingSourceHandled:()=>f(null)}):e.jsx(hf,{projectName:t,selection:l,mode:C,onModeChange:v,onReviewSavedSource:S,onSelectionChange:i,viewerResearchConfig:b})})]})}function mr({active:t,label:s,onClick:n}){return e.jsx("button",{type:"button",role:"tab","aria-selected":t,className:`-mb-px border-b-2 px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500 focus-visible:ring-inset ${t?"border-mono-400 text-heading":"border-transparent text-muted hover:border-strong hover:text-strong"}`,onClick:n,children:s})}function hf({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:l}){const{canWrite:i}=rn(),c=!i||n==="test",d=qe({...Ii({client:Y,path:{name:t}}),enabled:c,staleTime:6e4}),m=qe({...Wl({client:Y,path:{name:t}}),enabled:c,staleTime:6e4}),u=o.useMemo(()=>{const h=d.data;if(!h)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const y=new Map(h.targets.map(b=>[b.stableKey,[]]));for(const b of h.groups)for(const j of b.targetKeys)y.get(j)?.push(b.stableKey);const f=new Map(h.markets.map(b=>[b.stableKey,new Set]));for(const b of h.markets)for(const j of b.usageEdges)for(const A of y.get(j.targetKey)??[])f.get(b.stableKey)?.add(A);return[{id:"project",label:"Whole site",kind:"project",targetCount:h.targets.length},...h.groups.map(b=>({id:b.stableKey,label:b.label,kind:"group",targetCount:b.targetKeys.length,...b.parentGroupKey?{parentGroupIds:[b.parentGroupKey]}:{}})),...h.markets.map(b=>{const j=[...f.get(b.stableKey)??[]];return{id:b.stableKey,label:b.label,kind:"market",targetCount:0,...j.length?{parentGroupIds:j}:{}}}),...h.targets.map(b=>({id:b.stableKey,label:b.label,kind:"property",targetCount:1,...y.get(b.stableKey)?.length?{parentGroupIds:y.get(b.stableKey)}:{}}))]},[d.data]),p=o.useMemo(()=>(m.data?.templates??[]).map(h=>({id:h.id,version:h.updatedAt,label:h.name,pattern:h.pattern,variables:h.variables})),[m.data]),x={projectName:t,scopeOptions:u,planRevision:d.data?.active?.revision??null,selectedScope:(()=>{const h=u.find(f=>f.kind===s.measurementScope&&f.id===s.measurementScopeKey),y=d.data?.active?.revision;return h&&y&&(h.kind==="market"||h.kind==="property")?{kind:h.kind,key:h.id,label:h.label,planRevision:y,expectedPlanRevision:y}:(s.measurementScope==="market"||s.measurementScope==="property")&&s.measurementScopeKey?{kind:s.measurementScope,key:s.measurementScopeKey,label:s.measurementScopeKey,planRevision:y??0,expectedPlanRevision:y??0}:null})(),scopePending:d.isPending||d.isFetching,scopeError:d.isError,onRetryScope:()=>{d.refetch()},templates:p};return i?e.jsxs("div",{children:[e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(mr,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(mr,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(Lf,{projectName:t,onReviewDiscoveryProbe:h=>r({source:"discovery",discoveryProbeId:h})}):e.jsx(el,{...x,onReviewForTracking:({researchRunQueryId:h,scope:y})=>r({source:"research",researchRunQueryId:h},y??null)})})]}):e.jsx(el,{...x,viewerResearchConfig:l})}function pf({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:c,preview:d,isPreviewing:m,isCommitting:u,onPreview:p,onCommit:x}){const[h,y]=o.useState(null),[f,b]=o.useState(()=>nr(s)),[j,A]=o.useState(null),P=o.useRef(null),C=o.useRef(null),g=uc(t,s),v=o.useMemo(()=>yf(t.tracked,s,t.mode),[s,t.mode,t.tracked]),S=Nn({rows:v,getSearchText:B=>`${B.queryText} ${B.provenance?.source??"legacy"} ${B.assignments.map(te=>te.queryClass??"unknown").join(" ")}`});o.useEffect(()=>{if(g)return;if(!a){C.current=null;return}const B=`${a}:${_r(s)}`;if(C.current===B)return;const te=t.tracked.find(O=>O.queryId===a);te&&(C.current=B,y({kind:"edit",row:te,audience:t.mode==="advanced"?Kr(s):void 0,scopeLabel:Gr(s,t)}),b(tl(te,s)),A(null))},[s,a,g,t]),o.useEffect(()=>{if(g||!l)return;const B=nr(l.trackingSelection??s);y({kind:"add"}),b(l.source==="research"?{...B,source:"research",researchRunQueryId:l.researchRunQueryId}:{...B,source:"discovery",discoveryProbeId:l.discoveryProbeId}),A(null),i()},[i,l,s,g]),o.useEffect(()=>{g&&(y(null),A(null),a!==void 0&&r?.(void 0))},[r,a,g]),o.useEffect(()=>{if(!h||h.kind==="remove")return;const B=P.current;B&&(B.scrollIntoView?.({block:"start"}),B.focus({preventScroll:!0}))},[h]);function L(B="manual"){y({kind:"add"}),b({...nr(s),source:B}),A(null),r?.(void 0)}function M(B){C.current=`${B.queryId}:${_r(s)}`,y({kind:"edit",row:B,audience:t.mode==="advanced"?Kr(s):void 0,scopeLabel:Gr(s,t)}),b(tl(B,s)),A(null),r?.(B.queryId)}function w(B){C.current=`${B.queryId}:${_r(s)}`,y({kind:"remove",row:B,audience:t.mode==="advanced"?Kr(s):void 0,scopeLabel:Gr(s,t)}),A(null),r?.(B.queryId)}function U(){y(null),A(null),r?.(void 0)}const F=h?xf(h,f,t.mode):null,z=h!==null&&h.kind==="add"&&t.mode==="advanced"&&!Ki(f),_=F!==null&&(!z||f.contexts.length>0)&&!m;return g?e.jsx("div",{className:"query-tracking-workspace space-y-4",children:e.jsxs("section",{"aria-label":"Tracked queries",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["This saved ",s.measurementScope," filter is unavailable in the current measurement."]}),e.jsx(T,{type:"button",variant:"outline",className:"mt-3",onClick:()=>n?.({measurementScope:"project",measurementScopeKey:void 0}),children:"Show whole site"})]})}):e.jsxs("div",{className:"query-tracking-workspace space-y-4",children:[e.jsxs("section",{"aria-label":"Tracked queries",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[t.mode==="advanced"?e.jsx(bf,{selection:s,onSelectionChange:n}):null,e.jsx(Zs,{value:S.query,onChange:S.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!ie()&&e.jsxs(We,{type:"button",size:"sm",onClick:()=>L(),children:[e.jsx(Zh,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[S.totalRows.toLocaleString("en-US")," saved query ",S.totalRows===1?"record":"records"," in this view. Each record can have more than one property, group, or market assignment."]}),s.measurementScope==="group"?e.jsx("p",{className:"mt-1 text-xs leading-5 text-secondary",children:"Queries belong to properties, so a shared query can also cover other groups."}):null,t.active?null:e.jsx("p",{className:"mt-3 text-sm text-caution",children:"No published measurement yet."}),S.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:S.hasQuery?"No tracked queries match that search.":"No tracked queries in this scope yet."}):e.jsx("div",{className:"mt-5 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table min-w-[760px] table-auto",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Scope"}),t.mode==="advanced"?e.jsx("th",{children:"Class"}):null,e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Measurement"}),e.jsx("th",{className:"measurement-table-actions",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:S.rows.map(B=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:B.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(jf,{row:B,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(wf,{row:B})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:vf(B)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Sf,{row:B,outsidePlan:t.mode==="advanced"&&B.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!ie()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(We,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${B.queryText}`,onClick:()=>M(B),children:[e.jsx(ep,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(We,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${B.queryText}`,onClick:()=>w(B),children:[e.jsx(lc,{"aria-hidden":"true",size:13})," Remove"]})]})})]},B.queryId))})]})}),e.jsx(Ks,{page:S.page,pageSize:S.pageSize,visibleRows:S.rows.length,totalRows:S.totalRows,itemLabel:"queries",onPageChange:S.setPage})]}),h&&!ie()&&e.jsx(Cf,{workspace:t,templates:c,action:h,draft:f,onDraftChange:B=>{b(B),A(null)},onClose:U,canReview:_,isPreviewing:m,editorHeadingRef:P,onReview:()=>{F&&(A(F),p(F))}}),d&&j&&h&&e.jsx(Pf,{preview:d,workspace:t,isCommitting:u,onConfirm:()=>{x({...j,expectedWorkspaceVersion:d.workspaceVersion,previewToken:d.previewToken,reviewedAt:d.reviewedAt})}})]})}function nr(t){return{source:"manual",text:"",templateId:"",templateVersion:"",template:"",researchRunQueryId:"",discoveryProbeId:"",wholeSite:t.measurementScope==="project"||!t.measurementScopeKey,targetKeys:t.measurementScope==="property"&&t.measurementScopeKey?[t.measurementScopeKey]:[],groupKeys:t.measurementScope==="group"&&t.measurementScopeKey?[t.measurementScopeKey]:[],marketKeys:t.measurementScope==="market"&&t.measurementScopeKey?[t.measurementScopeKey]:[],contexts:[],queryClass:"auto"}}function tl(t,s){return{...nr(s),text:t.queryText,queryClass:"keep"}}function xf(t,s,n){if(t.kind==="remove")return{additions:[],removals:[{queryId:t.row.queryId,...t.audience?{audience:t.audience}:{}}]};if(t.kind==="edit")return s.text.trim()?{additions:[],removals:[],edits:[{queryId:t.row.queryId,text:s.text.trim(),...t.audience?{audience:t.audience}:{},...n==="advanced"&&s.queryClass!=="keep"?{queryClass:s.queryClass==="auto"?null:s.queryClass}:{}}]}:null;const a=gf(s);if(!a||bi(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=ff(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!Ki(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function gf(t){return t.source==="manual"?t.text.trim()?{source:"manual",text:t.text.trim()}:null:t.source==="template"?t.templateId&&t.templateVersion&&t.template?{source:"template",templateId:t.templateId,templateVersion:t.templateVersion,template:t.template}:null:t.source==="research"?t.researchRunQueryId?{source:"research",researchRunQueryId:t.researchRunQueryId}:null:t.discoveryProbeId?{source:"discovery",discoveryProbeId:t.discoveryProbeId}:null}function ff(t){if(t.wholeSite)return;const s={...t.targetKeys.length>0?{targetKeys:t.targetKeys}:{},...t.groupKeys.length>0?{groupKeys:t.groupKeys}:{},...t.marketKeys.length>0?{marketKeys:t.marketKeys}:{}};return Object.keys(s).length>0?s:void 0}function Ki(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function bi(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function Kr(t){if(t.measurementScopeKey){if(t.measurementScope==="property")return{targetKeys:[t.measurementScopeKey]};if(t.measurementScope==="group")return{groupKeys:[t.measurementScopeKey]};if(t.measurementScope==="market")return{marketKeys:[t.measurementScopeKey]}}}function Gr(t,s){const a=(t.measurementScope==="property"?s.targets:t.measurementScope==="group"?s.groups:t.measurementScope==="market"?s.markets:[]).find(r=>r.stableKey===t.measurementScopeKey)?.label;return a?t.measurementScope==="group"?`${a} · Group`:t.measurementScope==="market"?`${a} · Market`:a:"Whole site"}function Gi(t,s){return s.queryClass!=="all"&&(t.queryClass??"unknown")!==s.queryClass?!1:s.measurementScope==="project"||!s.measurementScopeKey?!0:s.measurementScope==="property"?t.targetKey===s.measurementScopeKey:s.measurementScope==="group"?t.groupKeys.includes(s.measurementScopeKey):t.marketKeys.includes(s.measurementScopeKey)}function yf(t,s,n){return n==="simple"?[...t]:t.filter(a=>a.assignments.length===0?s.measurementScope==="project"&&(s.queryClass==="all"||s.queryClass==="unknown"):a.assignments.some(r=>Gi(r,s)))}function bf({selection:t,onSelectionChange:s}){return e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-xs font-medium text-secondary",children:"Query type"}),e.jsxs("select",{"aria-label":"Query type",className:"h-11 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:t.queryClass,onChange:n=>s?.({queryClass:n.target.value}),children:[e.jsx("option",{value:"all",children:"All query types"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"unknown",children:"Unclassified"})]})]})}function _r(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function vf(t){switch(t.provenance?.source){case"manual":return"Manual";case"template":return"Template";case"research":return"Saved research";case"discovery":return"Discovery";default:return"Legacy"}}function Gc(t,s,n){const a=new Map(s.targets.map(f=>[f.stableKey,f.label])),r=new Map(s.groups.map(f=>[f.stableKey,f.label])),l=new Map(s.markets.map(f=>[f.stableKey,f.label])),i=new Set(t.assignments.map(f=>f.targetKey));if(i.size===0)return"Whole site";const c=n?t.assignments.filter(f=>Gi(f,n)):t.assignments,d=new Set(c.map(f=>f.targetKey));if(n?.measurementScope==="group"){const f=d.size,b=Math.max(0,i.size-f);return[`${f} ${f===1?"property":"properties"} in this group`,...b?[`Shared with ${b} other ${b===1?"property":"properties"}`]:[]].join(" · ")}const m=new Set,u=new Set;for(const f of c)f.groupKeys.forEach(b=>m.add(b)),f.marketKeys.forEach(b=>u.add(b));const x=n?.measurementScope==="property"&&i.has(n.measurementScopeKey??"")?i.size===1?["This property only"]:["This property",`Shared with ${i.size-1} other ${i.size===2?"property":"properties"}`]:d.size===1?[a.get([...d][0])??[...d][0]]:[`${d.size} properties`],h=m.size===1?r.get([...m][0])??[...m][0]:null,y=u.size===1?l.get([...u][0])??[...u][0]:null;return h&&y&&h===y?x.push(`${h} (group and market)`):(h?x.push(`Group: ${h}`):m.size>1&&x.push(`${m.size} groups`),y?x.push(`Market: ${y}`):u.size>1&&x.push(`${u.size} markets`)),x.join(" · ")}function jf({row:t,workspace:s,selection:n}){const a=Nf(t,s,n);return e.jsxs("details",{className:"group min-w-48",children:[e.jsx("summary",{className:"cursor-pointer rounded px-1 py-1 text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:Gc(t,s,n)}),e.jsxs("div",{className:"mt-2 rounded border border-default bg-surface p-2 text-xs leading-5 text-secondary",children:[e.jsx("p",{className:"font-medium text-strong",children:"Assigned relationships"}),e.jsx("ul",{className:"mt-1 list-disc space-y-1 pl-4",children:a.map(r=>e.jsx("li",{children:r},r))})]})]})}function Nf(t,s,n){const a=new Map(s.targets.map(d=>[d.stableKey,d.label])),r=new Map(s.groups.map(d=>[d.stableKey,d.label])),l=new Map(s.markets.map(d=>[d.stableKey,d.label])),c=t.assignments.filter(d=>Gi(d,n)).map(d=>{const m=a.get(d.targetKey)??d.targetKey??"Whole site",u=n.measurementScope==="group"&&n.measurementScopeKey?d.groupKeys.filter(x=>x===n.measurementScopeKey).map(x=>r.get(x)??x):d.groupKeys.map(x=>r.get(x)??x),p=n.measurementScope==="market"&&n.measurementScopeKey?d.marketKeys.filter(x=>x===n.measurementScopeKey).map(x=>l.get(x)??x):d.marketKeys.map(x=>l.get(x)??x);return[m,u.length?`Groups: ${u.join(", ")}`:null,p.length?`Markets: ${p.join(", ")}`:null].filter(x=>x!==null).join(" · ")});return[...new Set(c)].length?[...new Set(c)]:["Whole site"]}function wf({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(je,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function Sf({row:t,outsidePlan:s=!1}){return s?e.jsx(je,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(je,{tone:"positive",children:"Measured"}):e.jsx(je,{tone:"caution",children:"Awaiting sweep"})}function Cf({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:l,canReview:i,isPreviewing:c,editorHeadingRef:d,onReview:m}){const u=s.length>0;return n.kind==="remove"?e.jsxs(ve,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Remove query"}),e.jsxs("p",{className:"mt-1 text-sm leading-6 text-secondary",children:["Remove “",n.row.queryText,"” from future tracking?"]}),e.jsxs("p",{className:"mt-1 text-sm leading-5 text-secondary",children:[n.audience?`Only assignments in ${n.scopeLabel} will be removed.`:"All assignments will be removed."," Earlier results stay unchanged."]})]})}),e.jsx(Ur,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]}):n.kind==="edit"?e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Edit query"}),e.jsx(T,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("p",{className:"mt-3 text-sm leading-6 text-secondary",children:[n.audience?`Changes apply only to assignments in ${n.scopeLabel}.`:"Changes apply to every assignment of this query."," Earlier results stay unchanged."]}),e.jsxs("div",{className:"mt-4 max-w-2xl space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Query text"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.text,onChange:p=>r({...a,text:p.target.value})})]}),t.mode==="advanced"&&e.jsxs("label",{className:"block",htmlFor:"tracking-query-class",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:p=>r({...a,queryClass:p.target.value}),children:[e.jsx("option",{value:"keep",children:"Keep existing classifications"}),e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Existing locations and engines are preserved. Use Add query to create assignments in another scope."})]}),e.jsx(Ur,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]}):e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Add query"}),e.jsx(T,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-[minmax(250px,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[a.source==="manual"?e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Question"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",placeholder:"e.g. How do teams compare AEO platforms?",value:a.text,onChange:p=>r({...a,text:p.target.value})})]}):null,a.source==="template"?e.jsx(kf,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(sl,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(p=>({id:p.researchRunQueryId,label:p.queryText,detail:p.researchRunId})),onChange:p=>r({...a,researchRunQueryId:p})}):null,a.source==="discovery"?e.jsx(sl,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(p=>({id:p.discoveryProbeId,label:p.queryText,detail:p.discoverySessionId})),onChange:p=>r({...a,discoveryProbeId:p})}):null,e.jsxs("label",{className:"block",htmlFor:"tracking-query-source",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Query source"}),e.jsxs("select",{id:"tracking-query-source","aria-describedby":u?void 0:"tracking-query-source-no-templates",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.source,onChange:p=>r({...a,source:p.target.value}),children:[e.jsx("option",{value:"manual",children:"Write a question"}),u?e.jsx("option",{value:"template",children:"Saved template"}):null,e.jsxs("option",{value:"research",disabled:t.savedSources.research.length===0,children:["Saved research",t.savedSources.research.length===0?" (none available)":""]}),e.jsxs("option",{value:"discovery",disabled:t.savedSources.discovery.length===0,children:["Discovery result",t.savedSources.discovery.length===0?" (none available)":""]})]})]}),u?null:e.jsx("p",{id:"tracking-query-source-no-templates",className:"text-sm leading-6 text-secondary",children:"No saved templates are set up for this portfolio. Write a question, or use saved research or a discovery result."})]}),e.jsx(Rf,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!Ki(a)?e.jsx("div",{className:"mt-4",children:e.jsx(Af,{workspace:t,draft:a,onDraftChange:r})}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Measurement options"}),e.jsx("div",{className:"grid gap-4 pb-3 sm:grid-cols-2",children:t.mode==="advanced"?e.jsxs("div",{className:"block",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",htmlFor:"tracking-query-class",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:p=>r({...a,queryClass:p.target.value}),children:[e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}):e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:"Automatic"})]})})]}),a.source==="research"&&e.jsx("p",{className:"mt-4 rounded-md border border-default bg-surface-subtle px-3 py-2 text-sm text-secondary",children:"Only the saved query is added."}),e.jsx(Ur,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]})}function kf({templates:t,draft:s,onDraftChange:n}){return e.jsxs("div",{children:[e.jsxs("label",{className:"block",htmlFor:"tracking-template-source",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Saved template"}),e.jsxs("select",{id:"tracking-template-source","aria-describedby":bi(s)?"tracking-template-market-required":void 0,className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:s.templateId,onChange:a=>{const r=t.find(l=>l.id===a.target.value);n({...s,templateId:r?.id??"",templateVersion:r?.updatedAt??"",template:r?.pattern??""})},children:[e.jsx("option",{value:"",children:"Choose a template"}),t.map(a=>e.jsx("option",{value:a.id,children:a.name},a.id))]}),s.template?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-muted",children:s.template}):null]}),bi(s)?e.jsx("p",{id:"tracking-template-market-required",role:"status",className:"mt-2 text-sm leading-5 text-caution",children:"Choose a Market under Apply to for this template. A location alone does not select a market."}):null]})}function sl({id:t,label:s,value:n,options:a,onChange:r}){return e.jsxs("label",{className:"block",htmlFor:t,children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:s}),e.jsxs("select",{id:t,className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:n,onChange:l=>r(l.target.value),children:[e.jsx("option",{value:"",children:"Choose a saved query"}),a.map(l=>e.jsxs("option",{value:l.id,children:[l.label," · ",l.detail]},l.id))]})]})}function _i(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function ca(t){return JSON.stringify({providers:[...t.providers].sort(),models:Object.fromEntries(Object.entries(t.models).sort(([s],[n])=>s.localeCompare(n))),location:t.location})}function _c(t){return[...new Map(t.map(s=>[ca(s),s])).values()]}function Ui(t){const s=t.providers.map(n=>{const a=t.models[n];return a?`${n} (${a})`:n}).join(", ");return`${t.location??"No location"} · ${s}`}function Af({workspace:t,draft:s,onDraftChange:n}){const a=o.useMemo(()=>_c([...t.defaultContexts.map(_i),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?ca(s.contexts[0]):s.contexts.length>1?"__existing__":"";return e.jsxs("label",{className:"block",htmlFor:"tracking-query-context",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location and engines"}),e.jsxs("select",{id:"tracking-query-context","aria-label":"Location and engines",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:r,onChange:l=>{const i=a.find(d=>ca(d)===l.target.value),c=l.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:c})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(l=>e.jsx("option",{value:ca(l),children:Ui(l)},ca(l)))]}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-secondary",children:a.length===0?"No configured measurement context is available.":"Choose where this query will be measured."})]})}function Rf({workspace:t,draft:s,onDraftChange:n}){const[a,r]=o.useState(""),[l,i]=o.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),c=o.useMemo(()=>[...t.targets.map(h=>({kind:"target",key:h.stableKey,label:h.label,detail:"Property"})),...t.groups.map(h=>({kind:"group",key:h.stableKey,label:h.label,detail:"Group"})),...t.markets.map(h=>({kind:"market",key:h.stableKey,label:h.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),d=a.trim().toLocaleLowerCase(),m=d?c.filter(h=>`${h.label} ${h.detail}`.toLocaleLowerCase().includes(d)):c,u=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function p(h,y,f){const b=h==="target"?"targetKeys":h==="group"?"groupKeys":"marketKeys",j=s[b];n({...s,wholeSite:!1,[b]:f?[...j,y]:j.filter(A=>A!==y)})}function x(h,y){return(h==="target"?s.targetKeys:h==="group"?s.groupKeys:s.marketKeys).includes(y)}if(!l){const h=t.targets.find(y=>y.stableKey===s.targetKeys[0]);return e.jsxs("fieldset",{className:"self-start rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-sm text-strong",children:["Property: ",h?.label??s.targetKeys[0]]}),e.jsx(T,{type:"button",variant:"ghost",size:"sm","aria-label":"Change tracking destination",onClick:()=>i(!0),children:"Change"})]})]})}return e.jsxs("fieldset",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Choose where this question should be tracked."}),e.jsxs("label",{className:"mt-3 flex min-h-9 items-center gap-2 rounded px-1 text-sm text-strong",children:[e.jsx("input",{type:"checkbox",checked:s.wholeSite,onChange:h=>{n({...s,wholeSite:h.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),"Whole site"]}),!s.wholeSite&&!u?e.jsx("p",{role:"status",className:"mt-2 text-sm text-caution",children:"Choose Whole site or at least one property, group, or market."}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:"Group: properties grouped together. Market: search context."}),e.jsx(Zs,{value:a,onChange:r,label:"Filter assignments",placeholder:"Search Properties, Groups, Markets",className:"mt-3"}),e.jsx("div",{className:"mt-3 max-h-64 space-y-1 overflow-y-auto pr-1",children:m.length===0?e.jsx("p",{className:"px-1 py-2 text-sm text-muted",children:"No assignment matches that search."}):m.map(h=>e.jsxs("label",{className:"flex min-h-9 items-center gap-2 rounded px-1 py-1 text-sm text-strong hover:bg-surface-hover",children:[e.jsx("input",{type:"checkbox","aria-label":`${h.label}, ${h.detail}`,checked:x(h.kind,h.key),onChange:y=>p(h.kind,h.key,y.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:h.label}),e.jsx("span",{className:"text-xs text-muted",children:h.detail})]},`${h.kind}:${h.key}`))})]})}function Ur({canReview:t,isPreviewing:s,onCancel:n,onReview:a}){return e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[e.jsx(We,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(T,{type:"button",variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),e.jsx("p",{className:"text-sm leading-5 text-secondary",children:"Publishing does not run a sweep."})]})}function Pf({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=o.useRef(null);o.useEffect(()=>{const c=r.current;c&&(typeof c.scrollIntoView=="function"&&c.scrollIntoView({block:"start"}),c.focus({preventScroll:!0}))},[t]);const l=!t.diff.noOp,i=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(c=>c.rows.length>0);return e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{ref:r,tabIndex:-1,children:l?"Confirm tracked query changes":"No tracking changes"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:l?"Changes apply to future sweeps. Earlier results stay unchanged.":"This request leaves tracking unchanged."})]}),e.jsx(je,{tone:l?"caution":"neutral",children:l?"Ready to confirm":"No-op"})]}),i.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:i.map(c=>e.jsx(nl,{label:c.label,rows:c.rows,workspace:s,tracked:t.tracked},c.label))}):null,t.diff.unchanged.length>0?e.jsxs("details",{className:"mt-4 border-t border-default pt-2 text-sm text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3",children:[t.diff.unchanged.length," unchanged ",t.diff.unchanged.length===1?"query":"queries"]}),e.jsx(nl,{label:"Unchanged",rows:t.diff.unchanged,workspace:s,tracked:t.tracked})]}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Next sweep workload"}),e.jsxs("p",{className:"leading-6",children:["Next sweep: ",t.workload.nextSweepProviderCalls," provider requests (+",t.workload.addedProviderCalls,", −",t.workload.removedProviderCalls,")."]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:e.jsx(We,{type:"button",size:"sm",disabled:!l||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function nl({label:t,rows:s,workspace:n,tracked:a}){return e.jsxs("section",{"aria-label":`${t} queries`,children:[e.jsxs("p",{className:"text-xs font-medium text-secondary",children:[s.length," ",t.toLocaleLowerCase(),s.length===1?"":"s"]}),e.jsx("ul",{className:"mt-2 divide-y divide-default",children:s.map(r=>e.jsxs("li",{className:"py-2 text-sm",children:[e.jsx("p",{className:"font-medium text-strong",children:r.queryText}),e.jsx("p",{className:"mt-1 text-secondary",children:t==="Removed"?`${r.assignmentCount} ${r.assignmentCount===1?"assignment":"assignments"} removed`:Tf(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(If,{row:a.find(l=>l.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function If({row:t,workspace:s}){if(!t?.assignments.length)return null;const n=new Set(t.assignments.map(a=>a.targetKey)).size;return e.jsxs("details",{className:"mt-2 text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:["Classifications · ",n," ",n===1?"property":"properties"]}),e.jsx("ul",{className:"mt-1 max-h-40 space-y-1 overflow-y-auto",children:t.assignments.map((a,r)=>{const l=s.targets.find(d=>d.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",c=a.contexts.map(d=>Ui(_i(d))).join("; ");return e.jsx("li",{children:[l,i,c].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function Tf(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=_c(a.assignments.flatMap(i=>i.contexts).map(_i)),l=r.length===1?Ui(r[0]):r.length>1?`${r.length} contexts`:null;return[Gc(a,n),l].filter(i=>i!==null).join(" · ")}function Mf({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i}){const c=ms(),[d,m]=o.useState(null),u=qe({...Ii({client:Y,path:{name:t}})}),p=qe({...Wl({client:Y,path:{name:t}}),staleTime:6e4}),x=Ot({...yu(),onSuccess:y=>m(y),onError:async y=>{m(null),await c.invalidateQueries({queryKey:fu({client:Y,path:{name:t}})}),Fe({title:"Could not review tracking changes",detail:y instanceof Error?y.message:"Update the draft and review it again.",tone:"negative"})}}),h=Ot({...bu(),onSuccess:async y=>{m(null),r?.(void 0),await ro(c,t),Fe({title:y.committed?"Tracked queries updated":"No tracked-query change",detail:y.active?`Measurement revision ${y.active.revision}.`:"No measurement revision is published yet.",tone:y.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async y=>{m(null),await ro(c,t),Fe({title:"Could not confirm tracking changes",detail:y instanceof Error?y.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return u.isLoading?e.jsx(ve,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):u.isError||!u.data?e.jsxs(ve,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(T,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{u.refetch()},children:"Try again"})]}):e.jsx(pf,{workspace:u.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:p.data?.templates??[],preview:d,isPreviewing:x.isPending,isCommitting:h.isPending,onPreview:y=>{m(null),x.mutate({client:Y,path:{name:t},body:{...y,expectedWorkspaceVersion:u.data.workspaceVersion}})},onCommit:y=>h.mutate({client:Y,path:{name:t},body:y})})}function Lf({projectName:t,onReviewDiscoveryProbe:s}){const n=ms(),[a,r]=o.useState(null),[l,i]=o.useState(""),[c,d]=o.useState("100"),m=qe({...vu({client:Y,path:{name:t},query:{limit:"10"}}),refetchInterval:A=>A.state.data?.some(C=>yi.has(C.status))?3e3:!1}),u=m.data??[];o.useEffect(()=>{!a&&u[0]&&r(u[0].id)},[a,u]);const p=u.find(A=>A.id===a)??null,x=qe({...ju({client:Y,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:p&&yi.has(p.status)?3e3:!1}),h=x.data??null,y=Ot({mutationFn:()=>{const A={},P=l.trim();P&&(A.icpDescription=P);const C=Number.parseInt(c,10);return Number.isFinite(C)&&C>0&&(A.maxProbes=C),Nu(t,A)},onSuccess:async A=>{r(A.sessionId),i(""),await Df(n,t,A.sessionId),Fe({title:"Discovery started",detail:`Run ${Br(A.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${A.sessionId}`,dedupeMode:"replace"})},onError:A=>{Fe({title:"Discovery failed to start",detail:A instanceof Error?A.message:"Could not start discovery.",tone:"negative"})}}),f=h??p,b=o.useMemo(()=>(h?.probes??[]).slice(0,30),[h?.probes]);async function j(){try{const A=await m.refetch();if(A.error)throw A.error;const P=A.data?.length??0;Fe({title:"Discovery sessions refreshed",detail:`${P} recent session${P===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(A){Fe({title:"Discovery refresh failed",detail:A instanceof Error?A.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:ie()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(T,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{j()},children:[e.jsx(ya,{className:`size-3.5 ${m.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(je,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:l,onChange:A=>i(A.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:c,onChange:A=>d(A.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!ie()&&e.jsxs(We,{type:"button",size:"sm",disabled:y.isPending,onClick:()=>y.mutate(),children:[e.jsx(ir,{size:14}),y.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),m.isFetching&&e.jsx(je,{tone:"neutral",children:"Loading"})]}),u.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:u.map(A=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===A.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(A.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:Br(A.id)}),e.jsx(je,{tone:al(A.status),children:A.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",A.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",A.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",A.wastedCount??0]})]})]},A.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:f?Br(f.id):"No run selected"})]}),f&&e.jsx(je,{tone:al(f.status),children:f.status})]}),f?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ua,{label:"Questions tested",value:f.probeCount??0}),e.jsx(Ua,{label:"Cited queries",value:f.citedCount??0,tone:"positive"}),e.jsx(Ua,{label:"Worth tracking",value:f.aspirationalCount??0,tone:"caution"}),e.jsx(Ua,{label:"Skip",value:f.wastedCount??0,tone:"negative"})]}),f.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:f.error}),f.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:f.warning}),f.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:f.icpDescription})]}),f.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:f.competitorMap.slice(0,8).map(A=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[A.domain," ",e.jsx("span",{className:"text-muted",children:A.hits})]},A.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),f?.status==="completed"&&e.jsxs(ve,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Review a discovery question for tracking"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:"Choose a Cited query or Worth tracking result below. Tracking opens with the saved discovery source, where you choose its scope and review the exact next-sweep change."})]})}),e.jsx("p",{className:"mt-3 text-xs leading-5 text-muted",children:"Discovery remains research. This review does not add competitors or start a sweep."})]}),e.jsxs(ve,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),x.isFetching&&e.jsx(je,{tone:"neutral",children:"Loading"})]}),b.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Tracking review"})})]})}),e.jsx("tbody",{children:b.map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:A.query}),e.jsx("td",{children:e.jsx(je,{tone:$f(A.bucket),children:Ef(A.bucket)})}),e.jsx("td",{className:"text-secondary",children:A.citedDomains.length>0?A.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!ie()&&s&&(A.bucket==="cited"||A.bucket==="aspirational")&&e.jsx(We,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(A.id),children:"Review for tracking"})})]},A.id))})]})})]})]})]})]})}function Ua({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 al(t){return t==="completed"?"positive":t==="failed"?"negative":yi.has(t)?"caution":"neutral"}function $f(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const qf={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Ef(t){return t?qf[t]:"Not classified"}function Br(t){return t.length>8?t.slice(0,8):t}async function Df(t,s,n){await Promise.all([Tt(t,"discovery"),t.invalidateQueries({queryKey:wu({client:Y})})])}function Of({projectName:t}){const[s,n]=o.useState("changes"),[a,r]=o.useState(null),[l,i]=o.useState(null),c=qe({...Su({client:Y,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=qe({...Cu({client:Y,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),m=(d.data??[]).filter(b=>(b.status==="completed"||b.status==="partial")&&b.trigger!=="probe").reverse(),u=l??m[0]?.id??"",p=a??m.find(b=>b.id!==u)?.id??"",x=!!(p&&u&&p!==u),h=qe({...ku({client:Y,path:{name:t},query:{run1:p,run2:u}}),enabled:s==="compare"&&x}),y=c.data??[],f=h.data?.diff.filter(b=>b.changed||b.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([b,j])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===b,className:`filter-chip ${s===b?"filter-chip-active":""}`,onClick:()=>n(b),children:j},b))}),s==="changes"?e.jsx(op,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),c.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!c.isLoading&&y.length===0?e.jsxs(ve,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:cs()?Vn:"Complete an answer visibility sweep to create the first snapshot."})]}):null,y.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:y.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(b.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.mentionedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:tt(b.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.citedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:tt(b.overallCitedRate)})]},b.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:p,onChange:b=>r(b.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:m.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:u,onChange:b=>i(b.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:m.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]})]}),d.isLoading||h.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!d.isLoading&&m.length<2?e.jsxs(ve,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:cs()?Vn:"Run another answer visibility sweep before comparing historical evidence."})]}):null,h.data&&f.length===0?e.jsxs(ve,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,f.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:f.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:b.query??"Archived query"}),e.jsx("td",{children:e.jsxs(je,{tone:b.changed?"caution":"neutral",children:[b.run1State??"none"," → ",b.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(je,{tone:b.visibilityChanged?"caution":"neutral",children:[b.run1MentionState??"none"," → ",b.run2MentionState??"none"]})})]},b.queryId??b.query??"unknown"))})]})}):null]}):null]})}const rl={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},Ff={contract:null,assessment:null,googleAds:rl,gtm:rl,snapshots:[]};function Kf(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Bf(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Gf(t){switch(t){case"configured":return{label:"Configured",detail:"The conversion is declared, but the static configuration is not yet proven consistent.",tone:"caution"};case"static-mismatch":return{label:"Static mismatch",detail:"Stored configuration does not match the declared conversion. Review the failing checks before relying on it.",tone:"negative"};case"statically-consistent":return{label:"Statically consistent",detail:"Stored Google Ads and Tag Manager configuration aligns with the declared conversion.",tone:"positive"};case"runtime-unverified":return{label:"Runtime verification needed",detail:"The stored configuration aligns, but a real browser event has not been observed.",tone:"caution"};case"observed":return{label:"Observed",detail:"Stored static evidence and a runtime observation support this conversion path.",tone:"positive"};case"not-configured":return{label:"Setup needed",detail:"Connect both providers, select their resources, then declare the conversion Canonry should inspect.",tone:"neutral"};case"contract-selection-required":return{label:"Choose conversion",detail:"Choose one of the declared conversions before Canonry evaluates its evidence.",tone:"neutral"};case"assessment-loading":return{label:"Checking configuration",detail:"Canonry is loading the selected conversion assessment.",tone:"neutral"};case"assessment-unavailable":return{label:"Assessment unavailable",detail:"The selected conversion could not be assessed. Retry before treating static evidence as current.",tone:"negative"}}}function _f(t){switch(t.googleAds.state){case"not-connected":return{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."};case"selection-required":return{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."};case"stale":return{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."};default:return null}}function Uf(t){switch(t.gtm.state){case"not-connected":return{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."};case"selection-required":return{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."};case"stale":return{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."};default:return null}}function Uc(t){return t.googleAds.state==="not-connected"?{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."}:t.googleAds.state==="unavailable"||t.gtm.state==="unavailable"?{id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."}:t.googleAds.state==="selection-required"?{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."}:t.googleAds.state==="stale"?{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."}:t.gtm.state==="not-connected"?{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."}:t.gtm.state==="selection-required"?{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."}:t.gtm.state==="stale"?{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."}:t.contractSelectionRequired?{id:"select-contract",label:"Select conversion",detail:"Choose the declared conversion Canonry should assess."}:t.contract?t.assessmentState==="loading"?{id:"waiting-for-integrity",label:"Checking configuration…",detail:"Canonry is loading the selected conversion assessment."}:t.assessmentState==="unavailable"?{id:"retry-integrity",label:"Retry assessment",detail:"Retry the selected conversion assessment before acting on its evidence."}:t.assessment?.status==="runtime-unverified"?{id:"review-runtime-verification",label:"Review runtime verification",detail:"Static configuration is aligned. Verify a real browser event separately."}:t.assessment?.status==="configured"&&Vf(t)?{id:"review-findings",label:"Review findings",detail:"Resolve the mismatched or unknown checks before treating this conversion as ready."}:{id:"sync-static-evidence",label:"Refresh static evidence",detail:"Queue fresh read-only Google Ads and Tag Manager observations."}:{id:"declare-contract",label:"Declare conversion",detail:"Name the website event, Google Ads action, and Tag Manager tag that must agree."}}function Bf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Vf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Bc(t){switch(t){case"connected":return{label:"Connected",tone:"positive"};case"stale":return{label:"Needs refresh",tone:"caution"};case"selection-required":return{label:"Selection needed",tone:"caution"};case"not-connected":return{label:"Not connected",tone:"neutral"};case"unavailable":return{label:"Unavailable",tone:"negative"}}}function Qf(t,s){return t==="configured"?s==="not-configured"||s==="contract-selection-required"?"neutral":"positive":t==="static"?s==="assessment-unavailable"?"negative":s==="assessment-loading"?"neutral":s==="static-mismatch"?"negative":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"positive":s==="configured"?"caution":"neutral":s==="observed"?"positive":s==="runtime-unverified"?"caution":"neutral"}function zf(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 pn(t){return t.length<=12?t:`…${t.slice(-10)}`}function Hf(t){const s=[];return t.googleAds.requirePrimaryAction&&s.push("primary action"),t.googleAds.requireBiddableGoal&&s.push("biddable goal"),s.length>0?s.join(" and "):"No bidding-goal assertion"}function Wf(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"No additional event fields required"}const Vr={"ads-connection-missing":"Google Ads connection is available","ads-conversion-action-missing":"Google Ads conversion action exists and is enabled","ads-goal-missing":"Google Ads goal includes the conversion action","ads-goal-not-biddable":"Google Ads goal is available for bidding","ads-action-not-primary":"Google Ads action is primary","gtm-connection-missing":"Tag Manager connection is available","gtm-live-graph-missing":"Tag Manager configuration is available","gtm-tag-missing":"Required Tag Manager tag exists","gtm-tag-unrecognized":"Tag Manager tag type is supported","gtm-tag-paused":"Tag Manager tag is active","gtm-trigger-missing":"Required Tag Manager trigger is linked","gtm-variable-missing":"Required Tag Manager variable is linked","gtm-event-mismatch":"Tag Manager event matches the declaration","gtm-hostname-mismatch":"Tag Manager host matches the production site","gtm-value-mapping-missing":"Conversion value mapping is present","gtm-transaction-id-mapping-missing":"Transaction ID mapping is present","gtm-currency-mapping-missing":"Currency mapping is present","gtm-conversion-id-mismatch":"Google conversion ID matches","gtm-conversion-label-mismatch":"Google conversion label matches","runtime-event-not-observed":"Website event was observed","runtime-gtm-not-observed":"Tag Manager firing was observed","runtime-ads-not-observed":"Google Ads conversion was observed"};function il(t){return t.outcome==="pass"?{label:Vr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Vr[t.code],tone:"negative",outcome:"Fail"}:{label:Vr[t.code],tone:"caution",outcome:"Unknown"}}function Yf(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Jf(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("conversion value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"no additional event fields"}function Xf(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function ol({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const l=Bc(s.state),i=s.snapshotState==="loading"?"Loading stored snapshots":s.snapshotState==="unavailable"?"Stored snapshots unavailable":s.snapshotCount===0?"No stored snapshots":null;return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:t}),e.jsx("td",{children:e.jsx(je,{tone:l.tone,children:l.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),i?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:i}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Ht(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const Zf="A conversion names the website event, the Google Ads conversion action, and the Tag Manager tag that must agree. It needs both connections selected because it references resources from each.",ey="Available once Google Ads and Tag Manager are connected.",ty="Check that a conversion is wired the same way in Google Ads and Tag Manager, so the numbers you optimise against are the ones your site actually sends. Canonry only reads the configuration; it never changes or publishes it.";function sy({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:l}){const i=t.googleAds.state==="connected",c=t.gtm.state==="connected",d=t.googleAds.state==="unavailable",m=t.gtm.state==="unavailable",u=d||m||t.gtm.state==="unavailable",p={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},x=!i&&!c,h=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:d?p:_f(t)},{title:"Tag Manager",state:t.gtm.state,ready:c,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:m?p:Uf(t)}],y=i&&c&&!u?Uc(t):null;return e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("h2",{id:"conversion-integrity-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx(Ge,{text:"Canonry reads your Google configuration and never changes or publishes it. Connect Google Ads and Tag Manager, then choose one website conversion to check across both."})]}),x?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:ty}):null]})}),e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-y border-default py-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Conversion to check"}),e.jsx(Ge,{text:Zf})]}),y&&s?e.jsx(We,{type:"button",disabled:r,onClick:()=>s(y.id),children:r?"Working…":y.label}):e.jsx("p",{className:"text-sm text-secondary",children:ey})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:h.map(f=>{const b=f.ready?{label:"Ready",tone:"positive"}:Bc(f.state),j=f.action;return e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-heading",children:f.title}),e.jsx(je,{tone:b.tone,children:b.label}),f.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:f.summary}):null,j&&s?j.id==="retry-connection-status"?e.jsx(T,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(j.id),children:r?"Working…":j.label}):e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(j.id),children:r?"Working…":j.label}):null,f.summary&&f.onChange?e.jsx(We,{type:"button",variant:"ghost",size:"sm","aria-label":f.changeLabel,disabled:r,onClick:f.onChange,children:"Change"}):null]},f.title)})}),l?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:l}):null]})]})}function ny({workspace:t=Ff,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:l=null,onSelectContract:i,contractError:c=null,onRetryContracts:d,onRetryEvidence:m,onChangeGoogleAdsSelection:u,onChangeGtmSelection:p,onAddContract:x}){const h=Kf(t),y=Gf(h),f=Uc(t),b=t.assessment?.findings??[],j=b.filter(g=>g.outcome!=="pass"),A=b.filter(g=>g.outcome==="pass"),P=j.some(g=>g.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&c===null?e.jsx(sy,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:u,onChangeGtmSelection:p,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(je,{tone:y.tone,children:y.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Ht(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:y.detail}),t.assessmentEvidenceSnapshots?.length?e.jsxs("details",{className:"inline-disclosure mt-3 max-w-2xl",children:[e.jsx("summary",{children:"Evidence used for this assessment"}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm leading-6 text-secondary",children:t.assessmentEvidenceSnapshots.map(g=>e.jsxs("li",{className:"break-words",children:[Xf(g)," ",g.kind,", captured ",Ht(g.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",g.id,")"]})]},g.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?f.id==="review-findings"||f.id==="review-runtime-verification"||f.id==="retry-connection-status"||f.id==="select-contract"||f.id==="retry-integrity"||f.id==="waiting-for-integrity"?e.jsx(T,{type:"button",disabled:n||f.id==="waiting-for-integrity",onClick:()=>s(f.id),children:n?"Working…":f.label}):e.jsx(We,{type:"button",disabled:n,onClick:()=>s(f.id),children:n?"Working…":f.label}):f.id==="review-findings"?e.jsx(T,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):h==="runtime-unverified"?e.jsx(T,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:f.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),r.length>0&&x?e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:x,children:"Add conversion"}):null]}),r.length>1?e.jsxs("label",{htmlFor:"conversion-integrity-contract-select",className:"mb-5 block max-w-xl text-sm font-medium text-secondary",children:["Conversion to inspect",e.jsxs("select",{id:"conversion-integrity-contract-select",className:"mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",value:l??"",onChange:g=>i?.(g.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]})]}):null,t.contract?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Website event"}),e.jsx("dd",{className:"mt-1 text-sm font-medium text-heading",children:t.contract.eventName})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Google Ads goal"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:Hf(t.contract)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Tag Manager"}),e.jsxs("dd",{className:"mt-1 text-sm text-secondary",children:[t.contract.gtm.triggerIds.length," ",t.contract.gtm.triggerIds.length===1?"trigger":"triggers"," and ",t.contract.gtm.variableIds.length," ",t.contract.gtm.variableIds.length===1?"variable":"variables"," required"]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Runtime event fields"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:Wf(t.contract)})]})]}),e.jsxs("details",{className:"inline-disclosure mt-5",children:[e.jsx("summary",{children:"Show declared identifiers"}),e.jsxs("dl",{className:"mt-3 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads customer"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:pn(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:pn(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:pn(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:pn(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),c?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:c}),d?e.jsx(T,{type:"button",variant:"outline",onClick:d,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),j.length>0?e.jsxs("section",{id:"conversion-integrity-findings",tabIndex:-1,className:"page-section-divider","aria-labelledby":"conversion-integrity-findings-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Assessment findings"}),e.jsx("h3",{id:"conversion-integrity-findings-title",className:"text-base font-semibold text-heading",children:"Checks to review"})]}),e.jsxs(je,{tone:P,children:[j.length," ",j.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:j.map(g=>{const v=il(g);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:v.label}),e.jsx(je,{tone:v.tone,children:v.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",g.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",g.code]}),g.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",g.evidenceIds.join(", ")]}):null]},`${g.code}:${g.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(Ge,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(g=>{const v=Qf(g.key,h);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${v==="positive"?"bg-positive-fill":v==="caution"?"bg-caution-fill":v==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:g.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:g.detail}),e.jsx(je,{tone:v,children:zf(g.key,h)})]},g.key)})})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-connections-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection evidence"}),e.jsx("h3",{id:"conversion-integrity-connections-title",className:"text-base font-semibold text-heading",children:"Google Ads and Tag Manager"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads and Tag Manager connection and stored evidence state"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Connection"}),e.jsx("th",{scope:"col",children:"Selection"}),e.jsx("th",{scope:"col",children:"Stored evidence"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsxs("tbody",{children:[ol({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:u}:{},actionPending:n}),ol({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:p}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&m?e.jsx(T,{type:"button",variant:"outline",className:"mt-3",onClick:m,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:g.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:g.kind}),e.jsx("td",{className:"text-secondary",children:Ht(g.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:pn(g.id)})]},g.id))})]})})]}):null,A.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[A.length," ",A.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:A.map(g=>{const v=il(g);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:v.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",g.code]}),g.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",g.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(je,{tone:v.tone,children:v.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:g.subject})]},`${g.code}:${g.subject}`)})})]})})]}):null,h==="runtime-unverified"?e.jsxs("section",{id:"conversion-integrity-runtime-guidance",className:"page-section-divider","aria-labelledby":"conversion-integrity-runtime-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Runtime verification"}),e.jsx("h3",{id:"conversion-integrity-runtime-title",className:"text-base font-semibold text-heading",children:"Runtime verification checklist"})]})}),e.jsxs("ol",{className:"max-w-2xl list-decimal space-y-2 pl-5 text-sm leading-6 text-secondary marker:text-muted",children:[e.jsxs("li",{children:["Use a controlled browser session on ",Yf(t.contract)," and complete the conversion that emits ",e.jsx("span",{className:"font-mono text-heading",children:t.contract.eventName}),"."]}),e.jsxs("li",{children:["In Tag Manager preview or debugging, confirm tag ",e.jsx("span",{className:"font-mono text-heading",children:pn(t.contract.gtm.tagId)})," fires with ",Jf(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:pn(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const xn=3e4,ll={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Kt="mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",os="text-sm font-medium text-secondary";function cl(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:Nt(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function Ba(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function ay(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Google Ads connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Google Ads OAuth connection is stored for this project.",lastSnapshotAt:null};if(t.status==="selection-required"){const r=t.connection.selection.customerId;return r?{state:"stale",selection:`Selected customer ${r}`,...s,evidence:"A customer is selected, but Canonry needs a fresh conversion-goal observation.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}:{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs a customer account selection.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}const a=t.selectedCustomer;return{state:t.status,selection:a.descriptiveName??`Selected customer ${a.customerId}`,...s,evidence:t.status==="stale"?"The selected customer needs a fresh conversion-goal observation.":"Selected customer and conversion-goal evidence are stored.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}function ry(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function iy(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Tag Manager connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Tag Manager OAuth connection is stored for this project.",lastSnapshotAt:null};const a=t.selection;return t.status==="selection-required"||!a.accountId||!a.containerId?{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs an account and container selection.",lastSnapshotAt:t.connection.lastSnapshotAt}:{state:t.status,selection:ry(a.containerId,a.accountId,a.workspaceId),...s,evidence:t.status==="stale"?"The selected container needs a fresh static configuration observation.":"Selected container configuration evidence is stored.",lastSnapshotAt:t.connection.lastSnapshotAt}}function oy(t,s,n){return{name:t.name.trim(),eventName:t.eventName.trim(),googleAds:{customerId:s,conversionActionId:t.conversionActionId.trim(),...t.conversionId.trim()?{conversionId:t.conversionId.trim()}:{},...t.conversionLabel.trim()?{conversionLabel:t.conversionLabel.trim()}:{},campaignIds:Ba(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:Ba(t.triggerIds),variableIds:Ba(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:Ba(t.productionHosts)}}}function dl(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 Va(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 Qa(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function za({id:t,label:s,value:n,onChange:a,children:r,disabled:l=!1}){return e.jsxs("label",{htmlFor:t,className:os,children:[s,e.jsx("select",{id:t,className:Kt,value:n,onChange:i=>a(i.target.value),disabled:l,children:r})]})}function $n({id:t,checked:s,onChange:n,children:a}){return e.jsxs("label",{htmlFor:t,className:"flex items-start gap-2 text-sm text-secondary",children:[e.jsx("input",{id:t,type:"checkbox",checked:s,onChange:r=>n(r.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function ul({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1),[c,d]=o.useState(null),m=o.useRef(null),u=o.useRef(null),p=o.useRef(!1);o.useEffect(()=>{const f=p.current;p.current=a,a?u.current?.focus():f&&m.current?.querySelector("button")?.focus()},[a]);function x(){d(null),r(!0)}function h(){d(null),r(!1)}async function y(){i(!0),d(null);try{await n()}catch(f){d(Nt(f)),i(!1)}}return e.jsx("div",{ref:m,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(T,{ref:u,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:l,onClick:h,children:"Keep connected"}),e.jsx(We,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||l,onClick:()=>{y()},children:l?"Disconnecting…":`Disconnect ${t}`})]}),c?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:c}):null]}):e.jsxs(We,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:x,children:["Disconnect ",t]})})}function ml({id:t,label:s,options:n,synced:a,loading:r,failed:l,onRetry:i,emptyHint:c,value:d,onChange:m}){const u=n.some(f=>f.id===d),[p,x]=o.useState(!1),h=p||d!==""&&!u&&n.length>0,y=e.jsx("label",{htmlFor:t,className:os,children:s});return r?e.jsxs("div",{children:[y,e.jsx("select",{id:t,className:Kt,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):l?e.jsxs("div",{children:[y,e.jsx("input",{id:t,required:!0,className:Kt,value:d,onChange:f=>m(f.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:i,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[y,e.jsx("input",{id:t,required:!0,className:Kt,value:d,onChange:f=>m(f.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":c})]}):e.jsxs("div",{children:[y,h?e.jsx("input",{id:t,required:!0,className:Kt,value:d,onChange:f=>m(f.target.value)}):e.jsxs("select",{id:t,required:!0,className:Kt,value:d,onChange:f=>m(f.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(f=>e.jsxs("option",{value:f.id,children:[f.name,f.detail?` (${f.detail})`:"",f.active?"":" — inactive"]},f.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{x(!h),m("")},children:h?"Choose from synced list":"Enter an ID manually"})]})}function ly({projectId:t,projectName:s}){const n=rn(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),[m,u]=o.useState(""),[p,x]=o.useState(null),[h,y]=o.useState(!1),[f,b]=o.useState(!1),[j,A]=o.useState(""),[P,C]=o.useState(""),[g,v]=o.useState(""),[S,L]=o.useState(""),[M,w]=o.useState(""),[U,F]=o.useState(!1),[z,_]=o.useState(ll),[B,te]=o.useState(null),O=o.useRef(null),V=qe({...Au({client:Y,path:{name:s}}),staleTime:xn}),Q=qe({...Ru({client:Y,path:{name:s}}),staleTime:xn}),E=qe({...Pu({client:Y,path:{name:s}}),staleTime:xn}),J=qe({...Iu({client:Y,path:{name:s}}),staleTime:xn}),k=J.data,H=qe({...Tu({client:Y,path:{name:s},query:{limit:5}}),staleTime:xn}),se=qe({...Mu({client:Y,path:{name:s},query:{limit:5}}),staleTime:xn}),ne=E.data??[],ke=(B?ne.find(q=>q.id===B)??null:null)??(ne.length===1?ne[0]??null:null),X=ne.length>1&&!ke,ue=qe({...Lu({client:Y,path:{name:s,contractId:ke?.id??""}}),enabled:!!ke,staleTime:xn}),fe=qe({...$u({client:Y,path:{name:s}}),enabled:p==="google-ads"&&V.data?.connected===!0,staleTime:0}),Z=qe({...qu({client:Y,path:{name:s}}),enabled:p==="gtm"&&Q.data?.connected===!0,staleTime:0}),ce=qe({...Eu({client:Y,path:{name:s,accountId:g}}),enabled:p==="gtm"&&!!g,staleTime:0}),G=qe({...Du({client:Y,path:{name:s,accountId:g,containerId:S}}),enabled:p==="gtm"&&!!g&&!!S,staleTime:0}),de=Ot(Ou({client:Y})),De=Ot(Fu({client:Y})),Re=Ot(Ku({client:Y})),re=Ot(Gu({client:Y})),me=Ot(_u({client:Y})),Ae=Ot(Uu({client:Y})),st=Ot(Bu({client:Y})),pe=Ot(Vu({client:Y})),D=Ot(Qu({client:Y}));o.useEffect(()=>{if(p!=="google-ads"||h||!V.isSuccess)return;const q=V.data.connection?.selection;A(q?.customerId??""),C(q?.loginCustomerId??""),y(!0)},[h,V.data,V.isSuccess,p]),o.useEffect(()=>{if(p!=="gtm"||f||!Q.isSuccess)return;const q=Q.data.selection;v(q?.accountId??""),L(q?.containerId??""),w(q?.workspaceId??""),b(!0)},[f,Q.data,Q.isSuccess,p]),o.useEffect(()=>{!B||!E.data||E.data.some(q=>q.id===B)||te(null)},[E.data,B]);const Oe=o.useMemo(()=>{const q=H.data?.snapshots??[],Se=se.data?.snapshots??[],rt=[...q.map(yt=>({id:yt.id,provider:"google-ads",kind:yt.kind,capturedAt:yt.capturedAt})),...Se.map(yt=>({id:yt.id,provider:"gtm",kind:yt.kind,capturedAt:yt.capturedAt}))].sort((yt,vs)=>vs.capturedAt.localeCompare(yt.capturedAt)).slice(0,5),Et=[],Zt=ue.data?.googleAdsSnapshot,Ue=ue.data?.gtmSnapshot;return Zt&&Et.push({id:Zt.id,provider:"google-ads",kind:Zt.kind,capturedAt:Zt.capturedAt}),Ue&&Et.push({id:Ue.id,provider:"gtm",kind:Ue.kind,capturedAt:Ue.capturedAt}),{contract:ue.data?.assessment.contract??ke,assessment:ue.data?.assessment??null,contractSelectionRequired:X,assessmentState:ke?ue.isError?"unavailable":ue.isLoading?"loading":void 0:void 0,assessmentError:ue.isError?Nt(ue.error):null,googleAds:ay(V.data,cl(H.data?.total??0,H.isLoading,H.isError,H.error),V.isError),gtm:iy(Q.data,cl(se.data?.total??0,se.isLoading,se.isError,se.error),Q.isError),snapshots:rt,assessmentEvidenceSnapshots:Et}},[ke,X,H.data,H.error,H.isError,H.isLoading,V.data,V.isError,se.data,se.error,se.isError,se.isLoading,Q.data,Q.isError,ue.data,ue.error,ue.isError,ue.isLoading]),I=o.useSyncExternalStore(Gl,ar,ar),ye=Object.values(I.runs).some(q=>q.projectId===t&&(q.kind===_s["google-ads-sync"]||q.kind===_s["gtm-sync"])),_e=de.isPending||De.isPending||Re.isPending||re.isPending||me.isPending||Ae.isPending||st.isPending||pe.isPending||D.isPending||ye;async function ze(){await Promise.all([V.refetch(),Q.refetch(),E.refetch(),H.refetch(),se.refetch(),J.refetch(),ke?ue.refetch():Promise.resolve()])}async function Be(q){await ze();for(let Se=0;Se<10&&!q();Se+=1)await new Promise(rt=>setTimeout(rt,1500)),await ze()}function be(){const q=document.activeElement;O.current=q instanceof HTMLElement?q:null}function xt(q){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(q);return}globalThis.setTimeout(q,0)}function Ke(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Xe(q){if(!q)return;!q.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!q.hasAttribute("tabindex")&&(q.tabIndex=-1),q.focus({preventScroll:!0})}function ts(q,Se=q){const rt=document.getElementById(q);rt instanceof HTMLDetailsElement&&(rt.open=!0);const Et=rt?.scrollIntoView;typeof Et=="function"&&Et.call(rt,{behavior:Ke()?"auto":"smooth",block:"start"}),Xe(document.getElementById(Se)??rt)}function it(q,Se){be(),xt(()=>ts(q,Se))}function nt(){const q=O.current;O.current=null,q&&xt(()=>{q.isConnected&&q.focus({preventScroll:!0})})}function ut(){r(null),d(!1),nt()}function wt(){r(null),x(null),nt()}function Mt(){r(null),F(!1),nt()}function Ve(){r(null),x(null),d(!0),it("google-ads-connect-panel","google-ads-connect-title")}function R(){r(null),A(""),C(""),y(!1),x("google-ads"),d(!1),it("google-ads-selection-panel","google-ads-selection-title")}function Me(){r(null),v(""),L(""),w(""),b(!1),x("gtm"),d(!1),it("gtm-selection-panel","gtm-selection-title")}function we(){r(null),F(!0),it("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Le(q,Se){Kl({id:q.id,projectId:q.projectId,kind:q.kind,projectLabel:s,sourceAction:Se}),Fe({title:Se==="google-ads-sync"?"Google Ads sync queued":"Tag Manager sync queued",detail:`${s} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`google-marketing-sync:${q.id}`,dedupeMode:"replace"})}async function At(){Ss(n),r(null);try{const q=await de.mutateAsync({path:{name:s},body:{provider:"google-ads",...m.trim()?{developerToken:m.trim()}:{}}});u(""),d(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),dl(q.authorizationUrl,()=>{ze(),i(null),nt()})}catch(q){r(Nt(q))}}async function It(){Ss(n),r(null);try{const q=await De.mutateAsync({path:{name:s},body:{provider:"gtm"}});i("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),dl(q.authorizationUrl,()=>{ze(),i(null),nt()})}catch(q){r(Nt(q))}}async function St(){if(Ss(n),!j){r("Select a Google Ads customer before saving.");return}r(null);try{await Re.mutateAsync({path:{name:s},body:{customerId:j,...P.trim()?{loginCustomerId:P.trim()}:{}}}),x(null),nt(),await Be(()=>V.data?.selectedCustomer!=null)}catch(q){r(Nt(q))}}async function ee(){if(Ss(n),!g||!S){r("Select a Tag Manager account and container before saving.");return}r(null);try{await re.mutateAsync({path:{name:s},body:{accountId:g,containerId:S,...M?{workspaceId:M}:{}}}),x(null),nt(),await Be(()=>Q.data?.status==="connected")}catch(q){r(Nt(q))}}async function Ee(){Ss(n),r(null),await st.mutateAsync({path:{name:s}}),x(null),d(!1),A(""),C(""),y(!1),i(null),await ze(),Fe({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),O.current=null,xt(()=>Xe(document.getElementById("conversion-integrity-title")))}async function Te(){Ss(n),r(null),await pe.mutateAsync({path:{name:s}}),x(null),v(""),L(""),w(""),b(!1),i(null),await ze(),Fe({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),O.current=null,xt(()=>Xe(document.getElementById("conversion-integrity-title")))}async function Pe(){Ss(n),r(null);try{const q=await me.mutateAsync({path:{name:s}});Le(q,"google-ads-sync")}catch(q){r(Nt(q))}}async function Bt(){Ss(n),r(null);try{const q=await Ae.mutateAsync({path:{name:s}});Le(q,"gtm-sync")}catch(q){r(Nt(q))}}async function Wt(){Ss(n),r(null);try{const q=await Promise.allSettled([me.mutateAsync({path:{name:s}}),Ae.mutateAsync({path:{name:s}})]),[Se,rt]=q;Se.status==="fulfilled"&&Le(Se.value,"google-ads-sync"),rt.status==="fulfilled"&&Le(rt.value,"gtm-sync");const Et=q.find(Zt=>Zt.status==="rejected");if(Et?.status==="rejected")throw Et.reason}catch(q){r(Nt(q))}}async function ht(){Ss(n);const q=V.data?.connection?.selection.customerId,Se=Q.data?.selection;if(!q||!Se?.accountId||!Se.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const rt=await D.mutateAsync({path:{name:s},body:oy(z,q,{accountId:Se.accountId,containerId:Se.containerId})});_(ll),F(!1),nt(),(await E.refetch()).data?.some(Zt=>Zt.id===rt.id)&&te(rt.id)}catch(rt){r(Nt(rt))}}function Yt(q){switch(q){case"connect-google-ads":Ve();return;case"connect-gtm":be(),It();return;case"select-google-ads":R();return;case"select-gtm":Me();return;case"sync-google-ads":Pe();return;case"sync-gtm":Bt();return;case"sync-static-evidence":Wt();return;case"declare-contract":we();return;case"review-findings":it("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":it("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":ze();return;case"select-contract":it("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ue.refetch();return;case"waiting-for-integrity":return}}const Ze=fe.data?.customers??[],Xt=Z.data?.accounts??[],hs=ce.data?.containers??[],$s=G.data?.workspaces??[],ps=!!j&&!Ze.some(q=>q.customerId===j),Us=!!g&&!Xt.some(q=>q.id===g),gt=!!S&&!hs.some(q=>q.id===S),qs=!!M&&!$s.some(q=>q.id===M),vt=ps&&fe.isSuccess&&fe.data.truncated===!1,ct=Us&&Z.isSuccess&&Z.data.truncated===!1,Lt=gt&&ce.isSuccess&&ce.data.truncated===!1,xs=qs&&G.isSuccess&&G.data.truncated===!1,bs=ct||Lt||xs,$t=ct?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Lt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":xs?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,Ft=Qa(vt,fe.data,fe.isError),ft=Qa(ct,Z.data,Z.isError),qt=Qa(Lt,ce.data,ce.isError),Bs=Qa(xs,G.data,G.isError),Ct=fe.isError?Nt(fe.error):null,ss=Z.isError?Nt(Z.error):ce.isError?Nt(ce.error):G.isError?Nt(G.error):null,Jt=p==="google-ads"?Ct:p==="gtm"?ss:null,K=Va("customer",fe.data,Ze.length),ae=Va("account",Z.data,Xt.length),Ce=Va("container",ce.data,hs.length),he=Va("draft workspace",G.data,$s.length),Ie=Z.isError||ce.isError||G.isError&&!!M,Qe=c||p!==null||U;function mt(){fe.refetch()}function jt(){if(Z.isError){Z.refetch();return}if(ce.isError){ce.refetch();return}G.isError&&G.refetch()}return V.isLoading||Q.isLoading||E.isLoading?e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("div",{"aria-hidden":"true",className:"mt-5 grid gap-4 sm:grid-cols-2",children:[0,1].map(q=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"skeleton-text-sm w-full"}),e.jsx("div",{className:"skeleton-text-sm w-3/4"})]},q))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):E.isError&&!E.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",Nt(E.error)]}),e.jsx(T,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{E.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ny,{workspace:Oe,onPrimaryAction:Yt,actionPending:_e,actionError:Qe?null:a,contracts:ne,selectedContractId:ke?.id??null,onSelectContract:q=>te(q||null),contractError:E.isError?Nt(E.error):null,onRetryContracts:()=>{E.refetch()},onRetryEvidence:()=>{Promise.all([H.refetch(),se.refetch()])},onChangeGoogleAdsSelection:R,onChangeGtmSelection:Me,onAddContract:()=>Yt("declare-contract")}),l?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:l}):null,c?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:Je(async q=>{q.preventDefault(),await At()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:os,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:m,onChange:q=>u(q.target.value),className:Kt,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"submit",disabled:de.isPending,children:de.isPending?"Starting…":"Continue to Google"}),e.jsx(T,{type:"button",variant:"outline",onClick:ut,children:"Cancel"})]})]})]}):null,p==="google-ads"?e.jsxs("section",{id:"google-ads-selection-panel",className:"page-section-divider","aria-labelledby":"google-ads-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select customer context"})]})}),Jt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:Jt}),e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:mt,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,vt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:"The saved customer is no longer accessible. Choose another customer before saving."}):null,e.jsxs("div",{className:"grid max-w-2xl gap-4 sm:grid-cols-2",children:[e.jsxs(za,{id:"google-ads-customer",label:"Customer account",value:j,onChange:q=>{y(!0),A(q);const Se=Ze.find(rt=>rt.customerId===q);C(Se?.parentCustomerId??"")},disabled:fe.isLoading,children:[e.jsx("option",{value:"",children:fe.isLoading?"Loading accessible customers…":"Select a customer"}),ps?e.jsxs("option",{value:j,disabled:vt,children:["Saved customer ",j," (",Ft,")"]}):null,Ze.map(q=>e.jsx("option",{value:q.customerId,children:q.descriptiveName??`Customer ${q.customerId}`},q.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:os,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Kt,value:P,onChange:q=>{y(!0),C(q.target.value)},placeholder:"Use only when a manager context is required"})]})]}),K?e.jsx("p",{role:"status",className:`mt-3 text-sm ${fe.data?.truncated?"text-caution":"text-secondary"}`,children:K}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"button",disabled:Re.isPending||fe.isLoading||fe.isError||vt||!j,onClick:Je(St),children:Re.isPending?"Saving…":"Save customer selection"}),e.jsx(T,{type:"button",variant:"outline",onClick:wt,children:"Cancel"})]}),V.data?.connected?e.jsx(ul,{providerLabel:"Google Ads",disabled:_e,onDisconnect:Ee}):null]}):null,p==="gtm"?e.jsxs("section",{id:"gtm-selection-panel",className:"page-section-divider","aria-labelledby":"gtm-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Tag Manager"}),e.jsx("h3",{id:"gtm-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select container context"})]})}),Jt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:Jt}),e.jsx(T,{type:"button",variant:"outline",size:"sm",onClick:jt,children:Z.isError?"Retry account list":ce.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,$t?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:$t}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(za,{id:"gtm-account",label:"Account",value:g,onChange:q=>{b(!0),q!==g&&(L(""),w("")),v(q)},disabled:Z.isLoading,children:[e.jsx("option",{value:"",children:Z.isLoading?"Loading accounts…":"Select an account"}),Us?e.jsxs("option",{value:g,disabled:ct,children:["Saved account ",g," (",ft,")"]}):null,Xt.map(q=>e.jsx("option",{value:q.id,children:q.name},q.id))]}),e.jsxs(za,{id:"gtm-container",label:"Container",value:S,onChange:q=>{b(!0),q!==S&&w(""),L(q)},disabled:!g||ce.isLoading,children:[e.jsx("option",{value:"",children:ce.isLoading?"Loading containers…":"Select a container"}),gt?e.jsxs("option",{value:S,disabled:Lt,children:["Saved container ",S," (",qt,")"]}):null,hs.map(q=>e.jsx("option",{value:q.id,children:q.name},q.id))]}),e.jsxs(za,{id:"gtm-workspace",label:"Draft workspace (optional)",value:M,onChange:q=>{b(!0),w(q)},disabled:!S||G.isLoading,children:[e.jsx("option",{value:"",children:G.isLoading?"Loading workspaces…":"No draft workspace"}),qs?e.jsxs("option",{value:M,disabled:xs,children:["Saved draft workspace ",M," (",Bs,")"]}):null,$s.map(q=>e.jsx("option",{value:q.id,children:q.name},q.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[ae?e.jsx("p",{role:"status",className:Z.data?.truncated?"text-caution":"text-secondary",children:ae}):null,Ce?e.jsx("p",{role:"status",className:ce.data?.truncated?"text-caution":"text-secondary",children:Ce}):null,he?e.jsx("p",{role:"status",className:G.data?.truncated?"text-caution":"text-secondary",children:he}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"button",disabled:re.isPending||Z.isLoading||ce.isLoading||G.isLoading&&!!M||Ie||bs||!g||!S,onClick:Je(ee),children:re.isPending?"Saving…":"Save container selection"}),e.jsx(T,{type:"button",variant:"outline",onClick:wt,children:"Cancel"})]}),Q.data?.connected?e.jsx(ul,{providerLabel:"Tag Manager",disabled:_e,onDisconnect:Te}):null]}):null,U?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:Je(async q=>{q.preventDefault(),await ht()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:os,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Kt,value:z.name,onChange:q=>_(Se=>({...Se,name:q.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:os,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Kt,value:z.eventName,onChange:q=>_(Se=>({...Se,eventName:q.target.value})),placeholder:"booking_complete"})]}),e.jsx(ml,{id:"contract-conversion-action",label:"Google Ads conversion action",options:k?.googleAds.conversionActions??[],synced:k?.googleAds.syncedAt!=null,loading:J.isLoading,failed:J.isError,onRetry:()=>{J.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:z.conversionActionId,onChange:q=>_(Se=>({...Se,conversionActionId:q}))}),e.jsx(ml,{id:"contract-gtm-tag",label:"Tag Manager tag",options:k?.gtm.tags??[],synced:k?.gtm.syncedAt!=null,loading:J.isLoading,failed:J.isError,onRetry:()=>{J.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:z.tagId,onChange:q=>_(Se=>({...Se,tagId:q}))})]}),e.jsxs("details",{className:"inline-disclosure mt-5 max-w-3xl",children:[e.jsx("summary",{children:"Additional matching rules"}),e.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-conversion-id",className:os,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Kt,value:z.conversionId,onChange:q=>_(Se=>({...Se,conversionId:q.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:os,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Kt,value:z.conversionLabel,onChange:q=>_(Se=>({...Se,conversionLabel:q.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:os,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Kt,value:z.triggerIds,onChange:q=>_(Se=>({...Se,triggerIds:q.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:os,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Kt,value:z.variableIds,onChange:q=>_(Se=>({...Se,variableIds:q.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:os,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Kt,value:z.campaignIds,onChange:q=>_(Se=>({...Se,campaignIds:q.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:os,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Kt,value:z.productionHosts,onChange:q=>_(Se=>({...Se,productionHosts:q.target.value})),placeholder:"example.com"})]})]}),e.jsxs("fieldset",{className:"mt-5 border-t border-subtle pt-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Required evidence"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsx($n,{id:"contract-primary-action",checked:z.requirePrimaryAction,onChange:q=>_(Se=>({...Se,requirePrimaryAction:q})),children:"Google Ads action is primary"}),e.jsx($n,{id:"contract-biddable-goal",checked:z.requireBiddableGoal,onChange:q=>_(Se=>({...Se,requireBiddableGoal:q})),children:"Google Ads goal is biddable"}),e.jsx($n,{id:"contract-runtime-verification",checked:z.verificationRequired,onChange:q=>_(Se=>({...Se,verificationRequired:q})),children:"Runtime proof is required"}),e.jsx($n,{id:"contract-transaction-id",checked:z.requireTransactionId,onChange:q=>_(Se=>({...Se,requireTransactionId:q})),children:"Transaction ID is required"}),e.jsx($n,{id:"contract-value",checked:z.requireValue,onChange:q=>_(Se=>({...Se,requireValue:q})),children:"Conversion value is required"}),e.jsx($n,{id:"contract-currency",checked:z.requireCurrency,onChange:q=>_(Se=>({...Se,requireCurrency:q})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"submit",disabled:D.isPending,children:D.isPending?"Saving…":"Save conversion contract"}),e.jsx(T,{type:"button",variant:"outline",onClick:Mt,children:"Cancel"})]})]})]}):null]})}const cy=6e4,dy=["7d","14d","30d"],Bi="not available",uy='Figures come from the stored Google Ads snapshot; this view never calls Google. The window ends on the newest CLOSED day, because the capture day is only partly recorded and would read as a drop. A calendar day the provider returned no row for is zero delivery, so it is charted as zero. Rates with a zero denominator read "not available", never 0%.',my="No Google Ads snapshot stored yet",hy="Connect a Google Ads account in Conversion Integrity below, choose the customer, then run a Google Ads sync. Spend, clicks, impressions, and conversions appear here once the first snapshot is stored.",py="No closed days yet",xy="The stored snapshot covers no completed day yet. Figures appear after a full day closes in the account time zone; the day a snapshot is captured is partial and is left out on purpose. If this persists, check the latest Google Ads sync in Activity.",gy={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},Ws=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),Qr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),fy=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function qn(t,s){return t===null||!Number.isFinite(t)?Bi:s===null?fy.format(t/1e6):cp(t,s)}function zr(t){return t===null||!Number.isFinite(t)?Bi:tt(t)}function yy(t,s){return t===null||!Number.isFinite(t)?`${Bi} vs prior ${s}d`:t===0?`no change vs prior ${s}d`:`${t>0?"↑":"↓"} ${tt(Math.abs(t))} vs prior ${s}d`}function by(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function vy(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function jy(t,s){return s==="none"||t===null||!Number.isFinite(t)||t===0?"text-muted":(s==="up-good"?t>0:t<0)?"text-positive":"text-negative"}function Ny({projectName:t}){const[s,n]=o.useState("14d"),[a,r]=o.useState(()=>new Set(["costMicros","conversions"])),l=qe({...zu({client:Y,path:{name:t},query:{window:s}}),staleTime:cy}),i=l.data,c=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Ge,{text:uy})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Pt(i.startDate)," to ",Pt(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(pr,{windows:dy,value:s,onChange:n,label:"Google Ads time period"})]});if(l.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[c,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(g=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-20"}),e.jsx("div",{className:"skeleton-text-sm w-28"})]},g))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(l.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",Nt(l.error)]}),e.jsx(T,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{l.refetch()},children:"Retry performance"})]});const{totals:d,daily:m,campaigns:u,comparison:p,comparisonUnavailableReason:x,source:h}=i;if(!h){const g=x==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:g?py:my}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:g?xy:hy})]})]})}const y=h.currencyCode,f=h.campaignsInInventory>0&&h.campaignsQueried<h.campaignsInInventory?{queried:h.campaignsQueried,inInventory:h.campaignsInInventory}:null,b=d.costMicros>0&&d.conversions===0,j=[{key:"spend",comparable:!0,label:"Spend",value:qn(d.costMicros,y),change:p?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:Qr.format(d.conversions),change:p?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:b?"no conversions":qn(d.costPerConversionMicros,y),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:zr(d.conversionRate),change:p?.change.conversionRate??null,direction:"up-good",seriesKey:null}],A=[{key:"clicks",label:"Clicks",value:Ws.format(d.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:Ws.format(d.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:zr(d.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:qn(d.cpcMicros,y),seriesKey:null}],P={costMicros:{label:"Spend",color:lt[1],axisId:"spend",formatValue:g=>qn(g,y)},conversions:{label:"Conversions",color:lt[0],axisId:"conversions",formatValue:g=>Qr.format(g)},clicks:{label:"Clicks",color:lt[2],axisId:"clicks",formatValue:g=>Ws.format(g)},impressions:{label:"Impressions",color:lt[3],axisId:"impressions",formatValue:g=>Ws.format(g)}},C=[...a].map(g=>({dataKey:g,...P[g]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,f!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",Ws.format(f.queried)," of"," ",Ws.format(f.inInventory)," campaigns, so they are a subset of the account."]}):null,h.truncated?e.jsx("p",{role:"status",className:"mt-3 text-sm text-caution",children:"The provider returned a bounded result, so some rows are missing from the figures below."}):null,!p&&x==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:gy["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:j.map(g=>{const v=g.seriesKey!==null&&a.has(g.seriesKey),S=v&&a.size===1,L=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[g.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?P[g.seriesKey].color:"var(--color-mono-600)"}}):null,g.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:g.value}),p&&g.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${jy(g.change,g.direction)}`,children:yy(g.change,p.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:g.comparable?`no prior ${s} period stored`:" "})]});return g.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:L},g.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:S,onClick:()=>r(M=>{const w=new Set(M);return w.has(g.seriesKey)?w.delete(g.seriesKey):w.add(g.seriesKey),w.size===0?M:w}),className:`rounded-md border px-3 py-2 text-left transition-colors ${v?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${S?"cursor-default":""}`,children:L},g.key)})}),e.jsx("dl",{className:"mt-2 flex flex-wrap gap-x-6 gap-y-1 rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:A.map(g=>{const v=g.seriesKey!==null&&a.has(g.seriesKey),S=v&&a.size===1,L=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[g.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?P[g.seriesKey].color:"var(--color-mono-600)"}}):null,g.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:g.value})]});return g.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:L},g.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:S,onClick:()=>r(M=>{const w=new Set(M);return w.has(g.seriesKey)?w.delete(g.seriesKey):w.add(g.seriesKey),w.size===0?M:w}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${S?"cursor-default":"hover:bg-surface-hover"}`,children:L},g.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(ic,{data:m,xKey:"date",series:C,xTickFormatter:wn,labelFormatter:Pt}),e.jsx("ul",{className:"sr-only",children:m.map(g=>e.jsxs("li",{children:[Pt(g.date),":"," ",C.map(v=>`${v.label} ${P[v.dataKey].formatValue(g[v.dataKey])}`).join(", "),g.origin==="filled"?", no delivery reported":""]},g.date))})]}),e.jsxs("div",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"By campaign"}),e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Campaign performance"})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads campaign performance for the selected window"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Campaign"}),e.jsx("th",{className:"text-left",children:"Status"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Clicks"}),e.jsx("th",{className:"text-right",children:"Spend"}),e.jsx("th",{className:"text-right",children:"Conversions"}),e.jsx("th",{className:"text-right",children:"CTR"}),e.jsx("th",{className:"text-right",children:"Cost / conv."})]})}),e.jsx("tbody",{children:u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):u.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:g.name??g.campaignId,children:g.name??e.jsx("span",{className:"font-mono text-secondary",children:g.campaignId})}),e.jsx("td",{children:e.jsx(je,{tone:by(g.status),children:vy(g.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ws.format(g.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ws.format(g.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:qn(g.totals.costMicros,y)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Qr.format(g.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:zr(g.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:g.totals.costMicros>0&&g.totals.conversions===0?e.jsx(je,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:qn(g.totals.costPerConversionMicros,y)})})]},g.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",wa(Ut(h.capturedAt))," · ","customer ",h.customerId," · ","latest closed day ",Pt(h.asOfDate),h.openDate?e.jsxs(e.Fragment,{children:[" · ",Pt(h.openDate)," still open, excluded"]}):null,h.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",h.timeZone]}):null]})]})]})}const Hr=20,Os=50,wy=50,Sy=50;function Vi(t){return t==="viewer"}function Qi(t){return t?.status==="unavailable"}function Vc(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Qc(t,s){const n=new Map(s.map(r=>[r.id,r.label])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function Ha(t,s,n){if(t.kind==="all")return s.map(l=>l.id);if(t.kind==="specific")return s.filter(l=>t.propertyIds.includes(l.id)).map(l=>l.id);const a=new Set(t.groupIds),r=new Set(n.filter(l=>a.has(l.id)).flatMap(l=>l.propertyIds));return s.filter(l=>r.has(l.id)).map(l=>l.id)}function Cy(t,s,n){if(t.kind==="all")return`all ${n} ${n===1?"Property":"Properties"}`;if(t.kind==="specific")return n===1?"1 Property":`${n} Properties`;const a=t.groupIds.map(r=>s.find(l=>l.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function Wr(t,s){const n=new Set(s.map(r=>r.id)),a=t.propertyIds.filter(r=>n.has(r)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function hl(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function pl(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 Wa(t){return t.status==="duplicate"&&t.duplicateOfRow?`Duplicates row ${t.duplicateOfRow}.`:t.status==="matched"?null:t.reason==="group-label-ambiguous"?`More than one group matches “${t.group}”. Rename duplicate groups, then preview again.`:t.status==="ambiguous"?"More than one Property matches this row. Add an exact URL to choose one.":t.status==="unmatched"?"No included Property matches this row.":t.reason==="group-key-conflict"?`The group name “${t.group}” conflicts with an existing setup identity. Rename the group, then preview again.`:t.status==="invalid"?"Check the Property, group, and optional URL fields.":t.status==="proposed"?"Review this proposed Property before importing it.":t.status==="excluded"?"Include this Property before importing it.":t.reason??null}function vi(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Yr(t){return vi(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ji({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[l,i]=o.useState(""),[c,d]=o.useState(!1),m=l.trim().toLocaleLowerCase(),u=m?t.filter(y=>y.label.toLocaleLowerCase().includes(m)):t,p=c?u:u.slice(0,wy),x=p.length<u.length;function h(){const y=new Set([...s,...p.map(f=>f.id)]);n(t.filter(f=>y.has(f.id)).map(f=>f.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:l,onChange:y=>i(y.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p.length===0,onClick:h,children:"Select all shown"}),e.jsx(T,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),u.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",p.length," of ",u.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:p.map(y=>{const f=s.includes(y.id);return e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-sm text-primary",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{"aria-label":`Select ${y.label}`,checked:f,type:"checkbox",onChange:b=>n(Vc(s,y.id,b.currentTarget.checked))}),e.jsx("span",{children:y.label})]}),y.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[y.urlCount," URLs"]})]},y.id)})}),x?e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function zi(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(je,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Hi({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function ky({value:t}){const[s,n]=o.useState(0),[a,r]=o.useState(0),[l,i]=o.useState(null),c=t.preview,d=c?.counts.needsAttention??0,m=c?.rows.filter(S=>S.status==="matched")??[],u=c?.rows??[],p=u.filter(S=>S.status!=="matched"),x=Math.max(1,Math.ceil(u.length/Os)),h=Math.min(s,x-1),y=u.slice(h*Os,(h+1)*Os),f=Math.max(1,Math.ceil(p.length/Os)),b=Math.min(a,f-1),j=p.slice(b*Os,(b+1)*Os),A=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,P=m.length>0&&!t.isApplying,C=c!==null&&l===c.previewChecksum,g=p.length>0&&b===f-1;o.useEffect(()=>{n(0),r(0),i(null)},[c?.previewChecksum]);async function v(S){if(S)try{t.onCsvChange(await S.text())}catch{}}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-group-import-title",className:"border-y border-default py-4",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h4",{id:"advanced-measurement-group-import-title",className:"text-sm font-medium text-heading",children:"Import groups from CSV"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Import market membership once instead of selecting the same Properties for every group."})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"CSV file"}),e.jsx("input",{"aria-label":"Group membership CSV file",type:"file",accept:".csv,text/csv",disabled:t.isReviewing||t.isApplying,onChange:S=>{v(S.currentTarget.files?.[0])},className:"mt-1 block min-h-11 w-full text-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary"})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Or paste CSV"}),e.jsx("textarea",{"aria-label":"Group membership CSV",rows:5,value:t.csv,disabled:t.isReviewing||t.isApplying,onChange:S=>t.onCsvChange(S.currentTarget.value),placeholder:`property,group,url
3
3
  Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!A,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),c?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[c.counts.matchedRows," matched · ",c.counts.groupsReady," group",c.counts.groupsReady===1?"":"s"," ready",d>0?` · ${d} need${d===1?"s":""} attention`:""]}),c.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:c.groupChanges.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.label}),e.jsx("td",{className:"text-secondary",children:S.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:S.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[S.addedTargetKeys.length,S.unchangedTargetKeys.length>0?` · ${S.unchangedTargetKeys.length} already members`:""]})]},S.groupKey))})]})}):null,c.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",c.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:y.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(je,{tone:hl(S.status),children:pl(S.status)}),Wa(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Wa(S)}):null]})]},S.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",h+1," of ",x," · ",c.rows.length," rows"]}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h===0,onClick:()=>n(S=>Math.max(0,S-1)),children:"Previous 50 rows"}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h===x-1,onClick:()=>n(S=>Math.min(x-1,S+1)),children:"Next 50 rows"})]})]}):null,d>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",d," row",d===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:j.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(je,{tone:hl(S.status),children:pl(S.status)}),Wa(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Wa(S)}):null]})]},S.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",b+1," of ",f]}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===0,onClick:()=>r(S=>Math.max(0,S-1)),children:"Previous 50 exceptions"}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===f-1,onClick:()=>r(S=>Math.min(f-1,S+1)),children:"Review next 50 exceptions"})]}),e.jsxs("label",{className:"mt-3 flex min-h-11 max-w-xl items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:C,disabled:t.isApplying||!g,onChange:S=>i(S.currentTarget.checked?c.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",d," row",d===1?"":"s"," will be skipped."]}),e.jsx(T,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!P||!C,onClick:()=>{t.onApply(m.map(S=>S.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${m.length} matched row${m.length===1?"":"s"}`})]}):e.jsx(T,{type:"button",className:"mt-3 min-h-11",disabled:!P,onClick:()=>{t.onApply(m.map(S=>S.dataRow))},children:t.isApplying?"Creating groups…":`Create ${c.counts.groupsReady} group${c.counts.groupsReady===1?"":"s"} with ${m.length} membership${m.length===1?"":"s"}`})]}):null]})}const Ay="—";function Ry({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:l=!1,isBusy:i=!1,canContinue:c=!0,onSelectedQueryIdsChange:d,onApplySelectedQueries:m,onClearQueryAssignments:u,onRemoveQuery:p,onCreateQueries:x,onCreateAndPairQuestions:h,isCreatingQueries:y=!1,createQueriesError:f=null,onManageProjectQueries:b,groups:j,audience:A,onAudienceChange:P,assignmentImpact:C=null,isPreviewingAssignmentImpact:g=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:S,assignmentNotice:L=null,onReplaceAssignments:M,isReplacingAssignments:w=!1,onBack:U,onContinue:F}){const[z,_]=o.useState(""),[B,te]=o.useState(!1),[O,V]=o.useState(!1),[Q,E]=o.useState(""),[J,k]=o.useState(""),[H,se]=o.useState(null);if(Qi(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Hi,{message:s.message})});const ne=Vi(t),oe=A,ke=P,X=Ha(oe,n,j),ue=X.length,fe=ue>0&&r.length>0&&!l&&!i&&!g&&C!==null&&v===null,Z=u??p,ce=z.trim().toLocaleLowerCase(),G=ce?a.filter(I=>Yr(I).toLocaleLowerCase().includes(ce)):a,de=G.filter(I=>(I.propertyIds?.length??0)===0),De=O?de:G,Re=B?De:De.slice(0,Sy),re=Re.filter(I=>!vi(I)),me=[...new Set(Q.split(`
4
4
  `).map(I=>I.trim()).filter(Boolean))],Ae=[...J.matchAll(/\{([a-z][\w-]*)\}/gi)].map(I=>I[1]),st=n.filter(I=>X.includes(I.id)),pe=Ae.length===0||J.trim()===""?[]:st.map(I=>({propertyId:I.id,text:Ae.reduce((ye,_e)=>ye.replaceAll(`{${_e}}`,I.label),J.trim())})),D=[...new Set(pe.map(I=>I.text))];function Oe(){const I=new Set([...r,...re.map(ye=>ye.id)]);d(a.filter(ye=>I.has(ye.id)).map(ye=>ye.id))}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-queries-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-queries-title",children:"Queries"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose queries, then apply them to Properties."})]})}),ne?e.jsx(zi,{}):null,ne?null:e.jsxs("fieldset",{className:"border-y border-default py-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Apply to"}),e.jsx("div",{className:"mt-3 max-w-xl",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"sr-only",children:"Apply to"}),e.jsxs("select",{"aria-label":"Apply to",value:oe.kind==="all"?"all":oe.kind==="specific"?"specific":`group:${oe.groupIds[0]??""}`,onChange:I=>{const ye=I.currentTarget.value;ye==="all"?ke({kind:"all"}):ye==="specific"?ke({kind:"specific",propertyIds:[]}):ye.startsWith("group:")&&ke({kind:"groups",groupIds:[ye.slice(6)]})},className:"block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsxs("option",{value:"all",children:["All Properties · ",n.length]}),j.length>0?e.jsx("optgroup",{label:"Groups",children:j.map(I=>{const ye=Ha({kind:"groups",groupIds:[I.id]},n,j).length;return e.jsx("option",{value:`group:${I.id}`,disabled:ye===0,children:Wr(I,n)},I.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),oe.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:oe.groupIds.map(I=>{const ye=j.find(_e=>_e.id===I);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:[Wr(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 _e=oe.groupIds.filter(ze=>ze!==ye.id);ke(_e.length>0?{kind:"groups",groupIds:_e}:{kind:"all"})},children:"×"})]},ye.id):null})}),j.some(I=>!oe.groupIds.includes(I.id)&&Ha({kind:"groups",groupIds:[I.id]},n,j).length>0)?e.jsxs("label",{className:"block max-w-sm",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Add another group"}),e.jsxs("select",{"aria-label":"Add another group",value:"",onChange:I=>{I.currentTarget.value&&ke({kind:"groups",groupIds:[...oe.groupIds,I.currentTarget.value]})},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",children:"Choose a group"}),j.filter(I=>!oe.groupIds.includes(I.id)).map(I=>{const ye=Ha({kind:"groups",groupIds:[I.id]},n,j).length;return e.jsx("option",{value:I.id,disabled:ye===0,children:Wr(I,n)},I.id)})]})]}):null,ue===0?e.jsx("p",{role:"alert",className:"text-sm text-caution",children:"This group has no included Properties. Add Properties to the group, then try again."}):null]}):null,oe.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(ji,{legend:"Specific Properties",properties:n,selectedPropertyIds:oe.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:I=>{ke({kind:"specific",propertyIds:I})}})}):null,e.jsx("p",{className:"mt-3 max-w-2xl text-sm text-secondary",children:"Groups are shortcuts resolved when you assign. Changing membership later does not rewrite existing assignments, and a Property added later does not receive earlier group queries."})]}),ne||!x?null:e.jsxs("details",{open:a.length===0,className:"border-y border-default py-4",children:[e.jsx("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:"Add queries"}),e.jsxs("div",{className:"pt-3",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:a.length===0?"Add the queries you want to track":"Add more queries"}),e.jsx("p",{className:"mt-1 mb-2 text-sm text-secondary",children:"One per line. Add them to the project, then apply them to Properties."}),e.jsx("textarea",{"aria-label":"New queries, one per line",className:"w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:4,value:Q,onChange:I=>E(I.currentTarget.value),placeholder:`best apartments in dallas