@canonry/canonry 7.11.0 → 7.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/assets/{AuditHistoryPanel-D1WdkJKU.js → AuditHistoryPanel-BYxGn9mS.js} +1 -1
- package/assets/assets/{BacklinksPage-Uf1djxaV.js → BacklinksPage-BQxB_eFt.js} +1 -1
- package/assets/assets/{HistoryPage-CZPxzlS_.js → HistoryPage-DgGUM2tr.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-CaWq1f2G.js → MeasurementPropertyPage-Cl91vUu5.js} +1 -1
- package/assets/assets/ProjectPage-B_S900QN.js +8 -0
- package/assets/assets/{RunsPage-CDX5RxHi.js → RunsPage-BtjVuurK.js} +1 -1
- package/assets/assets/{SettingsPage-BfzKP-IR.js → SettingsPage-p0x0ZwGY.js} +1 -1
- package/assets/assets/{SiteHealthSection-42_E1ueq.js → SiteHealthSection-DMHWsfM4.js} +3 -3
- package/assets/assets/{TrafficPage-RjkpfGMw.js → TrafficPage-Bf0NkbIR.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-DIWDPo-8.js → TrafficSourceDetailPage-BtwOdTAO.js} +1 -1
- package/assets/assets/{extract-error-message-D_e8B2s_.js → extract-error-message-Cyc59Xi7.js} +1 -1
- package/assets/assets/index-D4QB1Igv.css +1 -0
- package/assets/assets/index-DR_kNdE4.js +86 -0
- package/assets/assets/{react-sigma_core.esm.min-Br-N5hoB.js → react-sigma_core.esm.min-CFB4bYg_.js} +1 -1
- package/assets/assets/{v2-overview-adapter-BCSXgy2l.js → v2-overview-adapter-CLF10Pij.js} +1 -1
- package/assets/index.html +2 -2
- package/dist/{chunk-OH7E7TJD.js → chunk-7I64KEGM.js} +2 -2
- package/dist/{chunk-CF7G2HGX.js → chunk-AU7OUDWR.js} +5 -0
- package/dist/{chunk-7G7YVTDA.js → chunk-BTHEFJCI.js} +5 -3
- package/dist/{chunk-JRBQFRNT.js → chunk-EPSHIH63.js} +3 -3
- package/dist/{chunk-S46DWUNR.js → chunk-GBH7N3VZ.js} +59 -32
- package/dist/{chunk-HA2BAJ6Z.js → chunk-GQMSJEMZ.js} +107 -36
- package/dist/{chunk-GQAESNJT.js → chunk-SM6ZZAPK.js} +5 -5
- package/dist/cli.js +20 -11
- package/dist/{demo-server-BYLZFDKI.js → demo-server-WJUA4EIG.js} +4 -4
- package/dist/index.js +6 -6
- package/dist/{intelligence-service-TIM4XTYH.js → intelligence-service-DJRH4Z3D.js} +2 -2
- package/dist/mcp.js +4 -4
- package/package.json +16 -16
- package/assets/assets/ProjectPage-BimakE9X.js +0 -8
- package/assets/assets/index-BNeiohKS.css +0 -1
- package/assets/assets/index-DKl_jsi3.js +0 -86
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{j as e,r as o,t as rd,u as qe,L as Ms,h as hs,o as Et,B as wi,C as Ml,D as id,k as od,l as ld}from"./vendor-tanstack-ZXXkndVj.js";import{T as Ne,t as cd,a as dd,s as Si,M as ga,I as Oe,f as tt,R as Yn,m as ud,B as P,c as md,b as hd,d as pd,S as Ll,e as $l,u as Ci,g as xd,n as Bn,C as gd,h as ql,i as El,j as ki,k as fd,l as yd,o as bd,p as vn,q as Dl,r as Ol,v as je,w as sr,x as W,y as ie,z as Ls,A as $t,D as Ze,E as vd,F as jd,G as Nd,H as Fl,J as wd,K as Sd,L as nn,N as jn,O as Cd,P as kd,Q as Mn,U as Jt,V as Ad,W as Rd,X as to,Y as Kl,Z as Yt,_ as Ai,$ as Pd,a0 as Id,a1 as Td,a2 as Md,a3 as so,a4 as De,a5 as Ld,a6 as $d,a7 as Nr,a8 as qd,a9 as Ed,aa as Dd,ab as Od,ac as Fd,ad as Kd,ae as Gd,af as _d,ag as Ud,ah as Bd,ai as Vd,aj as Qd,ak as zd,al as Hd,am as Wd,an as Gl,ao as Us,ap as Yd,aq as _l,ar as ir,as as Jd,at as Ye,au as Xd,av as Zd,aw as eu,ax as or,ay as tu,az as su,aA as nu,aB as Vn,aC as au,aD as ru,aE as iu,aF as Ul,aG as ti,aH as ou,aI as Ri,aJ as lu,aK as Qn,aL as ds,aM as xr,aN as Ts,aO as Bl,aP as nr,aQ as si,aR as cu,aS as no,aT as Vl,aU as fa,aV as du,aW as Ql,aX as zl,aY as uu,aZ as Hl,a_ as hn,a$ as Pi,b0 as wr,b1 as mu,b2 as hu,b3 as pu,b4 as xu,b5 as gu,b6 as ha,b7 as ao,b8 as Ea,b9 as Sr,ba as fu,bb as yu,bc as ro,bd as Cr,be as Nn,bf as Wl,bg as Ii,bh as Yl,bi as bu,bj as vu,bk as io,bl as ju,bm as Nu,bn as wu,bo as Su,bp as Cu,bq as ku,br as Au,bs as Ru,bt as Pu,bu as Iu,bv as Tu,bw as Mu,bx as Lu,by as $u,bz as qu,bA as Eu,bB as Du,bC as Ou,bD as Fu,bE as Ku,bF as Gu,bG as _u,bH as Uu,bI as Bu,bJ as Vu,bK as Qu,bL as zu,bM as Hu,bN as Cs,bO as Wu,bP as jt,bQ as Yu,bR as Ju,bS as Xu,bT as Zu,bU as em,bV as tm,bW as sm,bX as nm,bY as am,bZ as rm,b_ as im,b$ as om,c0 as lm,c1 as cm,c2 as dm,c3 as um,c4 as mm,c5 as hm,c6 as pm,c7 as xm,c8 as gm,c9 as fm,ca as oo,cb as ym,cc as bm,cd as vm,ce as jm,cf as Nm,cg as Jl,ch as wm,ci as Sm,cj as Cm,ck as Xl,cl as kr,cm as km,cn as Am,co as lo,cp as Rm,cq as Pm,cr as Im,cs as Tm,ct as Mm,cu as Lm,cv as $m,cw as Zl,cx as qm,cy as ec,cz as tc,cA as sc,cB as nc,cC as Em,cD as Dm,cE as Om,cF as Fm,cG as Km,cH as Gm,cI as _m,cJ as co,cK as Um,cL as Bm,cM as Vm,cN as Qm,cO as zm,cP as Hm,cQ as Wm,cR as Ym,cS as uo,cT as Jm,cU as Xm,cV as Zm,cW as eh,cX as th,cY as sh,cZ as nh,c_ as ah,c$ as rh,d0 as ih,d1 as oh,d2 as lh,d3 as Ar,d4 as ch,d5 as dh,d6 as uh,d7 as mh,d8 as hh,d9 as ph,da as xh,db as gh,dc as fh,dd as yh,de as bh,df as vh,dg as jh,dh as Nh,di as wh,dj as ac,dk as Sh,dl as Ch,dm as kh,dn as Ah,dp as Rh,dq as Ph,dr as Da,ds as Ih,dt as Th,du as Mh,dv as mo,dw as Lh}from"./index-DKl_jsi3.js";import{u as wn,D as Js,a as Gs,b as rc,M as ar,c as Os,F as $h,P as ic,s as qh,p as Eh,S as Dh}from"./SiteHealthSection-42_E1ueq.js";import{A as Ti,a as Oh,b as Fh,c as Kh,V as ho}from"./v2-overview-adapter-BCSXgy2l.js";import{o as Bt,C as ya,f as Sn,a as us,b as Ut,c as Pt,d as ns,e as lt,g as ms,h as Jn,M as oc,i as Gh,j as Sa,p as _h,k as Uh,l as po,m as Bh}from"./ChartPrimitives-CYlrwLJs.js";import{g as lc,y as ba,U as Vh,z as Qh,L as zh,D as Hh,l as Wh,j as lr,I as Yh,J as Jh,C as zn,X as Xh,e as Zh,K as ep,P as tp,N as sp,O as cc}from"./vendor-lucide-N6vOpZmh.js";import{u as np,a as ap,b as rp,t as ip,e as op,c as St}from"./extract-error-message-D_e8B2s_.js";import{R as Xs,C as Zs,a as va,X as en,Y as tn,T as sn,b as ni,L as cr,A as Ws,d as Ks,e as lp}from"./vendor-recharts-D-cUuLZo.js";import{A as cp}from"./AuditHistoryPanel-D1WdkJKU.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B4giJcws.js";import"./vendor-yaml-GWJz5H2G.js";const dp=1e6;function up(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/dp);if(n.showTinyAsLessThan&&t>0&&r===a.format(0)){const l=10**-(a.resolvedOptions().maximumFractionDigits??0);return`<${a.format(l)}`}return r}const Oa={projectWide:"Project-wide",projectWideHelp:"This tab covers the whole project. Your measurement scope stays selected for AI Visibility and Queries.",savedScopeUnavailable:"Saved scope unavailable"};function dc(t,s){return t!=="viewer"||s!==null}function uc(t,s){return t==="research"&&!s?"tracked":t}function mc(t,s){return s.measurementScope==="project"?!1:s.measurementScopeKey?!(s.measurementScope==="group"?t.groups:s.measurementScope==="property"?t.targets:t.markets).some(a=>a.stableKey===s.measurementScopeKey):!0}function ai(t,s){return t.find(n=>n.kind===s.measurementScope&&(n.kind==="project"||n.id===s.measurementScopeKey))}function mp(t){return t.measurementScope!=="project"||t.marketKey!==void 0}function hp(t){if(t.embedded)return{kind:"none"};const{tab:s}=t;switch(s){case"overview":return t.surface==="advanced-overview"?{kind:"report-picker"}:{kind:"none"};case"queries":case"discovery":{const{tracking:n}=t;return t.queryWorkspace!=="tracked"||n.state!=="ready"||n.mode!=="advanced"?{kind:"none"}:n.scopeUnavailable?{kind:"scope-unavailable"}:{kind:"tracking-picker"}}case"search-console":case"activity":case"technical-aeo":case"conversions":case"local":case"backlinks":case"history":return t.scoped&&t.surface==="advanced-overview"?{kind:"project-wide"}:{kind:"none"};case"settings":case"portfolio":return{kind:"none"};default:return s}}function ri({state:t,label:s,className:n}){return e.jsx(Ne,{tone:dd(t),className:n,children:s??cd(t)})}const pn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],xo={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},pp={"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."},xp="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function gp(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,Yn.percent),numeric:!0,detail:`${t.projectMentionSnapshots} of ${t.combinedMentionSnapshots} brand mentions`,showRows:!0}:{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1}}function fp({breakdown:t,projectLabel:s}){if(t.ranking.length===0)return null;const n=t.ranking.map(a=>({label:a.kind==="project"?`${s} (you)`:a.domain??"",mentions:a.mentionSnapshots,share:a.share,isYou:a.kind==="project"}));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Oe,{text:xp})]}),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 yp({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=gp(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:p.snapshotsTotal>0}),h=Si(x.headline),y=m==="non-brand"?ga[t.tone]:"text-secondary";function f(b){const j=pn.findIndex($=>$.value===d);let k=null;b.key==="ArrowRight"||b.key==="ArrowDown"?k=(j+1)%pn.length:b.key==="ArrowLeft"||b.key==="ArrowUp"?k=(j-1+pn.length)%pn.length:b.key==="Home"?k=0:b.key==="End"&&(k=pn.length-1),k!==null&&(b.preventDefault(),r(pn[k].value),b.currentTarget.querySelectorAll('[role="radio"]')[k]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:l,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Oe,{text:pp[m]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":l,className:"segmented flex-wrap",onKeyDown:f,children:pn.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:xo[m]})]}),x.numeric?e.jsxs("p",{className:`mention-share-value ${y}`,children:[h.figure,h.sign?e.jsx("span",{className:"text-faint",children:h.sign}):null]}):e.jsx("p",{className:"mention-share-value-text",children:x.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:xo[m]}),` · ${x.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),x.showRows&&e.jsx(fp,{breakdown:u,projectLabel:s})]})}function Ca({items:t,label:s="Details"}){return t.length===0?null:e.jsxs("details",{className:"av-details",children:[e.jsx("summary",{children:s}),e.jsx("ul",{className:"av-details-list",children:t.map((n,a)=>e.jsx("li",{children:n},a))})]})}function pa({options:t,value:s,onChange:n,label:a,className:r=""}){const l=o.useId();function i(c){const d=t.findIndex(u=>u.value===s);let m=null;c.key==="ArrowRight"||c.key==="ArrowDown"?m=(d+1)%t.length:c.key==="ArrowLeft"||c.key==="ArrowUp"?m=(d-1+t.length)%t.length:c.key==="Home"?m=0:c.key==="End"&&(m=t.length-1),m!==null&&(c.preventDefault(),n(t[m].value),c.currentTarget.querySelectorAll('[role="radio"]')[m].focus())}return e.jsx("div",{role:"radiogroup","aria-label":a,className:`segmented ${r}`.trim(),onKeyDown:i,children:t.map(c=>{const d=c.value===s,m=c.description?`${l}-${c.value}`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button",role:"radio","aria-checked":d,"aria-describedby":m,tabIndex:d?0:-1,onClick:()=>n(c.value),className:`segmented-option pointer-coarse:min-h-11 ${d?"segmented-option-active":""}`,children:c.label}),c.description?e.jsx("span",{id:m,className:"sr-only",children:c.description}):null]},c.value)})})}const bp=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],vp={"7d":"last 7 days","30d":"last 30 days","90d":"last 90 days",all:"all sweeps"},jp={"non-brand":"Non-brand",branded:"Branded",all:"All queries"},Np={"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."},wp={"select-query-class":"no query type selected","answer-selection":"answers selected by the brands they named","no-competitors":"no competitors configured","insufficient-observed":"needs 3 observed competitors, each named in 3 or more answers","no-answers":"no answer text","no-mentions":"no brands named",unavailable:"competitor data unavailable"},go="Mention share: your share of the brand mentions in these answers, each brand counted at most once per answer. Named: answers that name the brand. Cited: answers whose sources link to its site. Company names in answers are observations. Only competitor sites count toward mention share.",ii=100;function Sp(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function hc(t){return t==="unavailable"?"Unavailable":"Not measured"}function oi(t){switch(t){case"own":return"Your domain";case"direct-competitor":return"Competitor";case"ota-aggregator":return"Aggregator";case"editorial-media":return"Editorial";case"other":return"Other";default:return"Unclassified"}}function ks(t,s,n){return t===1?s:n}function pc(t){const s=t.label.trim(),n=md(t.domain);return s&&s.toLowerCase()!==t.domain.toLowerCase()&&s.toLowerCase()!==n.toLowerCase()?s:null}function xc({row:t,aliases:s=[],autoAliases:n=[]}){const a=pc(t),r=[...s.map(i=>({alias:i,auto:!1})),...n.map(i=>({alias:i,auto:!0}))],l=r.length>0?e.jsxs("span",{className:"av-of block",children:["Also named"," ",r.map(({alias:i,auto:c},d)=>e.jsxs("span",{children:[d>0?", ":"",i,c?e.jsx("span",{className:"av-alias-auto",title:"Detected automatically from this project's stored answers",children:" (auto)"}):null]},`${c?"auto":"curated"}:${i}`))]}):null;return a?e.jsxs(e.Fragment,{children:[a," ",e.jsx("span",{className:"av-of",children:t.domain}),l]}):e.jsxs(e.Fragment,{children:[t.domain,l]})}function Cp(t){const s=pc(t);return s?`${s} (${t.domain})`:t.domain}function fo(t,s){return s&&t>=ii?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:t})]}):e.jsx("strong",{children:t})}function li({action:t,domain:s,mutation:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(null);async function c(){if(!a){r(!0),i(null);try{await n(s)===!1&&i(`Could not ${t} competitor. Try again.`)}catch{i(`Could not ${t} competitor. Try again.`)}finally{r(!1)}}}return e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",size:"sm",variant:"outline",disabled:a,onClick:()=>{c()},children:[t==="pin"?"Pin":"Unpin"," ",e.jsx("span",{className:"sr-only",children:s})]}),l?e.jsx("span",{role:"alert",className:"sr-only",children:l}):null]})}function kp({urls:t}){return e.jsxs("details",{className:"inline-disclosure text-left text-xs text-secondary",children:[e.jsx("summary",{children:"Source URLs"}),e.jsx("ul",{className:"mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal",children:t.map(s=>e.jsx("li",{className:"break-all",children:s},s))})]})}function On({count:t,of:s,state:n,toneClass:a}){return n!=="measured"?e.jsx("span",{className:"text-[13px] text-secondary",children:hc(n)}):e.jsxs("span",{className:"whitespace-nowrap",children:[e.jsx("span",{className:`av-n-sm ${a}`,children:t})," ",e.jsxs("span",{className:"av-of",children:["of ",s]})]})}function yo({percent:t,state:s,toneClass:n}){if(s!=="measured"||t===null)return e.jsx("span",{className:"text-[13px] text-secondary",children:s==="measured"?"Not measured":hc(s)});const{figure:a,sign:r}=Si(tt(t,Yn.percent));return e.jsxs("span",{className:`av-n-sm ${n}`,children:[a,r?e.jsx("span",{className:"text-faint",children:r}):null]})}function Ap({rows:t,state:s,named:n,cited:a,onPin:r}){return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":"Other competitors seen",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Competitor"}),e.jsx("th",{scope:"col",children:"Type"}),e.jsx("th",{scope:"col",children:"Named"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(xc,{row:l})}),e.jsx("td",{className:"text-[13px] text-secondary",children:oi(l.surfaceClass)}),e.jsx("td",{children:e.jsx(On,{count:l.mentionCount,of:n,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(On,{count:l.citationCount,of:a,state:s,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex min-w-max items-start gap-2",children:[s==="measured"&&l.sampleUrls.length>0?e.jsx(kp,{urls:l.sampleUrls}):null,r?e.jsx(li,{action:"pin",domain:l.domain,mutation:r}):null]})})]},l.domain))})]})})}function Rp({onAddCompetitor:t}){const s=o.useId(),[n,a]=o.useState(""),[r,l]=o.useState(!1),[i,c]=o.useState(null);async function d(){const m=n.trim();if(!(!m||r)){l(!0),c(null);try{if(await t(m)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("Could not add competitor. Try again.")}finally{l(!1)}}}return e.jsxs("details",{className:"inline-disclosure",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:m=>{m.preventDefault(),d()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:m=>a(m.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(P,{type:"submit",size:"sm",className:"min-h-10",disabled:r||!n.trim(),children:r?"Adding…":"Add competitor"}),i?e.jsx("p",{role:"alert",className:"w-full text-sm text-negative",children:i}):null]})]})}function Pp({window:t,landscape:s,pinnedFallback:n=[],competitorAliases:a={},competitorAutoAliases:r={},canWrite:l,isEmbed:i,onWindowChange:c,onPin:d,onUnpin:m,onAddCompetitor:u,error:p,onRetry:x,isLoading:h=!1,scopeLabel:y}){const f=o.useId(),b=l&&!i,j=s?.pinned??n,k=s?.observed??[],$=s?.otherSources??[],S=s?.evidence,g=Sp(s),v=s?.basis==="observed",C=v?k.filter(D=>D.shareOfVoice!==null):j,T=v?k.filter(D=>D.shareOfVoice===null):k,I=s?.filters.queryClass,w=s?.marketState?.draft?.pendingCompetitorDomains.length??0,V=s?.truncated===!0,F=S?.answeredResults??0,z=S?S.answeredResults+S.missingAnswerTextResults:0,B=I==="non-brand"&&s?.project.shareOfVoice!=null?ga[ud(s.project.shareOfVoice)]:"text-primary",Q=D=>b?D.pinned?m?e.jsx(li,{action:"unpin",domain:D.domain,mutation:m}):null:d?e.jsx(li,{action:"pin",domain:D.domain,mutation:d}):null:null,se=C.some(D=>Q(D)!==null),K=[y,I?jp[I]:null,vp[t],s?.basis?v?"observed competitors only":"tracked competitors only":null].filter(Boolean).join(" · "),U=[];if(s&&!v&&C.length===0&&U.push({key:"no-pins",text:"No pinned competitors."}),s?.reason&&U.push({key:"reason",text:`Mention share: ${wp[s.reason]}`}),s&&T.length>0){const D=T.length;U.push({key:"others",text:V&&D>=ii?`${ii} or more other competitors seen`:`${D} other ${ks(D,"competitor","competitors")} seen`})}w>0&&U.push({key:"pending",text:`${s?.scope.kind==="all-markets"?"Pending publication across markets":"Pending publication"}: ${w} ${ks(w,"competitor","competitors")}`});const J=[S&&S.missingAnswerTextResults>0?"Answer data incomplete":null,S&&S.incompleteSourceResults>0?"Citation data incomplete":null].filter(Boolean);J.length>0&&U.push({key:"incomplete",text:J.join(" · "),className:ga.caution});const q=[];if(s&&S){q.push(s.runCount!==void 0?e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:s.runCount})," ",ks(s.runCount,"sweep","sweeps"),", ",e.jsx("strong",{children:S.answeredResults})," ",ks(S.answeredResults,"answer","answers")]}):e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:S.answeredResults})," ",ks(S.answeredResults,"answer","answers")]})),!s.reason&&g==="measured"&&s.project.shareOfVoice!==null&&q.push(e.jsxs(e.Fragment,{children:["Mention share: you ",e.jsx("strong",{children:s.project.mentionCount}),C.map(ee=>e.jsxs(rd.Fragment,{children:[", ",ee.domain," ",e.jsx("strong",{children:ee.mentionCount})]},ee.domain))," ","of ",e.jsx("strong",{children:S.mentionCredits})," ",v?"brand mentions":"tracked-brand mentions"]})),q.push(e.jsxs(e.Fragment,{children:["Answers with source links: ",e.jsx("strong",{children:S.sourceResults})]})),T.length===0&&q.push("Other competitors seen: none"),S.missingAnswerTextResults>0&&q.push(e.jsxs(e.Fragment,{children:["No answer text: ",e.jsx("strong",{children:S.missingAnswerTextResults})," ",ks(S.missingAnswerTextResults,"answer","answers"),", left out of mention share"]})),S.incompleteSourceResults>0&&q.push(e.jsxs(e.Fragment,{children:["Incomplete source lists: ",e.jsx("strong",{children:S.incompleteSourceResults})," ",ks(S.incompleteSourceResults,"answer","answers"),", not counted as misses"]}));const D=S.excludedProbeResults+S.excludedNonCompletedResults;D>0&&q.push(e.jsxs(e.Fragment,{children:["Left out: ",e.jsx("strong",{children:D})," ",ks(D,"answer","answers")," from spot checks or unfinished sweeps"]}))}const X=[...s?[{name:"You",row:s.project}]:[],...C.map(D=>({name:D.domain,row:D}))].filter(D=>D.row.sampleUrls.length>0);g==="measured"&&X.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:X.map(({name:D,row:ee})=>e.jsxs("div",{children:[e.jsx("p",{children:D}),e.jsx("ul",{className:"space-y-1 font-mono text-[11px] text-muted",children:ee.sampleUrls.map(ne=>e.jsx("li",{className:"break-all",children:ne},ne))})]},ee.domain))})]})),s&&T.length>0&&q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other competitors seen: ",fo(T.length,V)]}),e.jsx("div",{className:"av-subdetails-body",children:e.jsx(Ap,{rows:T,state:g,named:F,cited:z,onPin:b?d:void 0})})]}));const L=s?.observedNames??[];if(L.length>0){const D=s?.observedNamesTotal??L.length;q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Company names in answers: ",D>L.length?e.jsxs(e.Fragment,{children:["top ",e.jsx("strong",{children:L.length})," of ",e.jsx("strong",{children:D})]}):e.jsx("strong",{children:L.length})]}),e.jsx("ul",{className:"av-subdetails-body",children:L.map(ee=>e.jsxs("li",{children:[ee.name," · ",ee.answerCount," ",ks(ee.answerCount,"answer","answers")]},ee.name))})]}))}return $.length>0&&q.push(e.jsxs("details",{className:"av-subdetails",children:[e.jsxs("summary",{children:["Other sites cited: ",fo($.length,V)]}),e.jsx("ul",{className:"av-subdetails-body",children:$.map(D=>e.jsxs("li",{children:[e.jsxs("span",{children:[Cp(D)," · ",oi(D.surfaceClass)," · ",D.citationCount," ",ks(D.citationCount,"citation","citations")]}),D.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:D.sampleUrls.map(ee=>e.jsx("li",{className:"break-all",children:ee},ee))}):null]},D.domain))})]})),e.jsxs("section",{"aria-labelledby":f,"aria-busy":h,className:"overview-brief",children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:f,className:"av-card-title",children:"Competitors over time"}),e.jsx(Oe,{text:I?`${Np[I]} ${go}`:go})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsx("p",{className:"av-card-meta",children:K}),e.jsx(pa,{label:"Competitors over time window",className:"flex-wrap",options:bp,value:t,onChange:c})]})]}),e.jsxs("div",{className:"av-card-body space-y-3",children:[p?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:[e.jsx("span",{children:p}),x?e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:x,children:"Retry competitors over time"}):null]}):null,h&&!s&&j.length===0?e.jsx("div",{role:"status","aria-live":"polite",className:"h-24 animate-pulse rounded-md bg-surface",children:e.jsx("span",{className:"sr-only",children:"Loading competitors over time"})}):s||C.length>0?e.jsxs("table",{className:"av-grid av-grid-brands","aria-label":"Competitors over time",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Brand"})}),e.jsx("th",{scope:"col",className:"av-brand-type",children:"Type"}),e.jsx("th",{scope:"col",children:"Mention share"}),e.jsx("th",{scope:"col",children:"Named"}),e.jsx("th",{scope:"col",children:"Cited"}),se?e.jsx("th",{scope:"col",className:"av-brand-actions",children:e.jsx("span",{className:"sr-only",children:"Actions"})}):null]})}),e.jsxs("tbody",{children:[s?e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:s.project.label.trim()?e.jsxs(e.Fragment,{children:[s.project.label.trim()," ",e.jsx("span",{className:"av-of",children:"(you)"})]}):"You"}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:"Your brand"}),e.jsx("td",{children:e.jsx(yo,{percent:s.project.shareOfVoice,state:g,toneClass:B})}),e.jsx("td",{children:e.jsx(On,{count:s.project.mentionCount,of:F,state:g,toneClass:B})}),e.jsx("td",{children:e.jsx(On,{count:s.project.citationCount,of:z,state:g,toneClass:B})}),se?e.jsx("td",{className:"av-brand-actions"}):null]}):null,C.map(D=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:e.jsx(xc,{row:D,aliases:D.pinned?a[D.domain]:void 0,autoAliases:D.pinned?r[D.domain]:void 0})}),e.jsx("td",{className:"av-brand-type text-[13px] text-secondary",children:oi(D.surfaceClass)}),e.jsx("td",{children:e.jsx(yo,{percent:D.shareOfVoice,state:g,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(On,{count:D.mentionCount,of:F,state:g,toneClass:"text-primary"})}),e.jsx("td",{children:e.jsx(On,{count:D.citationCount,of:z,state:g,toneClass:"text-primary"})}),se?e.jsx("td",{className:"av-brand-actions",children:Q(D)}):null]},D.domain))]})]}):null,U.length>0?e.jsx("div",{className:"space-y-1 text-[13px] text-secondary",children:U.map(D=>e.jsx("p",{className:D.className,children:D.text},D.key))}):null]}),e.jsx(Ca,{items:q}),b&&u?e.jsx("div",{className:"border-t border-subtle px-5 py-3",children:e.jsx(Rp,{onAddCompetitor:u})}):null]})}function bo({history:t,maxDots:s=12,signal:n="citations"}){const a=t.slice(-s);if(a.length===0)return e.jsx("span",{className:"text-[13px] text-secondary",children:"No data"});const r=n==="mentions"?"Mention":"Citation",l=n==="mentions"?{cited:"mentioned","not-cited":"not mentioned",lost:"mention lost",emerging:"new mention",pending:"mention pending"}:{cited:"cited","not-cited":"not cited",lost:"citation lost",emerging:"new citation",pending:"citation pending"},i={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},c={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},d=a.length-1,m=new Date(a[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(a[d].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),p=`${a.length} ${a.length===1?"run":"runs"}`,x=a.map((h,y)=>{const f=new Date(h.createdAt).toLocaleDateString();return`${y===d?"Latest run, ":""}${f}: ${l[h.citationState]??h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"inline-flex w-max items-center gap-2 whitespace-nowrap",role:"img","aria-label":`${r} history across ${p}. ${x}`,children:[a.length>1?e.jsx("span",{className:"text-[11px] text-secondary shrink-0","aria-hidden":"true",children:m}):null,e.jsx("div",{className:"flex shrink-0 items-center gap-[3px]",title:p,"aria-hidden":"true",children:a.map((h,y)=>{const f=!!(h.model&&y>0&&a[y-1]?.model&&a[y-1].model!==h.model),b=y===d;return e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 ${c[h.citationState]??"rounded-sm"} ${i[h.citationState]??"bg-mono-700"} ${f?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[l[h.citationState]??h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,f?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[11px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{children:"latest"})]})]})}function ci(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const l=s.get(r.createdAt);l?l.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:l}])=>({runId:l,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const ka="__cited__",Aa="__mentioned__",_s="__mentionShare__";function $s(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Bt(n),end:Bt(a),sweepCount:s.sweepCount??1}}function ja(t,s=new Date){return pd(t,s)}function Ra(t,s=new Date){const n=$s(t);if(!n)return null;const a=ja(n.start,s),r=ja(n.end,s);return a===r?a:`${a} to ${r}`}function Mi(t,s=new Date){const n=$s(t),a=Ra(t,s);return!n||!a?"Sweep date unavailable":`${a} · ${n.sweepCount} ${n.sweepCount===1?"sweep":"sweeps"}`}function Ip(t){const s=$s(t);return s?hd(s.start):""}function Na(t){return t.trim().toLowerCase()}function Tp(t,s={}){return t.map(n=>{const a=n.trim().toLowerCase(),r=(s[n]??[]).map(l=>l.trim().toLowerCase()).filter(Boolean).sort();return a&&r.length>0?`${a}=${r.join("|")}`:a}).filter(Boolean).sort().join(`
|
|
2
|
-
`)}const Mp={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",muse:"Muse",local:"Local"};function ot(t){const s=Na(t);return Mp[s]??t.charAt(0).toUpperCase()+t.slice(1)}function di(t){return Math.round(t*1e3)/10}function ui(t){return t.byProvider??{}}function Lp(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?ka:Aa,m=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(p=>({date:p.startDate,[d]:di(p[m])})),series:[d],hasData:a,singleBucket:r}}const l=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys(ui(d))))].sort();return{rows:t.buckets.map(d=>{const m={date:d.startDate},u=ui(d);for(const p of i){const x=u[p];m[p]=x?di(x[l]):null}return m}),series:i,hasData:a,singleBucket:r}}function gc(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function $p(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function qp(t){return t.servedModelAttribution??{}}function Ep(t){return t.modelServiceMismatch??{}}function Dp(t){return t.modelPointerChanges??{}}function xa(t){return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function wa(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return t.models.length===0?"Unknown model":`${t.models.join(", ")}${t.includesUnknown?" and an unknown model":""}`}}function Op(t){return xa([...t.models,...t.includesUnknown?["an unknown model"]:[]])}function Fp(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 Kp(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:Fp(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Gp(t){const s=[];for(const[n,a]of Object.entries(t)){const r=a.eventTotal??a.events.length;r>a.events.length&&s.push({provider:n,shown:a.events.length,total:r})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function _p(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[_s]:r?.rate==null?null:di(r.rate)}}),n=s.map(a=>a[_s]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[_s],hasData:n.length>0,singleBucket:n.length===1}}function Up(t,s,n){return s==="mentionShare"?_p(t):Lp(t,s,n)}function Bp(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 Vp(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 Qp(t,s,n){const a=n==="mentioned"?"mentionRate":"citationRate";for(let r=t.buckets.length-1;r>=0;r--){const l=ui(t.buckets[r])[s];if(l)return l[a]}return null}function We(t){return Date.parse(t)}function fc(t,s){const n=$s(t);if(!n)return!1;const a=We(s);return a>=We(n.start)&&a<=We(n.end)}function yc(t){return t.basketChanges??[]}function bc(t,s){return s.filter(n=>fc(t,n.at)).sort((n,a)=>We(n.at)-We(a.at))}function dr(t,s){return Na(t)==="perplexity"&&s.status==="known"&&!s.model.includes("/")}function zp(t){return Object.entries(t).filter(([s,n])=>!dr(s,n.configured)).sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>({provider:s,mismatch:n}))}function Hp(t){return[...yc(t)].sort((s,n)=>We(n.at)-We(s.at)).map(s=>({at:Bt(s.at),added:s.added,removed:s.removed}))}function Wp(t,s){const n=[...t.events].sort((r,l)=>We(r.observedAt)-We(l.observedAt));let a=n[0]?.from??t.latestObservation.state;for(const r of n)We(r.observedAt)<=We(s)&&(a=r.to);return a}function vo(t,s,n,a){return{provider:t,at:Bt(s.observedAt),onOrBefore:s.fromPreWindowAnchor===!0,anchorAt:s.anchorObservedAt?Bt(s.anchorObservedAt):null,from:s.from,to:s.to,served:n,reroute:a}}function Yp(t,s){const n=[];for(const[a,r]of Object.entries(t)){const i=s[a]?.events??[],c=new Set(r.events.map(d=>d.observedAt));for(const d of r.events){const m=dr(a,d.to)?i.find(u=>u.observedAt===d.observedAt):void 0;n.push(vo(a,d,m?{from:m.from,to:m.to}:null,!1))}for(const d of i)c.has(d.observedAt)||dr(a,Wp(r,d.observedAt))&&n.push(vo(a,d,null,!0))}return n.sort((a,r)=>We(r.at)-We(a.at)||a.provider.localeCompare(r.provider))}function Jp({latest:t,queryChanges:s,modelRows:n,now:a=new Date}){const r=[...s.map(x=>x.at),...n.map(x=>x.at)];if(r.length===0)return null;const l=x=>t!==void 0&&fc(t,x),i=s.filter(x=>l(x.at)),c=i.reduce((x,h)=>x+h.added.length,0),d=i.reduce((x,h)=>x+h.removed.length,0),m=n.filter(x=>l(x.at)).length,u=t?Ra(t,a):null;if(u===null||c+d+m===0){const x=r.reduce((h,y)=>We(y)>We(h)?y:h);return`No changes since ${ja(x,a)}`}const p=[u];return c>0&&p.push(`${c} ${c===1?"query":"queries"} added`),d>0&&p.push(`${d} ${d===1?"query":"queries"} removed`),m>0&&p.push(`${m} new ${m===1?"model":"models"}`),p.join(" · ")}function Xp(t,s,n,a=null){const r=We(t);if(!Number.isFinite(r))return null;const l=s.filter(m=>We(m)<r);if(l.length>0)return Bt(l.reduce((m,u)=>We(u)>We(m)?u:m));const i=n.map(m=>$s(m)).filter(m=>m!==null).sort((m,u)=>We(m.start)-We(u.start)),c=i.findIndex(m=>We(m.start)<=r&&r<=We(m.end));if(c===-1)return null;const d=i[c];return We(d.start)===r?c>0?i[c-1].end:a&&We(a)<r?Bt(a):null:d.sweepCount===2&&We(d.end)===r?d.start:null}function Zp(t){const s=new Map,n=(a,r)=>{const l=s.get(a);l?l.push(r):s.set(a,[r])};for(const a of[...t].sort((r,l)=>r.revision-l.revision)){const r=We(a.at);for(const l of a.removed)n(l,{at:r,member:!1});for(const l of a.added)n(l,{at:r,member:!0})}return new Map([...s].filter(([,a])=>a.at(-1).member))}function Hn(t,s){let n=!t[0].member;for(const a of t)a.at<=s&&(n=a.member);return n}function ex(t,s,n){return t.some(a=>a.at>s&&a.at<=n)}function mi(t,s){const n=We(s.start),a=We(s.end);return s.sweepCount>2?ex(t,n,a):Hn(t,n)!==Hn(t,a)}function vc(t,s,n,a){const r=We(s),l=We(n),i={added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]},c=new Set;for(const[p,x]of Zp(t)){if(!a(x))continue;c.add(p);const h=Hn(x,r),y=Hn(x,l);h!==y?(y?i.added:i.removed).push(p):(h?i.removedAndAddedBack:i.addedAndRemovedAgain).push(p)}if(c.size===0)return null;const d=p=>[...p.added,...p.removed].some(x=>c.has(x)),m=t.filter(p=>We(p.at)>r&&We(p.at)<=l&&d(p)).sort((p,x)=>We(p.at)-We(x.at)),u=[...new Set(m.flatMap(p=>[...p.added,...p.removed]))].filter(p=>c.has(p));return{changes:m,keys:u,moves:i}}function tx(t,s){if(t.length<2)return null;const n=t[0],a=t.at(-1),r=$s(n),l=$s(a),i=r?.start??n.startDate,c=l?.end??a.endDate,d=vc(s,i,c,m=>Hn(m,We(i))!==Hn(m,We(c))||r!==null&&mi(m,r)||l!==null&&mi(m,l));return!d&&n.queryCount===a.queryCount?null:{...d??{changes:[],keys:[],moves:{added:[],removed:[],removedAndAddedBack:[],addedAndRemovedAgain:[]}},firstCount:n.queryCount,latestCount:a.queryCount}}function jc(t,s){const n=$s(t);if(!n)return null;const a=vc(s,n.start,n.end,r=>mi(r,n));return a?{...a,firstCount:t.queryCount,latestCount:t.queryCount}:null}function Rr(t){return`${t} ${t===1?"query":"queries"}`}function sx(t){const s=[],n=a=>s.length===0?Rr(a):String(a);return t.added.length>0&&s.push(`${n(t.added.length)} added`),t.removed.length>0&&s.push(`${n(t.removed.length)} removed`),t.removedAndAddedBack.length>0&&s.push(`${Rr(t.removedAndAddedBack.length)} removed and added back`),t.addedAndRemovedAgain.length>0&&s.push(`${Rr(t.addedAndRemovedAgain.length)} added and removed again`),xa(s)}function jo(t,s,n,a){return t?s!=="mentionShare"||n!=="non-brand"||!a?!1:t.keys.length>0&&t.keys.every(r=>a(r)==="branded"):!0}const No=320;function wo(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function So(t){return t==="non-brand"?0:t==="branded"?1:2}function nx(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 ax(t){return t.phrase}function Co(t,s){return s==="citations"?t.citationState:t.visibilityState==="pending"||t.answerMentioned==null&&t.visibilityState==null?"pending":t.visibilityState==="visible"||t.answerMentioned===!0?"cited":"not-cited"}function ko(t,s){if(s==="mentions")switch(t){case"cited":return"Mentioned";case"not-cited":return"Not Mentioned";case"pending":return"Pending";case"emerging":return"Newly Mentioned";case"lost":return"No Longer Mentioned"}switch(t){case"cited":return"Cited";case"not-cited":return"Not Cited";case"lost":return"Lost";case"emerging":return"Emerging";case"pending":return"Pending"}}function rx(t,s){return t.map(n=>Nc(n,s))}function Nc(t,s){return s==="citations"?t:{...t,citationState:Co(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Co(n,s)}))}}function Ao(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,l=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",c=l==="cited"||l==="emerging";return r==="lost"||l!==null&&c&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||l!==null&&!c&&i?{key:s,label:`New ${n}`,tone:"positive"}:l===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function ix(t){const s=ci(rx(t,"mentions")),n=ci(t);return[Ao(s,"mentions"),Ao(n,"citations")]}function ox({signal:t}){const s=t.tone==="positive"?"text-positive":t.tone==="negative"?"text-negative":t.tone==="pending"?"text-caution":"text-secondary";return e.jsx("span",{className:s,children:t.label})}function Ro({items:t}){return e.jsx("div",{className:"query-evidence-signals","aria-label":"Latest run mention and citation signals",children:ix(t).map(s=>e.jsx(ox,{signal:s},s.key))})}function wc({queryClass:t,actions:s}){return e.jsxs(e.Fragment,{children:[s?e.jsx("div",{className:"query-evidence-toolbar",children:e.jsxs("div",{className:"query-evidence-actions",children:[!t&&e.jsx(Ll,{}),s]})}):null,t?e.jsx($l,{queryClass:t,manage:!!s}):null]})}function lx({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed",providerSelection:a,onProviderSelectionChange:r,addedQueries:l=[],actions:i,actionPanel:c}){const{openEvidence:d}=Ci(),m=o.useId(),[u,p]=o.useState(new Set),x=xd(),[h,y]=o.useState("mentions"),[f,b]=o.useState(n),[j,k]=o.useState("all"),[$,S]=o.useState(""),g=a??$,v=q=>{S(q),r?.(q)},C=o.useMemo(()=>[...new Set([...t.map(q=>q.provider).filter(Boolean),...g?[g]:[]])].sort(),[t,g]),T=o.useMemo(()=>{const q=new Map;for(const X of t){if(g&&X.provider!==g)continue;const L=X.query,D=X.queryClass??null,ee=s?X.location??null:null,ne=JSON.stringify([L,D,ee]),oe=q.get(ne)??{key:ne,phrase:L,queryClass:D,location:ee,items:[],rawItems:[]};oe.items.push(Nc(X,h)),oe.rawItems.push(X),q.set(ne,oe)}return[...q.values()].sort((X,L)=>So(X.queryClass)-So(L.queryClass))},[t,h,s,g]),I=o.useMemo(()=>T.filter(q=>j==="all"||(j==="unclassified"?q.queryClass===null:q.queryClass===j)),[T,j]),w=wn({rows:I,getSearchText:ax}),V=o.useMemo(()=>{const q=new Map;for(const X of w.filteredRows){const L=q.get(X.queryClass)??new Set;L.add(X.phrase),q.set(X.queryClass,L)}return q},[w.filteredRows]),F=o.useMemo(()=>new Set(l.map(Bn)),[l]),z=x?6:5,B=w.rows.map(q=>q.key),Q=B.length>0&&B.every(q=>u.has(q)),se=q=>{p(X=>{const L=new Set(X);return L.has(q)?L.delete(q):L.add(q),L})},K=h==="mentions"?"mentioned":"cited",U=h==="mentions"?"Mention History":"Citation History",J=h==="mentions"?"mentioned":"cited";return e.jsxs("div",{className:"query-evidence",children:[e.jsx(wc,{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(q=>e.jsx("button",{id:`${m}-${q}`,type:"button",role:"tab","aria-controls":m,"aria-selected":h===q,tabIndex:h===q?0:-1,onClick:()=>y(q),onKeyDown:X=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(X.key))return;X.preventDefault();const L=X.key==="Home"?"mentions":X.key==="End"||q==="mentions"?"citations":"mentions";y(L),document.getElementById(`${m}-${L}`)?.focus()},children:q==="mentions"?"Mentions":"Citations"},q))}),e.jsx(Oe,{text:"Mentions track your brand or domain in answer text. Citations track your domain in source links. Each signal is measured independently."})]}),e.jsxs("div",{className:"query-evidence-display-controls",children:[e.jsxs("label",{className:"query-evidence-preview-toggle",children:[e.jsx("input",{type:"checkbox",checked:f==="detailed",onChange:q=>b(q.target.checked?"detailed":"compact")}),"Show answer previews"]}),e.jsx(P,{type:"button",variant:"ghost",className:"min-h-11",disabled:B.length===0,onClick:()=>{p(q=>{const X=new Set(q);for(const L of B)Q?X.delete(L):X.add(L);return X})},children:Q?"Collapse page":"Expand page"})]})]}),t.length>0||g?e.jsxs("div",{className:"query-evidence-filters",children:[e.jsx(Js,{value:w.query,onChange:w.setQuery,label:"Find a query",placeholder:"Find a query",className:"query-evidence-search"}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Answer engine"}),e.jsxs("select",{value:g,onChange:q=>{v(q.target.value),w.setPage(1)},children:[e.jsx("option",{value:"",children:"All engines"}),C.map(q=>e.jsx("option",{value:q,children:ot(q)},q))]})]}),e.jsxs("label",{className:"query-evidence-filter",children:[e.jsx("span",{className:"sr-only",children:"Query class"}),e.jsxs("select",{value:j,onChange:q=>{k(q.target.value),w.setPage(1)},children:[e.jsx("option",{value:"all",children:"All queries"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]})]}):null,e.jsxs("div",{id:m,role:"tabpanel","aria-labelledby":`${m}-${h}`,children:[e.jsx("div",{className:"query-evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table query-evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),x&&e.jsx("th",{scope:"col","aria-label":"Sentiment",children:e.jsxs("span",{className:"inline-flex items-center",children:["Sentiment",e.jsx(Oe,{text:"Branded query rows show the favorable share of judged answers. Non-brand rows show only their unfavorable and mixed answers. Expanded engine rows show each stored answer’s sentiment; factual and unmentioned answers are not judgments."})]})}),e.jsx("th",{scope:"col",children:U}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Answer"})})]})}),nx(w.rows).map(q=>e.jsxs("tbody",{children:[e.jsx("tr",{className:"query-evidence-group",children:e.jsxs("th",{scope:"rowgroup",colSpan:z,children:[wo(q.queryClass)," (",V.get(q.queryClass)?.size??0,")"]})}),q.rows.map(({key:X,phrase:L,queryClass:D,location:ee,items:ne,rawItems:oe})=>{const we=u.has(X),Y=B.indexOf(X),ue=`${m}-query-${Y}`,he=F.has(Bn(L)),Z=ne.map(re=>re.citationState),me=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))],pe=oe.map(re=>re.sourceSnapshotId).filter(re=>!!re),Ee=ci(ne),Re=ne.filter(re=>re.citationState===gd.cited||re.citationState==="emerging").length;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"query-evidence-row",onClick:()=>se(X),children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("button",{type:"button",className:"query-evidence-query","aria-label":L,"aria-describedby":ue,"aria-expanded":we,onClick:re=>{re.stopPropagation(),se(X)},children:[e.jsx(lc,{size:16,"aria-hidden":"true",className:we?"rotate-90":""}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{children:L}),e.jsxs("span",{id:ue,className:"query-evidence-meta",children:[e.jsx("span",{children:wo(D)}),s&&e.jsx("span",{children:ee??"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:me,label:ko(me,h),className:"rounded-none border-0 bg-transparent p-0 text-sm tracking-normal"}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums","aria-label":`${Re} of ${ne.length} engines ${J}`,title:`${Re} of ${ne.length} engines ${J}`,children:[Re,"/",ne.length]})]})}),x&&e.jsx("td",{children:e.jsx(ql,{queryId:G.length===1?G[0]:null,sourceSnapshotIds:G.length>1?[]:pe,queryClass:D,location:s?ee:void 0})}),e.jsx("td",{children:e.jsx(bo,{history:Ee,signal:h})}),e.jsx("td",{className:"evidence-change-cell",children:he?e.jsx("span",{className:"query-evidence-new",children:"new query"}):e.jsx(Ro,{items:oe})}),e.jsx("td",{})]}),we&&ne.map((re,xe)=>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:ko(re.citationState,h)})}),x&&e.jsx("td",{children:e.jsx(El,{queryId:re.queryId,sourceSnapshotIds:re.sourceSnapshotId?[re.sourceSnapshotId]:[],queryClass:re.queryClass,provider:re.provider,location:re.location??null})}),e.jsx("td",{children:e.jsx(bo,{history:re.runHistory,signal:h})}),e.jsx("td",{className:"evidence-change-cell",children:he?null:e.jsx(Ro,{items:[oe[xe]??re]})}),e.jsx("td",{children:e.jsx(P,{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(dx,{item:re,mode:h,onViewFull:()=>d(re.id)},h)})})]},re.id))]},X)})]},q.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(Gs,{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 ",K==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function cx(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=yd(t),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function hi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function dx({item:t,mode:s,onViewFull:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1);if(s==="mentions")return e.jsx(Po,{item:t,onViewFull:n});const c=t.evidenceUrls.length>0?t.evidenceUrls.map(d=>({uri:d,title:t.groundingSources.find(m=>m.uri===d)?.title})):t.groundingSources;return e.jsxs("div",{className:"query-evidence-preview space-y-3",children:[e.jsx("p",{className:"text-[13px] font-medium text-secondary",children:t.evidenceUrls.length>0?"Cited sources":c.length>0?"Grounding sources":"Cited domains"}),c.length>0?e.jsx("ul",{className:"space-y-4",children:c.slice(0,l?void 0:6).map((d,m)=>e.jsxs("li",{className:"min-w-0",children:[e.jsx(ki,{url:d.uri,title:d.title}),hi(t,fd(d.uri)??"")&&e.jsx("p",{className:"mt-1 text-[13px] text-secondary",children:"Competitor source"})]},`${m}-${d.uri}`))}):t.citedDomains.length>0?e.jsx("ul",{className:"space-y-1 text-sm text-secondary",children:t.citedDomains.slice(0,l?void 0:6).map(d=>e.jsxs("li",{className:"[overflow-wrap:anywhere]",children:[d,hi(t,d)?" · competitor source":""]},d))}):e.jsx("p",{className:"text-sm text-secondary",children:"No cited sources captured for this run."}),(c.length>6||c.length===0&&t.citedDomains.length>6)&&e.jsx(P,{type:"button",variant:"ghost",className:"min-h-11","aria-expanded":l,onClick:()=>i(d=>!d),children:l?"Show fewer sources":"View all sources"}),t.answerSnippet.trim()?e.jsxs("details",{open:a,className:"border-t border-subtle pt-1",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:d=>{d.preventDefault(),r(m=>!m)},children:"Answer text"}),a&&e.jsx(Po,{item:t,onViewFull:n,contextOnly:!0})]}):e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."})]})}function Po({item:t,onViewFull:s,contextOnly:n=!1}){const{matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}=t,c=o.useMemo(()=>cx({matchedTerms:a,mentionedCompetitorDomains:r,mentionedCompetitorTerms:l,recommendedCompetitors:i}),[a,r,l,i]);if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-sm text-secondary",children:"No answer text captured for this run."});const m=t.answerSnippet.length>No;return e.jsxs("div",{className:"query-evidence-preview space-y-3",children:[!n&&e.jsx("p",{className:"text-[13px] font-medium text-secondary",children:"Answer text"}),e.jsx(Ti,{headingLevel:4,highlightGroups:c,previewLength:No,children:t.answerSnippet}),(!n&&t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("dl",{className:"space-y-2 text-[13px] leading-6 text-secondary",children:[!n&&t.citedDomains.length>0&&e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Cited domains"}),e.jsxs("dd",{className:"flex flex-wrap gap-x-3 gap-y-1",children:[t.citedDomains.slice(0,6).map(u=>e.jsxs("span",{className:"[overflow-wrap:anywhere]",children:[u,hi(t,u)?" · competitor source":""]},`c-${u}`)),t.citedDomains.length>6&&e.jsxs("span",{children:["+",t.citedDomains.length-6," more"]})]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Competitors in answer"}),e.jsxs("dd",{className:"flex flex-wrap gap-x-3 gap-y-1",children:[t.mentionedCompetitorDomains.slice(0,4).map(u=>e.jsx("span",{className:"[overflow-wrap:anywhere]",children:u},`co-${u}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]})]}),m&&e.jsx(P,{type:"button",variant:"ghost",className:"min-h-11",onClick:u=>{u.stopPropagation(),s()},children:"View full answer"})]})}function Fa({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}function gr({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:l=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(i=>e.jsx("button",{type:"button","aria-pressed":s===i,disabled:l,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>{i!==s&&bd("window"),n(i)},children:r?r(i):i},i))})}const Pr=lt[0],Ir=lt[1],Io=lt[2],To=lt[3],ux=["both","server","ga4"],Mo={fontSize:11,paddingTop:6},Lo=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),$o=t=>typeof t=="number"?sr(Math.round(t)):String(t),rs=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function Tr(t,s){if(!t||s<2)return Array(s).fill(null);const n=t.endIndex-t.startIndex;if(n<=0)return Array(s).fill(null);const a=(t.end-t.start)/n;return Array.from({length:s},(r,l)=>l<t.startIndex||l>t.endIndex?null:t.start+(l-t.startIndex)*a)}function Mr({label:t,value:s,caption:n,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx(Oe,{text:a})]}),e.jsx("p",{className:"text-xl font-semibold text-primary tabular-nums",children:s}),e.jsx("p",{className:"text-xs text-muted mt-0.5",children:n})]})}function mx(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 hx({projectName:t,sinceMinutes:s}){const[n,a]=o.useState(!0),[r,l]=o.useState(!0),[i,c]=o.useState("both"),d=np(t,{sinceMinutes:s,granularity:"day",limit:1}),m=ap(t),p=qe({...Dl({client:W,path:{name:t}}),enabled:!!t,staleTime:vn}).data?.connected===!0,x=qe({...Ol({client:W,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&p,staleTime:vn}),h=o.useMemo(()=>d.data?.series?.points??[],[d.data]),y=o.useMemo(()=>{const T=x.data;return new Map((T?.days??[]).map(I=>[I.date,I.sessions]))},[x.data]),f=o.useMemo(()=>{const T=w=>w.measured!==!1;if(h.length===0||T(h[0]))return null;const I=h.findIndex(T)-1;return I<0?{from:h[0].bucket,to:h[h.length-1].bucket}:{from:h[0].bucket,to:h[I].bucket}},[h]),b=d.data?.series?.coverageStart??null,j=d.data?.series?.trends,k=o.useMemo(()=>{const T=Tr(j?.crawlerContentHits,h.length),I=Tr(j?.aiUserFetchHits,h.length),w=Tr(j?.aiReferralLandedHits,h.length);return h.map((V,F)=>({...V,crawlerContentHits:V.measured!==!1?rs(V.crawlerContentHits):null,aiUserFetchHits:V.measured!==!1?rs(V.aiUserFetchHits):null,aiReferralLandedHits:V.measured!==!1?rs(V.aiReferralLandedHits):null,ga4Visits:y.get(V.bucket)??null,crawlTrend:T[F],fetchTrend:I[F],visitTrend:w[F]}))},[h,y,j]),$=d.data?.totals,S=$&&{crawlers:rs($.crawlerContentHits),fetches:rs($.aiUserFetchHits),visits:rs($.aiReferralLandedHits)},g=o.useMemo(()=>h.reduce((T,I)=>({crawlers:T.crawlers+rs(I.crawlerContentHits),fetches:T.fetches+rs(I.aiUserFetchHits),visits:T.visits+rs(I.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[h]),v=S??g,C=v.crawlers>0||v.fetches>0||v.visits>0;if(d.isLoading)return e.jsx(je,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(d.isError)return e.jsxs(je,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!C){const T=m.data?.sources,I=T!==void 0&&T.length===0,w=!I&&b===null;return e.jsxs(je,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:I?"No server-side traffic source connected yet.":w?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:I?"Connect a traffic source to see how AI engines read this site over time.":w?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Mr,{label:"AI crawlers",value:sr(v.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(Mr,{label:"AI page fetches",value:sr(v.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(Mr,{label:"AI visitors",value:sr(v.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),h.length>0&&e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-xs text-muted",children:[e.jsx("span",{className:"text-secondary font-semibold",children:"Latest day (UTC)"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:rs(h[h.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:rs(h[h.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:rs(h[h.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:y.get(h[h.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(Oe,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:T=>a(T.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:T=>l(T.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Xs,{width:"100%",height:206,children:e.jsxs(Zs,{data:k,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(va,{stroke:ya,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Ut,stroke:us,tickFormatter:Sn,minTickGap:28}),e.jsx(tn,{tick:Ut,stroke:us,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:Pt,formatter:$o}),f&&e.jsx(ni,{x1:f.from,x2:f.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(cr,{wrapperStyle:Mo,iconType:"plainline",iconSize:14,formatter:T=>Lo.has(T)?"":T}),e.jsx(Ws,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Pr,fill:Pr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Ws,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Ir,fill:Ir,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Ks,{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(Ks,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Ir,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(Oe,{text:"Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other."})]}),e.jsx(gr,{windows:ux,value:i,onChange:c,label:"Visit measurement source",formatOption:T=>T==="ga4"?"GA4":T==="both"?"Both":"Server"})]}),e.jsx(Xs,{width:"100%",height:176,children:e.jsxs(Zs,{data:k,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(va,{stroke:ya,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Ut,stroke:us,tickFormatter:Sn,minTickGap:28}),e.jsx(tn,{tick:Ut,stroke:us,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:Pt,formatter:$o}),f&&e.jsx(ni,{x1:f.from,x2:f.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(cr,{wrapperStyle:Mo,iconType:"plainline",iconSize:14,formatter:T=>Lo.has(T)?"":T}),i!=="ga4"&&e.jsx(Ks,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Io,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Ks,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:To,strokeWidth:1.8,strokeDasharray:"5 3",dot:mx(k.map(T=>T.ga4Visits),To)}),r&&i!=="ga4"&&e.jsx(Ks,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Io,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const px=6,Wn="__other__",_n="_socialTotal";function xx(t,s=px){const n=new Map;for(const u of t)n.set(u.source,(n.get(u.source)??0)+u.sessions);const a=[...n.entries()].sort((u,p)=>p[1]!==u[1]?p[1]-u[1]:u[0].localeCompare(p[0])),r=a.slice(0,s),l=new Set(r.map(([u])=>u)),i=Math.max(0,a.length-s),c=new Map;for(const u of t){let p=c.get(u.date);p||(p={date:u.date,[_n]:0},c.set(u.date,p));const x=l.has(u.source)?u.source:Wn;p[x]=(p[x]??0)+u.sessions,p[_n]=(p[_n]??0)+u.sessions}const d=[...c.values()].sort((u,p)=>String(u.date).localeCompare(String(p.date))),m=r.map(([u])=>u);return i>0&&m.push(Wn),{data:d,sources:m,otherCount:i}}function Un(t){return t.replace(/\+/g," ")}function Sc(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const qo="_totalSessions",Eo="_organicSessions";function gx(t,s){const n=new Map;for(const i of s)n.set(i.date,{[qo]:i.sessions,[Eo]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[qo]:0,[Eo]:0},n.set(i.date,c));for(const d of i.bySource)c[d.source]=(c[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([i],[c])=>i.localeCompare(c)).map(([i,c])=>({date:i,...c})),r=a.map(i=>i.date),l=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:l}}const fx=["7d","30d","90d"],yx={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Hs=lt,pi=ms.textDim,Cc=ms.textFaint,aa=25;function bx(t){return rc(t.landingPage)}const vx=25,jx=10,Lr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Ka(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function kc(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Nx({projectName:t}){const{data:s,isLoading:n,isError:a}=rp(t);if(n)return e.jsx(je,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(je,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!ie()&&e.jsx(Ms,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(je,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ie()&&e.jsxs(e.Fragment,{children:[e.jsx(Ms,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(je,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(l=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(Ne,{tone:ip(l.status),children:l.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:l.lastSyncedAt?kc(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ie()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Ms,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function wx({projectName:t}){const[s,n]=o.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Nx,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(gr,{windows:fx,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(Sx,{projectName:t,window:s}),e.jsx(hx,{projectName:t,sinceMinutes:yx[s]})]})}function Sx({projectName:t,window:s}){const n=hs(),a=s??"30d",[r,l]=o.useState(null),[i,c]=o.useState(null),[d,m]=o.useState(!0),[u,p]=o.useState(!1),[x,h]=o.useState(!1),[y,f]=o.useState(null),[b,j]=o.useState(null),[k,$]=o.useState("sessions"),[S,g]=o.useState("desc"),[v,C]=o.useState("sessions"),[T,I]=o.useState("desc"),[w,V]=o.useState("sessions"),[F,z]=o.useState("desc"),[B,Q]=o.useState("sessions"),[se,K]=o.useState("desc"),[U,J]=o.useState(Lr),[q,X]=o.useState([]),[L,D]=o.useState([]),[ee,ne]=o.useState(!1);async function oe(te){m(!0),f(null);try{const _e=await n.fetchQuery({...Dl({client:W,path:{name:t}}),staleTime:vn});if(te.current)return;if(l(_e),!_e.connected){c(null),J(Lr),X([]),D([]),m(!1);return}const Pe=a==="all"?void 0:a,ve=await n.fetchQuery({...vd({client:W,path:{name:t},query:Pe?{window:Pe}:void 0}),staleTime:vn}),Tt=ve.windowStart||ve.windowEnd?{...ve.windowStart?{startDate:ve.windowStart}:{},...ve.windowEnd?{endDate:ve.windowEnd}:{}}:void 0,[Xt,Zt,Ot]=await Promise.all([n.fetchQuery({...Ol({client:W,path:{name:t},query:Pe?{window:Pe}:void 0}),staleTime:vn}).catch(()=>Lr),n.fetchQuery({...jd({client:W,path:{name:t},query:Pe?{window:Pe}:void 0}),staleTime:vn}).catch(()=>[]),n.fetchQuery({...Nd({client:W,path:{name:t},query:Tt}),staleTime:vn}).catch(()=>[])]);if(te.current)return;c(ve),J(Xt),X(Zt),D(Ot),m(!1)}catch(_e){if(te.current)return;f(_e instanceof Error?_e.message:"Failed to load GA4 data"),m(!1)}}o.useEffect(()=>{const te={current:!1};return oe(te),()=>{te.current=!0}},[t,a,n]);async function we(){p(!0),f(null),j(null);try{const te=await Fl(t);j(`Synced ${te.rowCount.toLocaleString()} page rows, ${te.aiReferralCount.toLocaleString()} AI and ${te.socialReferralCount.toLocaleString()} social referral rows (${te.days} days)`),await $t(n,"ga"),await oe({current:!1})}catch(te){f(te instanceof Error?te.message:"Sync failed")}finally{p(!1)}}async function Y(){h(!0),f(null),j(null);try{await wd(t),await $t(n,"ga"),l({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),j("GA4 disconnected")}catch(te){f(te instanceof Error?te.message:"Disconnect failed")}finally{h(!1)}}function ue(te){G.setPage(1),k===te?g(_e=>_e==="desc"?"asc":"desc"):($(te),g("desc"))}function he(te){v===te?I(_e=>_e==="desc"?"asc":"desc"):(C(te),I("desc"))}function Z(te){w===te?z(_e=>_e==="desc"?"asc":"desc"):(V(te),z("desc"))}const me=o.useMemo(()=>i?.topPages?[...i.topPages].sort((te,_e)=>{const Pe=te[k],ve=_e[k];return typeof Pe=="string"&&typeof ve=="string"?S==="asc"?Pe.localeCompare(ve):ve.localeCompare(Pe):S==="asc"?Pe-ve:ve-Pe}):[],[i?.topPages,k,S]),G=wn({rows:me,getSearchText:te=>rc(te.landingPage),pageSize:jx}),pe=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((te,_e)=>{const Pe=te[v],ve=_e[v];return typeof Pe=="string"&&typeof ve=="string"?T==="asc"?Pe.localeCompare(ve):ve.localeCompare(Pe):T==="asc"?Pe-ve:ve-Pe}):[],[i?.aiReferrals,v,T]),Ee=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((te,_e)=>{const Pe=te[B],ve=_e[B];return typeof Pe=="string"&&typeof ve=="string"?se==="asc"?Pe.localeCompare(ve):ve.localeCompare(Pe):se==="asc"?Pe-ve:ve-Pe}):[],[i?.aiReferralLandingPages,B,se]),Re=wn({rows:Ee,getSearchText:bx,pageSize:vx}),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 xe(te){Re.setPage(1),B===te?K(_e=>_e==="desc"?"asc":"desc"):(Q(te),K("desc"))}const Ae=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((te,_e)=>{const Pe=te[w],ve=_e[w];return typeof Pe=="string"&&typeof ve=="string"?F==="asc"?Pe.localeCompare(ve):ve.localeCompare(Pe):F==="asc"?Pe-ve:ve-Pe}):[],[i?.socialReferrals,w,F]),{socialChartData:et,socialChartSources:Le,socialOtherCount:O}=o.useMemo(()=>{const te=xx(L);return{socialChartData:te.data,socialChartSources:te.sources,socialOtherCount:te.otherCount}},[L]),{chartData:ke,chartSources:A,dateRange:be}=o.useMemo(()=>{const te=gx(U,q);return{chartData:te.data,chartSources:te.sources,dateRange:te.dateRange}},[U,q]);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()||Ls()?e.jsx(je,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Cx,{projectName:t,onConnected:()=>{(async()=>(await $t(n,"ga"),await oe({current:!1})))()}});const Ke=i?.organicSharePctDisplay??"0%",Ve=i?.channelBreakdown?.organic.sharePctDisplay??Ke,Ge=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,ge=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,vt=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Qe=i?.paidAiSessionsBySession??0,Je=i?.paidAiSharePctBySessionDisplay??"0%",Dt=i?new Set(i.aiReferrals.map(te=>te.source.toLowerCase())).size:0,ct=pe[0]??null,at=i?.totalDirectSessions??0,pt=i?.directSharePctDisplay??"0%",Ct=i?.channelBreakdown?.direct.sessions??at,It=i?.channelBreakdown?.direct.sharePctDisplay??pt,He=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,R=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",$e=i?.socialSessions??0,Ie=i?.socialSharePctDisplay??"0%",Fe=i?.channelBreakdown?.social.sessions??$e,dt=i?.channelBreakdown?.social.sharePctDisplay??Ie,ze=i?new Set(i.socialReferrals.map(te=>te.source.toLowerCase())).size:0,yt=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()&&!Ls()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:u,onClick:Ze(we),children:[e.jsx(ba,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Ze(Y),children:[e.jsx(Vh,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"mb-4 flex items-start justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Oe,{text:`Aggregated traffic metrics from Google Analytics 4.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]})}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx($r,{value:Ka(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx($r,{value:Ka(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Ke} of total`,tone:"positive"}),e.jsx($r,{value:i.totalUsers===null?"—":Ka(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!ie()&&!Ls()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:u,onClick:Ze(we),children:[e.jsx(ba,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Oe,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),be&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(be.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(be.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),ke.length>0&&e.jsxs(je,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:A.length>0?"AI vs. total sessions":"All sessions (baseline)"}),A.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),A.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:ke,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:us},tickFormatter:Sn}),e.jsx(tn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ns,labelFormatter:Pt,formatter:(te,_e)=>{const Pe=typeof te=="number"?te.toLocaleString():String(te??0),ve=String(_e??"");return ve==="_totalSessions"?[Pe,"Total Sessions"]:ve==="_organicSessions"?[Pe,"Organic Sessions"]:[Pe,ve]}}),e.jsx(cr,{wrapperStyle:{fontSize:11,color:ms.text},formatter:te=>te==="_totalSessions"?"Total Sessions":te==="_organicSessions"?"Organic Sessions":te}),e.jsx(Ws,{type:"monotone",dataKey:"_totalSessions",stroke:ms.textFaint,fill:ms.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),A.map((te,_e)=>e.jsx(Ws,{type:"monotone",dataKey:te,stackId:"ai",stroke:Hs[_e%Hs.length],fill:Hs[_e%Hs.length],fillOpacity:.4,strokeWidth:1.5},te))]})})})]}),e.jsxs(je,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(xs,{label:"Organic",value:Ve,hint:`${Ge.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions from Google organic search (sessionDefaultChannelGrouping = 'Organic Search'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(xs,{label:"Social",value:dt,hint:`${Fe.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(xs,{label:"Direct",value:It,hint:`${Ct.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(xs,{label:"Visitors from AI (at least)",value:vt,hint:Qe>0?`${ge.toLocaleString()} sessions · ${Qe.toLocaleString()} paid`:`${ge.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(xs,{label:"Other channels",value:R,hint:`${He.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),ct&&e.jsxs("div",{className:"mt-4 rounded-lg border border-positive-800/40 bg-positive-500/6 px-4 py-3 text-sm text-positive-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:ct.source})," via ",ct.medium,", accounting for ",ct.sessions.toLocaleString()," sessions.",Qe>0&&e.jsxs("span",{children:[" Paid AI: ",Qe.toLocaleString()," sessions (",Je,")."]})]})]}),e.jsxs(je,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${Dt} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(is,{label:"Source",sortKey:"source",current:v,dir:T,onSort:he,align:"left"}),e.jsx(is,{label:"Medium",sortKey:"medium",current:v,dir:T,onSort:he,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:v,dir:T,onSort:he,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:pe.map(te=>e.jsx(Ax,{referral:te},`${te.source}:${te.medium}:${te.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:re})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Js,{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(is,{label:"Landing Page",sortKey:"landingPage",current:B,dir:se,onSort:xe,align:"left"}),e.jsx(is,{label:"Source",sortKey:"source",current:B,dir:se,onSort:xe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:B,dir:se,onSort:xe,align:"right"})]})}),e.jsx("tbody",{children:Re.rows.map(te=>e.jsx(Rx,{row:te},`${te.landingPage}:${te.source}:${te.medium}:${te.sourceDimension}`))})]})}),e.jsx(Gs,{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(Oe,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(xs,{label:"Social Sessions",value:Ka($e),hint:`${$e.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(xs,{label:"Share of Traffic",value:Ie,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(xs,{label:"Platforms",value:String(ze),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),yt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-info-800/40 bg-info-500/6 px-4 py-3 text-sm text-info-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-info-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${yt.source} via ${yt.medium}`,children:Sc(Un(yt.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:yt.medium,children:["via ",Un(yt.medium)," · ",yt.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(xs,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(xs,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(xs,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),et.length>0&&e.jsxs(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),O>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Le.length-1," sources · ",O," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:et,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:us},tickFormatter:Sn}),e.jsx(tn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ns,labelFormatter:Pt,formatter:(te,_e)=>{const Pe=typeof te=="number"?te.toLocaleString():String(te??0),ve=String(_e??"");if(ve===_n)return[Pe,"Total Social"];if(ve===Wn){const Tt=`Other (${O} source${O===1?"":"s"})`;return[Pe,Tt]}return[Pe,Un(ve)]}}),e.jsx(Ws,{type:"monotone",dataKey:_n,stroke:Cc,fill:ms.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Le.map((te,_e)=>{const ve=te===Wn?pi:Hs[_e%Hs.length];return e.jsx(Ws,{type:"monotone",dataKey:te,stackId:"social",stroke:ve,fill:ve,fillOpacity:.4,strokeWidth:1.5},te)})]})})}),e.jsx(Ix,{sources:Le,otherCount:O})]}),e.jsxs(je,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Ae.length>aa&&!ee?`Top ${aa} 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(is,{label:"Source",sortKey:"source",current:w,dir:F,onSort:Z,align:"left"}),e.jsx(is,{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(is,{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:(ee?Ae:Ae.slice(0,aa)).map(te=>e.jsx(Px,{referral:te},`${te.source}:${te.medium}:${te.channelGroup}`))})]})}),Ae.length>aa&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>ne(te=>!te),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:ee?`Show top ${aa}`:`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(Oe,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx(Js,{value: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(is,{label:"Landing Page",sortKey:"landingPage",current:k,dir:S,onSort:ue,align:"left"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:k,dir:S,onSort:ue,align:"right"}),e.jsx(is,{label:"Organic",sortKey:"organicSessions",current:k,dir:S,onSort:ue,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:G.rows.map(te=>e.jsx(kx,{page:te},te.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(Gs,{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 ${kc(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Cx({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 k=j.result;try{const $=JSON.parse(k);if(!$.client_email||!$.private_key){p("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),c(null);return}c(k)}catch{p("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},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 Sd(t,{propertyId:n.trim(),keyJson:i});try{await Fl(t)}catch{}s()}catch(f){p(f instanceof Error?f.message:"Failed to connect GA4")}finally{m(!1)}}return e.jsxs(je,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),u&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:u}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:f=>a(f.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:x,type:"file",accept:".json,application/json",onChange:h,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>x.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(Qh,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(P,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:Ze(y),children:d?"Connecting & syncing…":"Connect GA4"})]})}function is({label:t,sortKey:s,current:n,dir:a,onSort:r,align:l}){const i=n===s;return e.jsx("th",{className:`py-1 ${l==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>r(s),"aria-label":`Sort by ${t}${i?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,i&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Ac={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function $r({value:t,label:s,subtitle:n,tone:a}){return e.jsxs("div",{className:"rounded-lg bg-surface border border-default px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${Ac[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function xs({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Oe,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Ac[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function kx({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 Rc={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Pc={session:"Detected via GA4 sessionSource (referrer or utm_source for this session)",first_user:"Detected via GA4 firstUserSource (referrer from the user's first-ever visit)",manual_utm:"Detected via GA4 sessionManualSource (explicit utm_source parameter for the session)"};function Ax({referral:t}){const s=tt(t.share),n=Rc[t.sourceDimension]??t.sourceDimension,a=Pc[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",l=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:l,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:a,children:n})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:s})]})}function Rx({row:t}){const s=Rc[t.sourceDimension]??t.sourceDimension,n=Pc[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"max-w-[400px] py-1.5 text-neutral",children:e.jsx(ar,{value:t.landingPage,className:"whitespace-nowrap"})}),e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()})]})}function Px({referral:t}){const s=tt(t.share),n=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Un(t.source),r=Un(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:a}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:n})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:s})]})}function Ix({sources:t,otherCount:s}){const n=[{key:_n,color:Cc,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Wn)n.push({key:Wn,color:pi,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Un(r);n.push({key:r,color:Hs[a%Hs.length]??pi,label:Sc(l,32),tooltip:l})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function Tx(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 Mx="Search Console is not connected yet. Your Canonry team can set this up.",Lx=["7d","30d","90d","all"],Ga=500,Do=[{key:"clicks",label:"Clicks",color:lt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:lt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Jn.caution,format:t=>tt(t)},{key:"position",label:"Avg position",color:lt[2],inverted:!0,format:t=>t.toFixed(1)}],Qs=25,$x="canonry:google-oauth-complete";function qx(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 Ex(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,l=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,c=`${r.startDate} to ${r.endDate}`,d=`Tile percentages compare these ${s} ${l} (${c}) with the ${s} ${l} before them (${i}).`;return n!=="split-window"?d:`${d} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function Oo(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Fo(t){const s=Number(t.errors??0),n=Number(t.warnings??0);return[s>0?`${s} error${s===1?"":"s"}`:"",n>0?`${n} warning${n===1?"":"s"}`:""].filter(Boolean).join(" · ")}function Ko(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Dx({projectName:t,refreshNonce:s}){const n=hs(),{isAdmin:a}=nn(),r=Ls(),[l,i]=o.useState(!1),[c,d]=o.useState([]),[m,u]=o.useState([]),[p,x]=o.useState([]),[h,y]=o.useState(null),[f,b]=o.useState([]),[j,k]=o.useState([]),[$,S]=o.useState(null),[g,v]=o.useState(""),[C,T]=o.useState(""),[I,w]=o.useState("30"),[V,F]=o.useState(!1),[z,B]=o.useState("30d"),[Q,se]=o.useState(["clicks","impressions"]),[K,U]=o.useState(!0),[J,q]=o.useState(null),[X,L]=o.useState(0),[D,ee]=o.useState({startDate:"",endDate:"",query:"",page:""}),[ne,oe]=o.useState(0),[we,Y]=o.useState(!1),[ue,he]=o.useState(0),[Z,me]=o.useState(!1),[G,pe]=o.useState(""),[Ee,Re]=o.useState(!0),[re,xe]=o.useState(!1),[Ae,et]=o.useState(!1),[Le,O]=o.useState(!1),[ke,A]=o.useState(!1),[be,Ke]=o.useState(!1),[Ve,Ge]=o.useState(!1),[ge,vt]=o.useState(null),[Qe,Je]=o.useState(!1),[Dt,ct]=o.useState(!1),[at,pt]=o.useState(null),[Ct,It]=o.useState(null),[He,R]=o.useState([]),[$e,Ie]=o.useState(new Set),[Fe,dt]=o.useState({}),[ze,yt]=o.useState(new Set),[te,_e]=o.useState(""),[Pe,ve]=o.useState(null),[Tt,Xt]=o.useState(""),[Zt,Ot]=o.useState(!1),[ut,es]=o.useState(!1),[it,gs]=o.useState(!1),[ps,Bs]=o.useState(!1),[bt,Vs]=o.useState("indexed"),[Mt,as]=o.useState(null),Vt=!!(D.query.trim()||D.page.trim()||Mt),xt=Mt!==null,ts=o.useMemo(()=>{if(!Mt)return p;const{key:N,dir:H}=Mt;return[...p].sort((ce,Ce)=>{const rt=N===jn.CTR?Number.isFinite(ce.ctr)?ce.ctr:0:ce[N],nt=N===jn.CTR?Number.isFinite(Ce.ctr)?Ce.ctr:0:Ce[N];return H==="asc"?rt-nt:nt-rt})},[p,Mt]),Qt=wn({rows:ts,pageSize:Os}),fs=Z?Qt.rows:ts,zt=wn({rows:(at??[]).filter(N=>N.path.toLowerCase().includes(te.trim().toLowerCase())),pageSize:Os}),[gt,Lt]=o.useState([]),[Nt,ys]=o.useState(null),[bs,_]=o.useState(1),ae=o.useMemo(()=>{if(gt.length<2)return null;const N=gt[gt.length-1],H=gt[gt.length-2];return{indexed:N.indexed-H.indexed,notIndexed:N.notIndexed-H.notIndexed}},[gt]);o.useEffect(()=>{_(1)},[ge,bt,Nt]);const de=o.useMemo(()=>Nt?(ge?.reasonGroups??[]).find(N=>N.reason===Nt):void 0,[ge,Nt]),le=o.useMemo(()=>ge?bt==="indexed"?ge.indexed:bt==="deindexed"?ge.deindexed:bt==="notIndexed"?Nt?de?.urls??[]:(ge.reasonGroups??[]).length===0?ge.notIndexed:[]:[]:[],[ge,bt,Nt,de]),Te=Math.max(1,Math.ceil(le.length/Qs)),Ue=Math.min(Math.max(1,bs),Te),mt=(Ue-1)*Qs,kt=o.useMemo(()=>ge?.indexed.slice(mt,mt+Qs)??[],[ge,mt]),vs=o.useMemo(()=>ge?.notIndexed.slice(mt,mt+Qs)??[],[ge,mt]),E=o.useMemo(()=>ge?.deindexed.slice(mt,mt+Qs)??[],[ge,mt]),Se=o.useMemo(()=>(de?.urls??[]).slice(mt,mt+Qs),[de,mt]),[st,qt]=o.useState(!1),[Ft,Be]=o.useState(null),[wt,qs]=o.useState(null),[Xn,ss]=o.useState(null);function an(N,H){const ce=op(N),Ce=Tx(ce);Ce?(qs(Ce),Be(null)):(qs(null),Be(ce.message||H))}const Kt=c.find(N=>N.connectionType==="gsc"),Es=(Kt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),Ds=He.length>0?He:(at??[]).map(N=>N.path),kn=Ds.filter(N=>at?.some(H=>H.path===N&&H.isSitemapsIndex)).length,Pa=kn===1?"Resubmit sitemap index":kn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Zn=p.length>0||f.length>0||j.length>0,ea=Cd(),rn=kd();async function fr(N,H=!1){if(r){u([]);return}if(!N){u([]),v("");return}et(!0);try{const{sites:ce}=await n.fetchQuery({...Gd({client:W,path:{name:t}}),staleTime:H?0:Yt});u(ce),v(N.propertyId??ce[0]?.siteUrl??""),qs(null)}catch(ce){u([]),an(ce,"Failed to load Search Console properties")}finally{et(!1)}}async function An(N){A(!0);const H=N??ne;try{const ce=Vt?Ga:Os,Ce=Vt?0:H,rt={limit:String(ce)};D.startDate&&(rt.startDate=D.startDate),D.endDate&&(rt.endDate=D.endDate),D.query&&(rt.query=D.query),D.page&&(rt.page=D.page),Ce>0&&(rt.offset=String(Ce)),z&&z!=="all"&&!D.startDate&&(rt.window=z);const nt=await n.fetchQuery({...Id({client:W,path:{name:t},query:rt}),staleTime:Yt}),ht=nt.rows;Vt?(Y(!1),x(ht),he(ht.length),me(!0)):(Y(Ce+ht.length<nt.totalMatching),x(ht),he(0),me(!1))}catch(ce){x([]),Y(!1),he(0),Be(ce instanceof Error?ce.message:"Failed to load GSC performance data")}finally{A(!1)}}async function on(){try{const N={};D.startDate&&(N.startDate=D.startDate),D.endDate&&(N.endDate=D.endDate),z&&z!=="all"&&!D.startDate&&(N.window=z);const H=await n.fetchQuery({...Pd({client:W,path:{name:t},query:N}),staleTime:Yt});y(H)}catch{y(null)}}async function Rn(N=!1){Ke(!0);try{const H=G.trim()||void 0,ce={limit:"20"};H&&(ce.url=H);const[Ce,rt]=await Promise.all([n.fetchQuery({...Fd({client:W,path:{name:t},query:ce}),staleTime:N?0:Yt}),n.fetchQuery({...Kd({client:W,path:{name:t}}),staleTime:N?0:Yt})]);b(Ce),k(rt)}catch(H){b([]),k([]),Be(H instanceof Error?H.message:"Failed to load GSC inspection history")}finally{Ke(!1)}}async function ln(N=!1){Je(!0);try{const[H,ce]=await Promise.all([n.fetchQuery({...Ld({client:W,path:{name:t}}),staleTime:N?0:Yt}),n.fetchQuery({...$d({client:W,path:{name:t}}),staleTime:N?0:Yt}).catch(()=>[])]);vt(H),Lt(ce)}catch(H){vt(null),Lt([]),Be(H instanceof Error?H.message:"Failed to load coverage data")}finally{Je(!1)}}async function cn(N){qt(!0),Be(null);try{const H=await so(t,{urls:N}),{succeeded:ce,failed:Ce,total:rt}=H.summary;De({title:"Indexing requested",detail:Ce===0?`${ce} URL${ce!==1?"s":""} submitted for indexing.`:`${ce}/${rt} submitted successfully, ${Ce} failed.`,tone:Ce===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(H){Be(H instanceof Error?H.message:"Failed to request indexing")}finally{qt(!1)}}async function ta(){qt(!0),Be(null);try{const N=await so(t,{urls:[],allUnindexed:!0}),{succeeded:H,failed:ce,total:Ce}=N.summary;De({title:"Indexing requested",detail:ce===0?`${H} unindexed URL${H!==1?"s":""} submitted for indexing.`:`${H}/${Ce} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(N){Be(N instanceof Error?N.message:"Failed to request indexing")}finally{qt(!1)}}async function dn(){ct(!0),Be(null);try{const N=await Nr(t);n.setQueryData(qd({client:W,path:{name:t}}),N),pt(N.sitemaps),It(N.summary),R(N.preferredSubmissionUrls),Ie(new Set),dt({}),N.sitemaps.length===0&&ss("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(N){Be(N instanceof Error?N.message:"Failed to list sitemaps")}finally{ct(!1)}}async function sa(N){const H=$e.has(N);if(Ie(ce=>{const Ce=new Set(ce);return H?Ce.delete(N):Ce.add(N),Ce}),!(H||Fe[N])){yt(ce=>new Set(ce).add(N));try{const ce=await Nr(t,N);dt(Ce=>({...Ce,[N]:ce.sitemaps}))}catch(ce){Be(ce instanceof Error?ce.message:"Failed to load sitemap files")}finally{yt(ce=>{const Ce=new Set(ce);return Ce.delete(N),Ce})}}}async function js(N){if(!Es||N.length===0)return;const H=[...new Set(N)];es(!0),Be(null),ve({completed:0,total:H.length});let ce=0,Ce=0,rt=0,nt=null;try{for(let Rt=0;Rt<H.length;Rt+=50){const Xe=H.slice(Rt,Rt+50);try{const Me=await Ed(t,Xe);ce+=Me.summary.accepted,Ce+=Me.summary.failed,rt+=Xe.length,ve({completed:rt,total:H.length})}catch(Me){rt+=Xe.length;const Ns=Xe.length,mn=H.length-rt,Tn=Me instanceof Error?Me.message:"The batch request failed",ws=`${ce} accepted, ${Ce} failed, ${Ns} unconfirmed, ${mn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;nt=`Sitemap submission stopped after a batch request failed. ${ws} ${Tn}`,Be(nt),De({title:"Sitemap resubmission partially completed",detail:ws,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const ht=H.length;De({title:Ce===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:Ce===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ce}/${ht} sitemap submissions; ${Ce} failed. Indexing is not guaranteed.`,tone:Ce===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Xt("")}catch(ht){Be(ht instanceof Error?ht.message:"Failed to submit sitemap to Google")}finally{es(!1),ve(null),await dn(),nt&&Be(nt)}}async function Ia(){es(!0);const N=at??[];try{const H=N.filter(Ce=>Ce.isSitemapsIndex),ce=[];for(let Ce=0;Ce<H.length;Ce+=4)(await Promise.all(H.slice(Ce,Ce+4).map(async nt=>{const ht=Fe[nt.path];if(ht)return ht;const Rt=await Nr(t,nt.path);return dt(Xe=>({...Xe,[nt.path]:Rt.sitemaps})),Rt.sitemaps}))).forEach((nt,ht)=>{ce.push(...nt.length>0?nt.map(Rt=>Rt.path):[H[Ce+ht].path])});await js([...N.filter(Ce=>!Ce.isSitemapsIndex).map(Ce=>Ce.path),...ce])}catch(H){Be(H instanceof Error?H.message:"Failed to load sitemap files"),es(!1)}}async function Ta(N){Ot(!0),Be(null);try{await Dd(t,"gsc",N),await $t(n,"google"),d(H=>H.map(ce=>ce.connectionType==="gsc"?{...ce,sitemapUrl:N}:ce)),De({title:"Default sitemap updated",detail:N,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(H){Be(H instanceof Error?H.message:"Failed to set the default sitemap")}finally{Ot(!1)}}async function Ma(N){try{await rn.mutateAsync({projectName:t,projectLabel:t,opts:N?{sitemapUrl:N}:void 0})}catch{}}async function yr(){Re(!0),Be(null);try{const[N,H]=await Promise.all([r||!a?Promise.resolve(null):Kl().catch(()=>null),n.fetchQuery({...Ai({client:W,path:{name:t}}),staleTime:Yt}).catch(()=>[])]);i(!!N?.google?.configured),d(H);const ce=H.find(Ce=>Ce.connectionType==="gsc");await Promise.all([r?Promise.resolve():fr(ce),An(),on(),Rn(),ln(),!r&&ce?.propertyId?dn():Promise.resolve()])}finally{Re(!1)}}o.useEffect(()=>{yr()},[t,s,a]),o.useEffect(()=>{oe(0),q(null),ee(N=>N.startDate||N.endDate?{...N,startDate:"",endDate:""}:N),L(N=>N+1),on()},[z]);const un=o.useRef(!1);o.useEffect(()=>{if(!un.current){un.current=!0;return}oe(0),Qt.setPage(1),An(0)},[X]);function Pn(N){const H=J===N?null:N;q(H),ee(ce=>({...ce,startDate:H??"",endDate:H??""})),L(ce=>ce+1)}const na=o.useRef(!1);o.useEffect(()=>{if(!na.current){na.current=!0;return}oe(0),An(0)},[xt]);async function La(){if(!l){Be("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}xe(!0),Be(null),ss(null);try{let N=function(Me){if(Me.source!==Ce||Me.origin!==rt||!Me.data||typeof Me.data!="object")return;const Ns=Me.data;Ns.type!==$x||Ns.connectionType!=="gsc"||Xe(!0)};const{authUrl:H,redirectUri:ce}=await Md(t,"gsc");if(!H.startsWith("https://accounts.google.com/")){Be("Unexpected OAuth redirect URL. Please try again.");return}const Ce=window.open(H,"_blank","width=600,height=700");if(!Ce){window.location.assign(H);return}const rt=ce?new URL(ce).origin:window.location.origin;let nt=!1,ht=null;const Rt=()=>{ht!==null&&window.clearInterval(ht),window.removeEventListener("message",N)},Xe=async Me=>{if(!nt){nt=!0,Rt(),ss(Me?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await $t(n,"google"),await yr()}finally{ss(null)}}};window.addEventListener("message",N),ss("Finish the Google consent flow in the popup. This page will refresh automatically."),ht=window.setInterval(()=>{Ce.closed&&Xe(!1)},1e3)}catch(N){Be(N instanceof Error?N.message:"Failed to start OAuth flow")}finally{xe(!1)}}async function In(){Be(null),ss(null);try{await Td(t,"gsc"),await $t(n,"google"),d(N=>N.filter(H=>H.connectionType!=="gsc")),u([]),v("")}catch(N){Be(N instanceof Error?N.message:"Failed to disconnect")}}async function $a(){if(g){O(!0),Be(null);try{await _d(t,"gsc",g),await $t(n,"google"),d(N=>N.map(H=>H.connectionType==="gsc"?{...H,propertyId:g}:H)),De({title:"GSC property updated",detail:`${t} is now linked to ${g}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(N){Be(N instanceof Error?N.message:"Failed to save GSC property")}finally{O(!1)}}}async function br(){Be(null),ss(null);try{await ea.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(I,10)||void 0,full:V||void 0}}),await $t(n,"gsc")}catch{}}async function qa(){if(C.trim()){Ge(!0),Be(null),ss(null);try{const N=await Od(t,C.trim());await $t(n,"gsc"),S(N),T(""),await Rn()}catch(N){Be(N instanceof Error?N.message:"Failed to inspect URL")}finally{Ge(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),wt&&e.jsx("div",{className:"mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:wt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:wt.message}),(Mn(wt.enableUrl)||Mn(wt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Mn(wt.enableUrl)&&e.jsx("a",{href:Mn(wt.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),Mn(wt.indexingApiUrl)&&e.jsx("a",{href:Mn(wt.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>qs(null),children:"×"})]})}),Ft&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[Ft,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Be(null),children:"×"})]}),Xn&&e.jsxs("div",{className:"mb-3 rounded-lg border border-positive-800/40 bg-positive-950/20 px-3 py-2 text-sm text-positive",children:[Xn,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>ss(null),children:"×"})]}),Ee?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Kt?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:Kt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",ge?.lastInspectedAt?Jt(ge.lastInspectedAt):"never"]}),!r&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ze(In),children:"Disconnect"})]}):a?e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(Ne,{tone:l?"caution":"negative",children:l?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:l?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[l?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:re,onClick:Ze(La),children:re?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ms,{to:"/settings",children:"Open Settings"})}),!l&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}):e.jsx(je,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:Mx})}),(Kt||Zn)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Oe,{text:`${Ex(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 ${Ga.toLocaleString()} matching rows while the table shows ${Os} per page.`})]}),h?.window?.startDate&&h.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[h.window.startDate," to ",h.window.endDate,(h.window.daysSinceLatestData??0)>0&&` · latest data ${h.window.daysSinceLatestData} day${h.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gr,{windows:Lx,value:z,onChange:N=>{B(N),oe(0),Qt.setPage(1)},label:"Search Console time period",formatOption:N=>N==="all"?"All":N}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ke,onClick:()=>{oe(0),Qt.setPage(1),An(0),on()},children:ke?"Loading…":"Apply filters"})]})]}),h&&h.daily.length>0&&(()=>{const{totals:N,daily:H,trends:ce,periodComparison:Ce}=h,nt=Do.filter(Me=>Q.includes(Me.key)).map(Me=>({dataKey:Me.key,label:Me.label,color:Me.color,axisId:Me.key,inverted:Me.inverted,formatValue:Me.format,trend:K?ce?.[Me.key]??null:null})),ht=Me=>N[Me]??null,Rt=new Map(H.map(Me=>[Me.date,Me])),Xe=H.length===0?[]:Ad(H[0].date,H[H.length-1].date).map(Me=>Rt.get(Me)??{date:Me});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Do.map(Me=>{const Ns=Q.includes(Me.key),mn=ht(Me.key),Tn=mn===null;return e.jsxs("button",{type:"button","aria-pressed":Ns,disabled:Tn,className:`rounded-md border px-3 py-2 text-left transition-colors ${Ns?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Tn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{se(ws=>ws.includes(Me.key)?ws.length===1?ws:ws.filter(vr=>vr!==Me.key):[...ws,Me.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:Ns?Me.color:"transparent",border:`1px solid ${Me.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:Me.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:mn===null?"—":Me.format(mn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:qx(Ce,Me.key,Me.inverted)})]},Me.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:K,onChange:Me=>U(Me.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(oc,{data:Xe,xKey:"date",series:nt,xTickFormatter:Sn,labelFormatter:Pt,onSelectX:Pn,selectedX:J})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:H.map(Me=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":J===Me.date,onClick:()=>Pn(Me.date),children:[Pt(Me.date),": ",Me.clicks," clicks, ",Me.impressions," impressions"]},Me.date))}),J&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Pt(J)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Pn(J),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:D.startDate,onChange:N=>ee(H=>({...H,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:D.endDate,onChange:N=>ee(H=>({...H,endDate:N.target.value}))}),e.jsx(Js,{value:D.query,onChange:N=>ee(H=>({...H,query:N})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Js,{value:D.page,onChange:N=>ee(H=>({...H,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(jn).map(N=>e.jsx("th",{className:"text-right","aria-sort":Mt?.key===N?Mt.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{Qt.setPage(1),as(H=>H?.key===N?H.dir==="desc"?{key:N,dir:"asc"}:null:{key:N,dir:"desc"})},children:[Rd[N],Mt?.key===N?Mt.dir==="desc"?" ↓":" ↑":""]})},N))]})}),e.jsx("tbody",{children:fs.map((N,H)=>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(ar,{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}:${H}`))})]})}),e.jsx(Gs,{page:Z?Qt.page:Math.floor(ne/Os)+1,pageSize:Os,visibleRows:fs.length,totalRows:Z?ue:void 0,hasNextPage:Z?void 0:we,disabled:ke,itemLabel:Z?"matches":"rows",onPageChange:N=>{if(Z){Qt.setPage(N);return}const H=(N-1)*Os;oe(H),An(H)}}),Z&&ue>=Ga?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Ga.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Oe,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ge&&ge.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:st,onClick:()=>{ta()},children:st?"Requesting…":`Request indexing (${ge.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Qe,onClick:()=>{ln(!0)},children:Qe?"Loading…":"Reload saved coverage"})]})]}),ge&&ge.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const N=ge.summary.indexedShare??0,H=ge.summary.notIndexedShare??0,ce=54,Ce=2*Math.PI*ce,rt=Ce*(1-N),nt=Ce*H,ht=Ce*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:ce,fill:"none",stroke:ms.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:Jn.positiveDeep,strokeWidth:"14",strokeDasharray:Ce,strokeDashoffset:rt,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),ge.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:ms.textFaint,strokeWidth:"14",strokeDasharray:`${nt} ${Ce-nt}`,strokeDashoffset:-ht,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-3xl font-bold tabular-nums text-primary",children:tt(ge.summary.indexedShare)}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:ge.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:ge.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(ge.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(ge.reasonGroups??[]).length," ",(ge.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),ge.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:ge.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(N=>{const H=N==="indexed"?ge.indexed.length:N==="notIndexed"?ge.notIndexed.length:ge.deindexed.length,ce=N==="indexed"?"Indexed":N==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":bt===N,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${bt===N?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{Vs(N),ys(null)},children:[ce," (",H,")"]},N)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[bt==="indexed"&&ge.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:kt.map(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))})]}),bt==="notIndexed"&&!Nt&&(ge.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(ge.reasonGroups??[]).map(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:()=>ys(N.reason),onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),ys(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))})]}),bt==="notIndexed"&&!Nt&&(ge.reasonGroups??[]).length===0&&ge.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:vs.map(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))})]}),bt==="notIndexed"&&Nt&&(()=>{const N=(ge.reasonGroups??[]).find(H=>H.reason===Nt);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:()=>ys(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:N.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[N.count," affected page",N.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:st,onClick:()=>{cn(N.urls.map(H=>H.url))},children:st?"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(H=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:H.url}),e.jsx("td",{className:"text-secondary",children:H.crawlTime?H.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:st,onClick:()=>{cn([H.url])},title:"Request indexing",children:"Index"})})]},H.id))})]})]}):null})(),bt==="deindexed"&&ge.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:E.map((N,H)=>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}-${H}`))})]}),(bt==="indexed"&&ge.indexed.length===0||bt==="notIndexed"&&!Nt&&ge.notIndexed.length===0||bt==="deindexed"&&ge.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Gs,{page:Ue,pageSize:Qs,visibleRows:Math.min(Qs,le.length-mt),totalRows:le.length,onPageChange:_,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":ps,onClick:()=>Bs(N=>!N),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:ps?"Hide snapshots":gt.length>0?`View ${gt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",ge.summary.indexed.toLocaleString()," indexed, ",ge.summary.notIndexed.toLocaleString()," not indexed.",ae&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ae.indexed>=0?"+":"",ae.indexed.toLocaleString()," indexed, ",ae.notIndexed>=0?"+":"",ae.notIndexed.toLocaleString()," not indexed."]})]}),ps&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:gt.length>0?e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-right",children:"Indexed"}),e.jsx("th",{className:"text-right",children:"Not indexed"})]})}),e.jsx("tbody",{children:gt.map(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:Qe?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),!r&&e.jsxs(e.Fragment,{children:[e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Oe,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Dt||!Kt?.propertyId,onClick:()=>{dn()},children:Dt?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:Tt,onChange:N=>Xt(N.target.value),onKeyDown:N=>N.key==="Enter"&&void js([Tt.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!Es||ut||!Tt.trim(),onClick:()=>{js([Tt.trim()])},children:ut?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!Es||ut||Ds.length===0,onClick:()=>{js(Ds)},children:ut?"Resubmitting…":Pa}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!Es||ut||!at?.length,onClick:()=>{Ia()},children:"Resubmit all files"}),Ct&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ct.indexes," index",Ct.indexes===1?"":"es",", ",Ct.files," file",Ct.files===1?"":"s"]}),Pe&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Pe.completed,"/",Pe.total]})]}),!Es&&Kt&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:Ze(La),children:"Reconnect"})]}),at&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:at.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Js,{value:te,onChange:N=>{_e(N),zt.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:zt.rows.flatMap(N=>{const H=Oo(N),ce=Fo(N),Ce=Ko(N),rt=Fe[N.path]??[],nt=$e.has(N.path),ht=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(ar,{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":nt,"aria-label":`${nt?"Collapse":"Expand"} files in ${N.path}`,onClick:()=>{sa(N.path)},children:ze.has(N.path)?"Loading…":`${nt?"▾":"▸"} Index${Fe[N.path]?` (${rt.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:Ce}),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:H.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ce||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!Es||ut,onClick:()=>{js([N.path])},children:N.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Kt?.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:Zt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Ta(N.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:rn.isPending,onClick:()=>{Ma(N.path)},children:"Inspect URLs"})]})})]},N.path),Rt=N.isSitemapsIndex&&nt?rt.map(Xe=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(ar,{value:Xe.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Ko(Xe)}),e.jsx("td",{className:"text-secondary",children:Xe.lastSubmitted?Xe.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:Xe.lastDownloaded?Xe.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Oo(Xe).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Fo(Xe)||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!Es||ut,onClick:()=>{js([Xe.path])},children:"Resubmit"}),Kt?.sitemapUrl===Xe.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Zt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Ta(Xe.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:rn.isPending,onClick:()=>{Ma(Xe.path)},children:"Inspect URLs"})]})})]},`${N.path}:${Xe.path}`)):[];return[ht,...Rt]})})]}),e.jsx(Gs,{page:zt.page,pageSize:Os,visibleRows:zt.rows.length,totalRows:zt.totalRows,onPageChange:zt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:C,onChange:N=>T(N.target.value),onKeyDown:N=>N.key==="Enter"&&void qa()}),e.jsx(P,{type:"button",size:"sm",disabled:Ve||!Kt?.propertyId||!C.trim(),onClick:Ze(qa),children:Ve?"Inspecting…":"Inspect URL"})]}),$&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:$.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:$.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:to($.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Jt($.crawlTime)})]})]})]})]}),e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:be,onClick:()=>{Rn(!0)},children:be?"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=>pe(N.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:be,onClick:()=>{Rn(!0)},children:"Apply filter"})]}),f.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Coverage"}),e.jsx("th",{className:"text-left",children:"Mobile"}),e.jsx("th",{className:"text-left",children:"Inspected"})]})}),e.jsx("tbody",{children:f.map(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:to(N.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Jt(N.inspectedAt)})]},N.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),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:Jt(N.transitionDate)})]},`${N.url}:${N.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Kt&&!r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>gs(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 ${it?"rotate-90":""}`,"aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted",children:"Setup & Configuration"})]})}),it&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Oe,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:g,disabled: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(P,{type:"button",size:"sm",variant:"outline",disabled:Ae,onClick:()=>{fr(Kt,!0)},children:Ae?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!g||Le,onClick:Ze($a),children:Le?"Saving…":"Save property"})]})]})]}),e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:I,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:V,onChange:N=>F(N.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:ea.isPending||!Kt.propertyId,onClick:Ze(br),children:ea.isPending?"Queueing…":"Queue sync"}),!Kt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Ox=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Fx({projectName:t,projectId:s}){const n=hs(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),m=qe(Ai({client:W,path:{name:t}})),u=m.data?.find(Y=>Y.connectionType==="gbp"),p=!!u,x=a?{locationName:a}:void 0,h=qe({...Ud({client:W,path:{name:t}}),enabled:p}),y=qe({...Bd({client:W,path:{name:t},query:x}),enabled:p}),f=qe({...Vd({client:W,path:{name:t},query:x}),enabled:p}),b=qe({...Qd({client:W,path:{name:t},query:x}),enabled:p}),j=qe({...zd({client:W,path:{name:t},query:x}),enabled:p}),k=qe({...Hd({client:W,path:{name:t},query:x}),enabled:p}),$=qe({queryKey:["gbp-section-insights",t],queryFn:()=>Wd(t),enabled:p});function S(){$t(n,"gbp")}const g=Et({...Yd(),onSuccess:Y=>{Gl({id:Y.runId,projectId:s,kind:Us["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),De({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=o.useSyncExternalStore(_l,ir,ir),C=Object.values(v.runs).some(Y=>Y.kind===Us["gbp-sync"]&&Y.projectId===s),T=g.isPending||C,I=Et({...Jd(),onSuccess:()=>S()});if(o.useEffect(()=>{if(!a||!h.data)return;const Y=h.data.locations.filter(ue=>ue.selected);(Y.length<=1||!Y.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 Y=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(je,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:Y.map((ue,he)=>e.jsxs("li",{className:"grid grid-cols-[1.5rem_1fr] gap-x-3",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full bg-mono-800 text-xs font-medium tabular-nums text-neutral","aria-hidden":"true",children:he+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ue.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-bg-elevated/80 px-2 py-1 font-mono text-xs text-neutral",children:ue.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ue.note})]})]},ue.title))})]})})}const w=y.data,V=h.data?.locations??[],F=V.filter(Y=>Y.selected),z=f.data?.keywords??[],B=b.data?.lodging??[],Q=j.data?.placeActions??[],se=k.data?.places??[],K=V.length>0?V[0].accountName:u.domain,U=a?V.find(Y=>Y.locationName===a)?.displayName??null:null,J=a?V.filter(Y=>Y.locationName===a):F,q=new Set(J.map(Y=>Y.locationName)),X=B.filter(Y=>q.has(Y.locationName)),L=Q.filter(Y=>q.has(Y.locationName)),D=se.filter(Y=>q.has(Y.locationName)),ee=new Set(F.map(Y=>Y.locationName)),ne=a?z:z.filter(Y=>ee.has(Y.locationName)),oe=!a&&F.length>1,we=($.data??[]).filter(Y=>!Y.dismissed&&Ox.has(Y.type)&&(!U||Y.query===U||Y.query===a||Y.title.startsWith(U)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Oe,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:T,onClick:()=>g.mutate({client:W,path:{name:t},body:{}}),children:T?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[K?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:K})," · "]}):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:Y=>r(Y.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(Y=>e.jsx("option",{value:Y.locationName,children:Y.displayName},Y.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:[we.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),we.map(Y=>e.jsx("div",{className:["insight-card",Xx(Y.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:[Y.title,Y.recommendation?.reason&&e.jsx(Oe,{text:Y.recommendation.reason})]})},Y.id))]}),w&&e.jsx(sg,{performance:w.performance,freshness:w.freshness,timeseries:w.timeseries}),w?.profileCompleteness&&e.jsx(Kx,{summary:w.profileCompleteness}),J.length>0&&e.jsx(Gx,{locations:J,lodging:X,places:D,placeActions:L,expandedLocation:l,onToggleExpanded:Y=>{i(ue=>ue===Y?null:Y)}}),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,Yn.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(Y=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:Y.keyword}),oe&&e.jsx("td",{className:"text-muted",children:V.find(ue=>ue.locationName===Y.locationName)?.displayName??Y.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:Y.valueCount!==null?Y.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",Y.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[Y.periodStart,"–",Y.periodEnd]})]},`${Y.locationName}:${Y.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(Y=>!Y),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",V.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:V.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!ie()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:V.map(Y=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:Y.displayName}),e.jsx("td",{className:"text-muted",children:Y.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(Ne,{tone:Y.selected?"positive":"neutral",children:Y.selected?"Tracked":"Not tracked"})}),!ie()&&e.jsx("td",{className:"text-right",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:I.isPending,onClick:()=>I.mutate({client:W,path:{name:t,locationName:Y.locationName},body:{selected:!Y.selected}}),children:Y.selected?"Untrack":"Track"})})]},Y.id))})]})})]})]})})}function Kx({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:ra(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:ra(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:ra(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:ra(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:ra(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-default py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(Oe,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${Jx(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Gx({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:l}){const i=new Map(s.map(m=>[m.locationName,m])),c=new Map(n.map(m=>[m.locationName,m])),d=new Map;for(const m of a){const u=d.get(m.locationName)??[];u.push(m),d.set(m.locationName,u)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Oe,{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(Ne,{tone:m.selected?"positive":"neutral",children:m.selected?"Tracked":"Not tracked"}),m.openStatus&&m.openStatus!=="OPEN"&&e.jsx(Ne,{tone:m.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Ic(m.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Ux,{location:m})}),e.jsx("td",{children:e.jsx(Bx,{lodging:u})}),e.jsx("td",{children:e.jsx(Qx,{place:p,mapsUri:m.mapsUri})}),e.jsx("td",{children:e.jsx(Hx,{actions:x})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>l(m.locationName),children:h?"Hide":"Details"})})]}),h&&e.jsx("tr",{className:"bg-mono-950/35 hover:bg-mono-950/35",children:e.jsx("td",{colSpan:6,className:"px-4 py-4",children:e.jsx(Yx,{location:m,lodging:u,place:p,placeActions:x})})})]},m.id)})})]})})]})}function _x(t){return[{label:"Description",tone:bn(t.description)?"positive":"neutral",value:bn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:bn(t.primaryPhone)?"positive":"neutral",value:bn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:bn(t.websiteUri)?"positive":"neutral",value:bn(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function Ux({location:t}){const s=_x(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(Ne,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Bx({lodging:t}){return e.jsx(Li,{...Vx(t)})}function Vx(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 Qx({place:t,mapsUri:s}){return e.jsx(Li,{...zx(t,s)})}function zx(t,s){if(!t)return{tone:"neutral",label:"Public listing not checked",detail:s?"Maps link available.":"No Places snapshot."};const n=t.amenities.length;return{tone:n>0?"positive":"neutral",label:n>0?`${n} signal${n===1?"":"s"} detected`:"0 supported signals detected",detail:`Places tier: ${t.tier}`}}function Hx({actions:t}){return e.jsx(Li,{...Wx(t)})}function Wx(t){if(t.length===0)return{tone:"neutral",label:"No CTAs stored",detail:"No placeActionLinks returned."};const s=t.filter(n=>n.providerType==="MERCHANT").length;return s===0?{tone:"neutral",label:`${t.length} aggregator CTA${t.length===1?"":"s"}`,detail:"No merchant-owned CTA returned."}:{tone:"positive",label:`${s} merchant CTA${s===1?"":"s"}`,detail:`${t.length} total returned.`}}function Li({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(Ne,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Yx({location:t,lodging:s,place:n,placeActions:a}){const r=s?eg(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(qr,{title:"Owner profile · Business Information",children:[e.jsx(Ht,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Ht,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Ht,{label:"Description",value:bn(t.description)?t.description:"Not returned"}),e.jsx(Ht,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Ht,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Ht,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Ht,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Ht,{label:"Open status",value:Ic(t.openStatus)}),e.jsx(Ht,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(qr,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{label:"Last checked",value:Go(s.syncedAt)}),e.jsx(Ht,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Ht,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(qr,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{label:"Places tier",value:n.tier}),e.jsx(Ht,{label:"Last checked",value:Go(n.syncedAt)}),e.jsx(Ht,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(l=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[ur(l.placeActionType),l.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[ur(l.providerType),l.uri?` · ${Zx(l.uri)}`:""]})]},l.placeActionLinkName))})})]})]})}function qr({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Ht({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function ra(t,s,n){return t===s?"positive":t===0?n:"caution"}function Jx(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Xx(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function bn(t){return typeof t=="string"&&t.trim().length>0}function Ic(t){return t?ur(t):"Not returned"}function ur(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Zx(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Go(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function eg(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&tg(n)).map(([s])=>ur(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function tg(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function sg({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Xd.filter(y=>(a[y]??0)>0),l=Zd.filter(y=>(a[y]??0)>0),i=Object.keys(a).filter(y=>(a[y]??0)>0&&eu(y)==="other").sort((y,f)=>(a[f]??0)-(a[y]??0)),c=Object.keys(a).filter(y=>(a[y]??0)===0).sort(),d=n.map(y=>{const f={date:y.date};for(const[b,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(_o,{data:d,metrics:r,kind:"line",firstPending:m,lastDate:u}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:h.map(y=>e.jsxs("span",{className:"text-sm text-secondary",children:[or(y)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[y]??0).toLocaleString()})]},y))})]})]}),p&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(_o,{data:d,metrics:l,kind:"area",firstPending:m,lastDate:u})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(y=>or(y)).join(", ")]})]})}function _o({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(va,{stroke:ya,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:us},tickFormatter:Sn,minTickGap:24}),e.jsx(tn,{tick:Ut,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ns,labelFormatter:Pt,formatter:(l,i)=>[typeof l=="number"?l.toLocaleString():String(l??0),or(String(i??""))]}),e.jsx(cr,{wrapperStyle:{fontSize:11,color:ms.text},formatter:l=>or(l)}),a&&r&&e.jsx(ni,{x1:a,x2:r,fill:ms.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:ms.textDim,fontSize:10}}),s.map((l,i)=>n==="line"?e.jsx(Ks,{type:"monotone",dataKey:l,stroke:lt[i%lt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx(Ws,{type:"monotone",dataKey:l,stackId:"reach",stroke:lt[i%lt.length],fill:lt[i%lt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},l))]})})})}function ng(t){return Gh(Bt(String(t)))}function ag(t){return Sa(Bt(String(t)))}function Er({children:t,label:s="More info",placement:n="top",className:a}){const r=o.useId(),[l,i]=o.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":l?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:e.jsx(Jh,{className:"h-3.5 w-3.5","aria-hidden":!0})}),l&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const _a=Os;function Ln(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Dr(t){return t.toLocaleString()}function rg(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 ig(t){const s=t.filter(n=>n.kind===Us["backlink-extract"]&&!Ul(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function og(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 lg({projectName:t}){const s=Ls(),[n,a]=o.useState(null),[r,l]=o.useState(null),[i,c]=o.useState([]),[d,m]=o.useState(null),[u,p]=o.useState(null),[x,h]=o.useState(null),[y,f]=o.useState(Date.now()),[b,j]=o.useState(0),[k,$]=o.useState(!0),[S,g]=o.useState(!1),[v,C]=o.useState(null),T=o.useCallback(async()=>{$(!0),C(null);try{const[U,J,q,X,L]=await Promise.all([tu().catch(()=>null),su(t,{excludeCrawlers:!0}).catch(()=>null),nu(t,{limit:_a,offset:b,excludeCrawlers:!0}).catch(ee=>{if(ee instanceof Vn&&ee.code==="NOT_FOUND")return null;throw ee}),au(t).catch(()=>[]),ru(t).catch(()=>[])]);m(U),a(J),l(q),c(X);const D=ig(L);p(D)}catch(U){C(U instanceof Error?U.message:"Failed to load backlinks")}finally{$(!1)}},[t,b]);o.useEffect(()=>{T()},[T]),o.useEffect(()=>{if(!u)return;const U=u.id;let J=!1;const q=async()=>{try{const L=await ti(U);if(J)return;Ul(L.status)?(p(null),h(L),await T()):p(D=>D?.id===L.id?{...D,...L}:D)}catch{}},X=window.setInterval(()=>{q()},3e3);return()=>{J=!0,window.clearInterval(X)}},[u,T]),o.useEffect(()=>{if(!u)return;const U=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(U)},[u]),o.useEffect(()=>{if(!x||x.status==="failed")return;const U=window.setTimeout(()=>h(null),1e4);return()=>window.clearTimeout(U)},[x]);async function I(){g(!0),C(null);try{const U=await ou(t);p(U)}catch(U){U instanceof Vn&&U.code==="MISSING_DEPENDENCY"?C("DuckDB is not installed. Visit the Backlinks admin page to install it."):C(U instanceof Error?U.message:"Failed to trigger extract")}finally{g(!1)}}const w=o.useMemo(()=>i.slice().sort((U,J)=>U.queriedAt.localeCompare(J.queriedAt)).map(U=>({date:U.queriedAt,linkingDomains:U.totalLinkingDomains})),[i]),V=r?.rows??[],F=r?.total??0,z=n?.excludedLinkingDomains??0,B=Math.floor(b/_a)+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(je,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:v})}),u&&e.jsx(je,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(zh,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(Ne,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[og(u.startedAt??null,u.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",y]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),x&&!u&&e.jsx(je,{className:`surface-card p-4 mb-4 ${x.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(Hh,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${x.status==="failed"?"text-negative":"text-positive"}`,children:x.status==="failed"?"Extract failed":"Extract complete"}),x.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:iu(x.error)}):x.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),Q()]});function Q(){return k?e.jsx(je,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):se()}function se(){const U=n!==null&&n.totalLinkingDomains>0,J=x?.status==="failed",q=n!==null&&n.totalLinkingDomains===0&&!J,X=d?.status==="ready",L=d?.status==="failed",D=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return U?K(e.jsxs(e.Fragment,{children:[!ie()&&!s&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:S||u!==null,onClick:Ze(I),children:[e.jsx(Yh,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":S?"Queuing…":"Re-run extract"]}),e.jsx(Er,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ie()&&!s&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"Open admin"})})]})):e.jsx(je,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Wh,{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(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"Set up backlinks"})})})]}),D&&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(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"View sync status"})})})]}),L&&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(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"Go to Backlinks admin"})})})]}),X&&!D&&!q&&!J&&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(P,{type:"button",size:"sm",disabled:S||u!==null,onClick:Ze(I),children:[e.jsx(lr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":S?"Queuing…":"Run extract"]}),e.jsx(Er,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),J&&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(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"Go to Backlinks admin"})})})]}),q&&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(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ln("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:S||u!==null,onClick:Ze(I),children:[e.jsx(lr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":S?"Queuing…":"Re-run extract"]}),e.jsxs(Er,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:n.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function K(U){if(!n)return null;const J="Linking hosts",q="linking hosts",X="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 ",q]}),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 ",q," 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 ",q," 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"})," · ",X," ",e.jsx("code",{className:"text-secondary",children:n.release})," · queried ",rg(n.queriedAt),z>0&&e.jsxs(e.Fragment,{children:[" · ",z," excluded domain",z===1?"":"s"]})]}),w.length>=2&&e.jsxs(je,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:w,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:lt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:lt[0],stopOpacity:0})]})}),e.jsx(en,{dataKey:"date",tick:Ut,stroke:us,tickFormatter:ng}),e.jsx(tn,{tick:Ut,stroke:us,allowDecimals:!1}),e.jsx(sn,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:ag}),e.jsx(Ws,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:lt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(je,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:J})]})}),e.jsxs("tbody",{children:[V.map(L=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:L.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Dr(L.numHosts)})]},L.linkingDomain)),V.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 ${X} was a crawler/proxy host (${z} hidden).`:`No referring domains in this ${X}.`})})]})]})}),e.jsx(Gs,{page:B,pageSize:_a,visibleRows:V.length,totalRows:F,onPageChange:L=>j((L-1)*_a)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:U})]})}}const cg=["non-brand","branded","unclassified"],Uo={"non-brand":"Non-brand",branded:"Branded",unclassified:"Unclassified"};function dg(t,s){return s<=0?"neutral":t/s*100>=70?"positive":"caution"}function ug(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 cg.map(i=>a.get(i)).filter(i=>i!==void 0&&i.queries>0)}function mg(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 hg={engine:"engine no longer configured",query:"query no longer tracked"},Bo={"non-brand":"non-brand queries",branded:"branded queries",unclassified:"unclassified queries"},pg="Each engine's latest answer to each query, spot checks left out. Mentioned: the answer names you. Cited: its sources link to your site. Competitor cited instead of you: answers that cite a tracked competitor's site and not yours.";function $n(t,s,n){return t===1?s:n}function xg({projectName:t,classify:s,hasCompetitors:n,providerScores:a=[]}){const r=o.useId(),[l,i]=o.useState("non-brand"),c=qe({...lu({client:W,path:{name:t}}),staleTime:Ri}),d=c.data??null,m=d?.status==="ready"?ug(d,s):[],u=m.find(f=>f.key===l)??m.at(0);let p;c.isError?p=e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Could not load engine results: ",St(c.error)]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{c.refetch()},children:"Retry"})]}):d?d.status==="no-data"?p=e.jsx("p",{className:"text-sm text-secondary",children:d.reason==="no-queries"?"Add queries to start tracking AI citations.":ds()?Qn:"Engine results appear after the first AI Visibility sweep."}):u||(p=e.jsx("p",{className:"text-sm text-secondary",children:"No engine answers yet."})):p=e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine results…"});const x=[];if(u&&d?.status==="ready"){const f=$n(u.queries,"query","queries");x.push(e.jsxs(e.Fragment,{children:["Cited and named: ",e.jsxs("strong",{children:[u.citedAndNamed," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Cited but not named: ",e.jsxs("strong",{children:[u.citedNotNamed," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Named but not cited: ",e.jsxs("strong",{children:[u.namedNotCited," of ",u.queries]})," ",f]})),x.push(e.jsxs(e.Fragment,{children:["Not cited or named: ",e.jsxs("strong",{children:[u.neither," of ",u.queries]})," ",f]}));for(const $ of u.engines)$.answered<u.queries&&x.push(e.jsxs(e.Fragment,{children:[ot($.provider),": answered ",e.jsxs("strong",{children:[$.answered," of ",u.queries]})," ",f]}));u.unanswered>0&&x.push(e.jsxs(e.Fragment,{children:["No answers yet: ",e.jsx("strong",{children:u.unanswered})," ",$n(u.unanswered,"query","queries")]}));const{providersCiting:b,providersMentioning:j,providersConfigured:k}=d.summary;x.push(e.jsxs(e.Fragment,{children:["All queries: cited by ",e.jsxs("strong",{children:[b," of ",k]})," ",$n(k,"engine","engines"),", named by ",e.jsxs("strong",{children:[j," of ",k]})]}));for(const $ of a)x.push(e.jsxs(e.Fragment,{children:[ot($.provider),$.model?` (${$.model})`:""," citation rate:"," ",e.jsx("strong",{children:tt($.score,Yn.percent)}),", ",e.jsxs("strong",{children:[$.cited," of ",$.total]})," ",$n($.total,"answer","answers"),", all queries"]}));for(const $ of u.competitorGaps)x.push(`"${$.query}" (${ot($.provider)}): ${$.competitors.join(", ")} cited instead of you`);for(const $ of mg(d))x.push(`"${$.query}" (${ot($.provider)}): ${$.competitors.join(", ")} cited instead of you, not counted (${hg[$.reason]})`)}const h=d?.status==="ready"?d.summary.latestRunAt:null,y=(f,b)=>u?.key==="non-brand"?ga[dg(f,b)]:"text-primary";return e.jsxs("section",{className:"overview-brief","aria-labelledby":r,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:r,className:"av-card-title",children:"By engine"}),u&&e.jsx(Oe,{text:pg})]}),h||u?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[h?e.jsxs("p",{className:"av-card-meta",children:["Latest run ",xr(h)]}):null,m.length>1?e.jsx(pa,{label:"Query type",className:"flex-wrap",options:m.map(f=>({value:f.key,label:Uo[f.key]})),value:u.key,onChange:i}):u?e.jsx("span",{className:"mention-share-class",children:Uo[u.key]}):null]}):null]}),e.jsx("div",{className:"av-card-body",children:p??(u&&e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"av-grid av-grid-dense","aria-label":`By engine, ${Bo[u.key]}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsxs("th",{scope:"col",children:["Of ",u.queries," ",$n(u.queries,"query","queries")]}),u.engines.map(f=>e.jsx("th",{scope:"col",children:ot(f.provider)},f.provider))]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Mentioned"}),u.engines.map(f=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(f.mentioned,f.answered)}`,children:f.mentioned})},f.provider))]}),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label",children:"Cited"}),u.engines.map(f=>e.jsx("td",{children:e.jsx("span",{className:`av-n-sm ${y(f.cited,f.answered)}`,children:f.cited})},f.provider))]})]})]}),e.jsxs("p",{className:"av-card-line",children:[e.jsx("span",{className:"av-card-line-label",children:"Competitor cited instead of you"}),n?e.jsxs("span",{children:[e.jsx("span",{className:"av-n-sm text-primary",children:u.competitorCited})," ",e.jsxs("span",{className:"av-of",children:["of ",u.answers," ",$n(u.answers,"answer","answers")]}),e.jsxs("span",{className:"sr-only",children:[" · ",Bo[u.key]]})]}):e.jsx("span",{className:"text-[13px] text-secondary",children:"No competitors tracked"})]})]}))}),e.jsx(Ca,{items:x})]})}const gg={[Ts.queued]:{word:"queued",tone:"text-secondary"},[Ts.running]:{word:"running",tone:"text-info-300"},[Ts.completed]:{word:"completed",tone:"text-secondary"},[Ts.partial]:{word:"partial",tone:"text-caution-400"},[Ts.failed]:{word:"failed",tone:"text-negative-400"},[Ts.cancelled]:{word:"cancelled",tone:"text-secondary"}};function fg({runs:t,collapsed:s=!1}){const n=o.useId(),{openRun:a}=Ci(),r=new Set(t.map(c=>c.location??"")).size>1,l=t.some(c=>c.kind!==Us["answer-visibility"]),i=t.map(c=>`${c.startedAt}: ${c.summary}.${c.statusDetail?` ${c.statusDetail}`:""}`);return e.jsx("section",{className:"overview-brief","aria-labelledby":n,children:e.jsxs("details",{className:"av-history",open:!s||void 0,children:[e.jsxs("summary",{className:"av-card-head",children:[e.jsx("h2",{id:n,className:"av-card-title",children:"Past sweeps"}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t.length>0?e.jsxs("span",{className:"av-card-meta",children:[t.length," recent"]}):null,e.jsx(zn,{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=gg[c.status],m=c.status===Ts.partial||c.status===Ts.failed;return e.jsxs("tr",{children:[e.jsx("th",{scope:"row",className:"av-row-label tabular-nums",children:e.jsx("button",{type:"button",className:"av-link",onClick:()=>a(c.id),"aria-label":`View the ${c.startedAt} sweep`,children:c.startedAt})}),l?e.jsx("td",{className:"text-[13px] text-secondary",children:c.kindLabel}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.triggerLabel}),r?e.jsx("td",{className:"text-[13px] text-secondary",children:c.location??"No location"}):null,e.jsx("td",{className:"text-[13px] text-secondary",children:c.duration}),e.jsxs("td",{children:[e.jsx("span",{className:`av-status ${d.tone}`,children:d.word}),m&&c.statusDetail?e.jsx("span",{className:"ml-2 text-[13px] text-secondary",children:c.statusDetail}):null]})]},c.id)})})]})}),e.jsx(Ca,{items:i})]})})}const yg=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"all",label:"All"}],Vo="Measured answers",bg="Close answers",Ps={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},vg={"non-brand":"non-brand queries",branded:"branded queries",unknown:"unclassified queries"},cs={up:t=>`Up ${t} pts`,down:t=>`Down ${t} pts`,none:"No change",previousUnavailable:"No earlier value",comparedWith:t=>`vs ${t} sweep`,noPreviousRun:"No earlier sweep to compare",definitionChanged:t=>t===null?"Not compared: setup changed":`Not compared: setup changed since ${t}`,modelChanged:t=>t===null?"Not compared: engines or models changed":`Not compared: engines or models changed since ${t}`,legacyUnknown:"Not compared: older sweep lacks comparison details",partialRun:"Not compared: a sweep was incomplete",scopedRun:"Not compared: this sweep covered part of the project",explanation:"Change compares this sweep with the sweep before it when both completed and used the same setup, engines and models."},ia={simpleMention:"Mentioned counts answers naming your brand in the answer text, not in the source links.",simpleCitation:"Cited counts answers linking to your site in the sources behind the answer, not in the answer text.",advancedMention:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned. An answer that could not be tied to one property is left out of the rate, never counted as not mentioned.",advancedCitation:"An answer counts when it cites a matching URL for any assigned property. This does not mean every property was cited. An answer whose sources could not be checked is left out of the rate, as neither cited nor not cited, and counted on its own line.",propertyReach:"Selected properties named in at least one measured answer, out of the selected properties that have a name to match on. It counts properties, not answers, and shows no rate while any of those properties is unmeasured."},jg="Counts properties, not answers. The buckets do not overlap and add up to the total. Cited only means the engine used the property's page as a source without naming it in the answer. Not measured covers a property with no eligible completed measurement, and one where only one of the two signals was measured: calling that mentioned but not cited would assert an absence nothing measured. Neither signal means both were measured and neither was found. One verified mention or citation stands, and a later uncertain answer cannot erase it.",mr="min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400";function Ng(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function Tc(t){return t.reason==="identity-ambiguous"?Hl.ambiguous:t.reason==="not-applicable"?"Not applicable":"Not measured"}function Cn({value:t,signal:s}){if(t.rate===null)return e.jsx("span",{className:"text-sm text-secondary",children:Tc(t)});const n=Pi(t,s);return e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children: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 Qo({value:t}){return t.rate===null?null:e.jsx("span",{className:"report-rate-bar","aria-hidden":"true",children:e.jsx("span",{className:"report-rate-bar-fill progress-fill-neutral",style:{width:`${t.rate*100}%`}})})}function Or(t,s){if(!t||t.state==="unavailable")return null;const n=t[s];if(n.state==="unavailable")switch(n.reason){case wr["previous-unavailable"]:return{text:cs.previousUnavailable,tone:"text-secondary"};case wr["current-unavailable"]:case wr["not-applicable"]:return null}const{direction:a,magnitude:r}=Vl(n.delta);switch(a){case"up":return{text:cs.up(r),tone:"text-positive"};case"down":return{text:cs.down(r),tone:"text-negative"};case"none":return{text:cs.none,tone:"text-secondary"}}}function zo(t,s){const n=Bt(t);return s!==null&&po(n)===po(Bt(s))?Bh(n):Sa(n)}function wg(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 Sg(t,s){if(!t)return null;if(t.state==="unavailable"){const n=t.previousRun?zo(t.previousRun.createdAt,s):null;switch(t.reason){case hn["no-selected-run"]:return null;case hn["no-previous-run"]:return cs.noPreviousRun;case hn["definition-changed"]:return cs.definitionChanged(n);case hn["model-changed"]:return cs.modelChanged(n);case hn["legacy-unknown"]:return cs.legacyUnknown;case hn["partial-run"]:return cs.partialRun;case hn["scoped-run"]:return cs.scopedRun}}return cs.comparedWith(zo(t.previousRun.createdAt,s))}function Cg(t,s){const n=`${t.queryCount} ${t.queryCount===1?"query":"queries"} · ${t.answerCount} ${t.answerCount===1?"answer":"answers"}`;return s===null?n:`${n} · ${s}`}function Fr({label:t,help:s,value:n,signal:a,unit:r,classNoun:l,change:i}){const c=e.jsx("span",{className:"sr-only",children:` · ${l}`}),d=Pi(n,a);return e.jsxs("div",{className:"report-headline-tile",children:[e.jsxs("dt",{className:"flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:t}),e.jsx(Oe,{text:s})]}),n.rate===null?e.jsxs("dd",{className:"text-lg text-secondary",children:[Tc(n),c]}):e.jsxs(e.Fragment,{children:[e.jsxs("dd",{className:"report-headline-value",children:[e.jsx("span",{className:"text-3xl font-semibold tabular-nums text-heading",children: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 kg={otherQueries:"Other queries"},Ua={retiredScope:"This saved scope is unavailable for this measurement. Show the whole site to choose another.",retiredMarket:"This saved market is unavailable for this measurement. Show all markets to choose another.",showWholeSite:"Show whole site",showAllMarkets:"Show all markets"};function Ag(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(" · ")||kg.otherQueries}return a.sort((r,l)=>r.marketLabel.localeCompare(l.marketLabel)||r.query.localeCompare(l.query))}function Ho({value:t,signal:s,singleAnswer:n}){if(n&&t.denominator===1&&t.unattributed===void 0&&t.unchecked===void 0&&(t.rate===0||t.rate===1)){const a=t.rate===1;return e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm ${a?"text-positive":"text-secondary"}`,children:[a?e.jsx(Zh,{size:16,"aria-hidden":"true"}):e.jsx(ep,{size:16,"aria-hidden":"true"}),a?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Cn,{value:t,signal:s}),t.reason==="evidence-incomplete"?e.jsx(Oe,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function Wo({targetKeys:t,labels:s}){return t.length===0?e.jsx("span",{children:"No assigned properties"}):t.length===1?e.jsx("span",{children:s.get(t[0])??t[0]}):e.jsxs("details",{children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[t.length," properties"]}),e.jsx("ul",{className:"max-h-48 space-y-2 overflow-y-auto pb-3",children:t.map(n=>e.jsx("li",{children:s.get(n)??n},n))})]})}function Rg({group:t,queryClass:s,advanced:n,targetLabels:a,marketHeading:r,onViewAnswers:l}){const i=t.rows[0],c=p=>JSON.stringify([...p.targetKeys].sort()),d=t.rows.every(p=>c(p)===c(i)),m=t.rows.every(p=>p.location===i.location),u=p=>p===null?"No location requested":`Requested search location: ${p}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[r?e.jsx("tr",{children:e.jsx("th",{colSpan:4,className:"border-t border-default py-4 text-left",children:e.jsx("h3",{className:"text-base font-semibold text-heading",children:r})})}):null,e.jsx("tr",{className:"measurement-result-heading",children:e.jsxs("th",{scope:"rowgroup",colSpan:4,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"break-words text-base font-medium text-heading",children:t.query}),e.jsx("div",{className:"text-sm font-normal",children:e.jsx(ql,{showLabel:!0,queryId:i.queryId,sourceSnapshotIds:t.rows.flatMap(p=>p.sourceSnapshotIds??[]),queryClass:s==="unknown"?null:s,location:m?i.location:void 0})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 text-sm font-normal text-secondary",children:[n&&d?e.jsx(Wo,{targetKeys:i.targetKeys,labels:a}):null,m?e.jsx("span",{children:u(i.location)}):null]})]})}),t.rows.map(p=>e.jsxs("tr",{className:"measurement-engine-result",children:[e.jsxs("td",{className:"measurement-result-engine",children:[e.jsx("span",{className:"font-medium text-heading",children:ot(p.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:p.model??"Model not recorded"}),n&&!d?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(Wo,{targetKeys:p.targetKeys,labels:a})}):null,m?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:u(p.location)}),e.jsx(El,{showLabel:!0,showSubjects:n,queryId:p.queryId,sourceSnapshotIds:p.sourceSnapshotIds??[],queryClass:s==="unknown"?null:s,provider:p.provider,model:p.model,location:p.location})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(Ho,{value:p.mentionCoverage,signal:"mentioned",singleAnswer:p.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(Ho,{value:p.citationCoverage,signal:"cited",singleAnswer:p.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(P,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${p.query} · ${p.provider}`,onClick:x=>l(p,x.currentTarget),children:[p.answerCount===1?"View answer":"View answers",e.jsx(lc,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([p.provider,p.model,p.location])))]})}const Pg="Cited counts only answers whose sources could be checked.",Yo=[{key:"mentioned",label:"Mentioned",color:lt[1],dashed:!1},{key:"cited",label:"Cited",color:Jn.positive,dashed:!0}],Jo="var(--chart-tooltip-bg)";function Ig({population:t}){const s=o.useId(),[n,a]=o.useState({mentioned:!0,cited:!0}),r=Yo.filter(x=>n[x.key]).map(x=>x.key),l=x=>a(h=>{const y={...h,[x]:!h[x]};return y.mentioned||y.cited?y:h});let i=0;const c=t.trend.map((x,h)=>(h>0&&x.continuity.state!=="comparable"&&(i+=1),{createdAt:Date.parse(x.createdAt),[`mentioned-${i}`]:x.mentionCoverage.rate,[`cited-${i}`]:x.citationCoverage.rate})),d=Array.from({length:i+1},(x,h)=>h),m=new Set(t.trend.slice(1).map(x=>x.continuity.state)),u=[...c.length===1?["First measurement. A trend appears after another comparable run."]:[],...m.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...m.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...m.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(x=>x.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[],...t.trend.some(x=>x.citationCoverage.unchecked!==void 0)?[Pg]:[]];if(c.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const p=t.trend.some(x=>x.mentionCoverage.rate!==null||x.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[p?e.jsxs(e.Fragment,{children:[e.jsxs("fieldset",{className:"flex flex-wrap gap-x-5 py-1 text-sm text-secondary",children:[e.jsx("legend",{className:"sr-only",children:"Trend legend"}),Yo.map(x=>e.jsxs("label",{className:"flex min-h-11 items-center gap-2",children:[e.jsx("input",{type:"checkbox",className:"size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",checked:n[x.key],disabled:n[x.key]&&r.length===1,onChange:()=>l(x.key)}),e.jsxs("svg",{"aria-hidden":"true",className:"shrink-0",width:"24",height:"10",viewBox:"0 0 24 10",children:[e.jsx("line",{x1:"0",y1:"5",x2:"24",y2:"5",stroke:x.color,strokeWidth:"2",strokeDasharray:x.dashed?"6 4":void 0}),e.jsx("circle",{cx:"12",cy:"5",r:"3",fill:x.dashed?Jo:x.color,stroke:x.color,strokeWidth:"2"})]}),x.label]},x.key))]}),u.length>0&&e.jsx("p",{id:s,className:"pb-3 text-sm text-secondary",children:u.join(" ")}),e.jsx("div",{className:"visibility-trend-chart",role:"img","data-visible-series":r.join(" "),"aria-describedby":u.length>0?s:void 0,"aria-label":`${Ps[t.queryClass]} mention and citation trend`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:c,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(va,{stroke:ya,vertical:!1}),e.jsx(en,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Ut,tickLine:!1,axisLine:{stroke:us},tickFormatter:x=>new Date(Number(x)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(tn,{domain:[0,1],tick:Ut,tickLine:!1,axisLine:!1,width:48,tickFormatter:x=>tt(Number(x))}),e.jsx(sn,{...ns,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(Ks,{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(Ks,{type:"linear",dataKey:`cited-${x}`,name:"Cited",stroke:Jn.positive,strokeWidth:2,strokeDasharray:"6 4",connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:Jo,strokeDasharray:"none"}}):null]},x))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:p?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${Ps[t.queryClass]} trend data`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"}),e.jsx("th",{children:"Comparison"})]})}),e.jsx("tbody",{children:t.trend.map(x=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(x.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(Cn,{value:x.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(Cn,{value:x.citationCoverage,signal:"cited"})}),e.jsx("td",{children:x.continuity.state.replaceAll("-"," ")})]},x.runId))})]})})]})}function xi(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function $i(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,l=t.populations.find(m=>m.queryClass===r);if(l)return l;const i=xi(a,s)??xi(t,s),c=t.populations.find(m=>m.queryClass===i?.queryClass);if(c)return c;const d=["non-brand","branded","unknown"].map(m=>t.populations.find(u=>u.queryClass===m));return d.find(m=>m&&(m.summary.queryCount>0||m.trend.some(u=>u.queryCount>0)))??d.find(m=>m!==void 0)??t.populations[0]}const At={queryType:"Query type",filters:t=>t===0?"Filters":`Filters · ${t}`,panel:"Visibility filters",clearFilters:"Clear filters",manageQueries:"Manage queries",removeFilter:t=>`Remove filter ${t}`,engine:t=>`Engine: ${t}`,model:t=>`Model: ${t}`,location:t=>`Requested search location: ${t}`,noLocation:"No location requested",dateRange:(t,s)=>`${t} to ${s} (UTC)`,dateFrom:t=>`From ${t} (UTC)`,dateThrough:t=>`Through ${t} (UTC)`,resultsFrom:t=>`Results from: ${t}`,resultsFromSelectedSweep:"Results from: selected sweep"},Tg={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},Mg="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 Lg(t,s){return t&&s?At.dateRange(t.slice(0,4)===s.slice(0,4)?Uh(t):Pt(t),Pt(s)):t?At.dateFrom(Pt(t)):s?At.dateThrough(Pt(s)):null}function $g(t,s){const n=[];t.provider&&n.push({key:"engine",label:At.engine(t.provider),patch:{measurementProvider:void 0}}),t.model&&n.push({key:"model",label:At.model(t.model),patch:{measurementModel:void 0}}),t.location&&n.push({key:"location",label:t.location==="none"?At.noLocation:At.location(t.location),patch:{measurementLocation:void 0}});const a=Lg(t.from,t.to);if(a&&n.push({key:"dates",label:a,patch:{measurementFrom:void 0,measurementTo:void 0}}),t.measurementRunId){const r=s.populations.flatMap(l=>l.trend).find(l=>l.runId===t.measurementRunId);n.push({key:"run",label:r?At.resultsFrom(Sa(Bt(r.createdAt))):At.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function Ba(t,s,n){return s===""||t.some(a=>a.value===s)?t:[...t,{value:s,label:n}]}function qg({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=$g(s,t),b=s.measurementScope==="property"?s.measurementScopeKey:void 0,j=b?r?.({id:b,label:ai(t.scopeOptions,s)?.label??b}):null,k=s.provider??"",$=s.model??"",S=s.location??"",g=s.measurementRunId??"",v=()=>c.current?.focus(),C=(I,w,V,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:I}),z?e.jsx(Oe,{text:z}):null]}),e.jsx("select",{id:`${d}-${w}`,className:mr,value:V,onChange:B=>n({[w]:B.target.value||void 0,measurementQueryKey:void 0}),children:F.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]}),T=(I,w,V,F)=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("label",{htmlFor:`${d}-${w}`,className:"mb-1 block text-sm font-medium text-heading",children:I}),e.jsx("input",{id:`${d}-${w}`,type:"date",className:mr,value:V?.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:At.queryType}),e.jsxs("select",{"aria-label":At.queryType,className:Mg,value:y,onChange:I=>n({queryClass:I.target.value,measurementQueryKey:void 0}),children:[e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"unknown",children:"Unclassified"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{tone:x.state==="measured"?"positive":"neutral",children:x.state==="measured"?"Complete":x.state==="partial"?"Partial":"Not measured"}),x.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:Sa(Bt(x.completedAt))}):null]})]}),e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[e.jsx(P,{ref:c,type:"button",variant:"outline",className:"min-h-11","aria-expanded":l,"aria-controls":m,onClick:()=>i(I=>!I),children:At.filters(f.length)}),f.map(I=>e.jsxs(P,{type:"button",variant:"outline",className:"visibility-filter-token min-h-11 rounded-md text-sm","aria-label":At.removeFilter(I.label),onClick:()=>{n(I.patch),v()},children:[e.jsx("span",{className:"min-w-0 truncate",children:I.label}),e.jsx(Xh,{size:16,className:"shrink-0","aria-hidden":"true"})]},I.key)),j,a?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:a,children:At.manageQueries}):null]})]}),e.jsxs("div",{id:m,role:"group","aria-label":At.panel,hidden:!l,className:"border-b border-default",onKeyDown:I=>{I.key==="Escape"&&(I.target instanceof HTMLElement&&I.target.getAttribute("aria-expanded")==="true"||(i(!1),v()))},children:[e.jsxs("div",{className:"visibility-report-filters",children:[C("Answer engine","measurementProvider",k,Ba([{value:"",label:"All engines"},...u.providers.map(I=>({value:I,label:I}))],k,k)),C("Requested search location","measurementLocation",S,Ba([{value:"",label:"All requested locations"},...u.locations.flatMap(I=>I.kind==="exact"?[{value:I.value,label:I.value}]:I.kind==="none"?[{value:"none",label:At.noLocation}]:[])],S,S==="none"?At.noLocation:S)),C("AI model","measurementModel",$,Ba([{value:"",label:"All models"},...Array.from(new Set(u.models.filter(I=>!s.provider||I.provider===s.provider).map(I=>I.model))).map(I=>({value:I,label:I}))],$,$),"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),T("Start date (UTC)","measurementFrom",s.from,"T00:00:00.000Z"),T("End date (UTC)","measurementTo",s.to,"T23:59:59.999Z"),C("Results from","measurementRunId",g,Ba([{value:"",label:"Latest saved sweep"},...[...h.trend].reverse().map(I=>({value:I.runId,label:new Date(I.createdAt).toLocaleString()}))],g,"Selected sweep"),"Choose a saved AI sweep to view its results. No new sweep starts.")]}),e.jsx("div",{className:"flex justify-end pb-3",children:e.jsx(P,{type:"button",variant:"ghost",className:"min-h-11",disabled:f.length===0,onClick:()=>{n({...Tg}),v()},children:At.clearFilters})})]})]})}function Eg({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,k=j.populations.filter(w=>[...w.queries.items,...w.evidence.items].some(V=>V.queryKey===i)),$=c?[c.queryClass]:(k.length?k:m?[]:[b]).map(w=>w.queryClass),S=i?JSON.stringify([c??i,$]):void 0;o.useEffect(()=>{if(!S){s||(y.current=void 0);return}if(y.current===S)return;const w=h.current?.querySelectorAll(`[aria-label="${Vo}"]`);if(w?.length){for(const V of w){const F=V.closest("details[data-query-results]");F&&(F.open=!0)}w[0].focus({preventScroll:!0}),w[0].scrollIntoView?.({block:"start"}),y.current=S}},[S,s]);const{selection:g}=t,v=Ng(g.scope),C=new Map(t.scopeOptions.filter(w=>w.kind==="property").map(w=>[w.id,w.label])),T=w=>{const V=j.populations.find(F=>F.queryClass===w.queryClass)?.evidence;return{items:V?.items.filter(F=>F.queryKey===i&&(!c||F.provider===c.provider&&F.model===c.model&&F.location===c.location&&(c.runId===null||F.runId===c.runId)))??[],nextCursor:V?.nextCursor}},I=()=>{y.current=void 0;const w=f.current;w!==null&&w.row.queryKey===i&&(!c||w.row.provider===c.provider&&w.row.model===c.model&&w.row.location===c.location)&&w?.element.isConnected?w.element.focus():h.current?.querySelector(`details[data-query-results="${b.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})};return e.jsxs("section",{ref:h,className:"visibility-report","aria-label":"AI visibility results",children:[g.provenance.kind==="legacy-simple"&&g.queryClass!=="unknown"&&g.queryClass!=="all"?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default py-3 text-sm text-secondary",children:[e.jsx("p",{children:"These saved results aren't separated by query type."}),e.jsx(P,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,[b].map(w=>{const V=Ag(w.queries.items,g.scope.kind==="property"&&!g.market&&w.queryClass==="non-brand"?new Map(t.scopeOptions.filter(K=>K.kind==="market").map(K=>[K.id,K.label])):void 0),F=T(w),z=F.items[0]?.query??w.queries.items.find(K=>K.queryKey===i)?.query,B=g.mode==="advanced"&&g.scope.kind!=="property",Q=vg[w.queryClass],se=Sg(w.comparison,wg(g,w));return e.jsxs("section",{"aria-label":Ps[w.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head flex-wrap items-center",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("h2",{children:Ps[w.queryClass]}),e.jsx(Oe,{text:w.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":w.queryClass==="branded"?"Queries that name the measured identity.":"These queries were not labeled as branded or non-brand when measured. Their saved results remain available here, separate from branded and non-brand rates."})]}),e.jsxs("div",{className:"report-headline-caption",children:[e.jsx("span",{className:"tabular-nums",children:Cg(w.summary,se)}),e.jsx(Oe,{text:cs.explanation})]})]}),e.jsxs("dl",{className:"report-headline mt-3","data-columns":B?3:2,"aria-label":`${Ps[w.queryClass]} headline results`,children:[e.jsx(Fr,{label:B?"Answers mentioning a property":"Mentioned answers",help:g.mode==="advanced"?ia.advancedMention:ia.simpleMention,value:w.summary.mentionCoverage,signal:"mentioned",unit:"answers",classNoun:Q,change:Or(w.comparison,"mentionCoverage")}),e.jsx(Fr,{label:B?"Answers citing a property":"Cited answers",help:g.mode==="advanced"?ia.advancedCitation:ia.simpleCitation,value:w.summary.citationCoverage,signal:"cited",unit:"answers",classNoun:Q,change:Or(w.comparison,"citationCoverage")}),B?e.jsx(Fr,{label:"Properties mentioned",help:ia.propertyReach,value:w.summary.propertyReach,signal:"mentioned",unit:"properties",classNoun:Q,change:Or(w.comparison,"propertyReach")}):null]}),e.jsx($l,{queryClass:g.queryClass,manage:!0}),e.jsx(Ig,{population:w}),B&&(w.breakdown.groups.length>0||w.breakdown.properties.length>0)?e.jsx(Dg,{population:w,scope:g.scope,scopeOptions:t.scopeOptions,marketKey:g.market?.id,onSelectionChange:n},`${g.scope.kind}:${g.scope.id}`):null,g.mode==="advanced"?e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Ps[w.queryClass]} property outcomes`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Property outcomes"}),e.jsxs("span",{className:"visibility-disclosure-meta",children:[w.summary.outcomes.total," ",w.summary.outcomes.total===1?"property":"properties"]})]}),e.jsxs("div",{className:"visibility-disclosure-panel flex flex-wrap items-start justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-x-8 gap-y-3",children:[["bothSignals","mentioned and cited"],["mentionedOnly","mentioned only"],["citedOnly","cited only"],["neither","neither signal"],["notMeasured","not measured"]].map(([K,U])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:w.summary.outcomes[K]}),e.jsx("span",{className:"text-sm text-secondary",children:U})]},K))}),e.jsx(Oe,{text:jg})]})]}):null,e.jsxs("details",{className:"visibility-disclosure","data-query-results":w.queryClass,"aria-label":`${Ps[w.queryClass]} query results`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Query results"}),e.jsxs("span",{className:"visibility-disclosure-meta",children:[w.queries.total," ",w.queries.total===1?"result":"results"," · ",v]})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-3",children:[r?e.jsx("input",{type:"search","aria-label":`Search ${Ps[w.queryClass]}`,placeholder:"Search queries",className:`${mr} max-w-sm`,value:l,onChange:K=>r(K.target.value)}):null,e.jsx(Oe,{text:g.mode==="advanced"?"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, property scope, and answer counts. Mentioned and Cited count answers matching any assigned property, not the percentage of properties found.":"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, and answer counts. Mentioned counts answers naming your brand. Cited counts answers linking to your site."})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table measurement-results-table","aria-label":`${Ps[w.queryClass]} engine results`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Answer engine"}),e.jsx("th",{scope:"col",children:"Mentioned"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),V.map((K,U)=>e.jsx(Rg,{group:K,queryClass:w.queryClass,marketHeading:K.marketLabel!==V[U-1]?.marketLabel?K.marketLabel:void 0,advanced:g.mode==="advanced",targetLabels:C,onViewAnswers:(J,q)=>{f.current={row:J,element:q},n({measurementQueryKey:J.queryKey,measurementAnswer:JSON.stringify({queryKey:J.queryKey,queryClass:w.queryClass,provider:J.provider,model:J.model,location:J.location,runId:g.run.id,revision:g.revision})})}},K.queryKey))]})}),w.queries.items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:"No measured queries match this selection."}):e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:[V.length," ",V.length===1?"query":"queries"," · ",w.queries.items.length," ",w.queries.items.length===1?"engine result":"engine results"," shown of ",w.queries.total," results"]}),w.queries.nextCursor&&a?e.jsx(P,{variant:"outline",onClick:()=>a(w.queries.nextCursor),children:"Next queries"}):null,i&&$.includes(w.queryClass)?e.jsxs("section",{tabIndex:-1,className:"scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-label":Vo,"aria-busy":m,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("h3",{className:"min-w-0 flex-1 text-base font-semibold text-heading [overflow-wrap:anywhere]",children:z??"Answers"}),e.jsx(P,{variant:"ghost",className:"min-h-11",onClick:I,children:bg})]}),m?e.jsx("p",{role:"status",className:"py-4 text-sm text-secondary",children:"Loading saved answers…"}):u?e.jsxs("div",{role:"alert",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["Saved answers unavailable: ",u]}),p?e.jsx(P,{variant:"outline",onClick:p,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[F.items.map(K=>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:K.provider}),K.model?e.jsx("span",{className:"text-[13px] text-secondary",children:K.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:K.location===null?At.noLocation:At.location(K.location)}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(K.createdAt).toLocaleDateString()}),e.jsx(Ne,{tone:"neutral",children:K.mentioned===null?K.mentionUnavailableReason==="identity-ambiguous"?Hl.ambiguous:"Mention not checked":K.mentioned?"Mentioned":"Not mentioned"}),e.jsx(Ne,{tone:"neutral",children:K.cited===null?"Citation not checked":K.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Ti,{headingLevel:4,copyable:!!K.answerText?.trim(),children:K.answerText??"Answer text unavailable."})}),K.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:[Oh," (",K.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:K.sources.map(U=>e.jsx("li",{className:"min-w-0",children:e.jsx(ki,{url:U})},U))})]}):null]},K.answerId)),T(w).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:T(w).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,T(w).nextCursor&&x?e.jsx(P,{variant:"outline",onClick:()=>x(T(w).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"visibility-disclosure","aria-label":`${Ps[w.queryClass]} competitors`,children:[e.jsxs("summary",{className:"visibility-disclosure-summary",children:[e.jsx("span",{className:"visibility-disclosure-label",children:"Competitors"}),e.jsx("span",{className:"visibility-disclosure-meta",children:w.competitorAvailability.state==="unavailable"?"Not available":`${w.competitors.length} measured`})]}),e.jsxs("div",{className:"visibility-disclosure-panel",children:[w.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):w.competitors.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No measured competitors in this selection."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Competitor"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:w.competitors.map(K=>e.jsxs("tr",{children:[e.jsx("td",{children:K.domain}),e.jsx("td",{children:e.jsx(Cn,{value:K.mentionCoverage,signal:"mentioned"})}),e.jsx("td",{children:e.jsx(Cn,{value:K.citationCoverage,signal:"cited"})})]},K.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(K=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:K.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[K.answerCount," ",K.answerCount===1?"answer":"answers"]})]},K.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},w.queryClass)})]})}function Dg({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const l=new Map(n.filter(p=>p.kind==="group").map(p=>[p.id,p])),i=[...l.values()].some(p=>p.parentGroupIds?.length),c=t.breakdown.groups.filter(p=>{const x=l.get(p.id)?.parentGroupIds??[];return s.kind==="project"?x.length===0:s.kind==="group"&&i?x.includes(s.id):!0}),[d,m]=o.useState(()=>s.kind==="project"&&c.length>0?"groups":"properties"),u=wn({rows:d==="groups"?c:t.breakdown.properties,getSearchText:p=>p.label});return e.jsxs("section",{className:"border-t border-default py-5","aria-label":"Scope breakdown",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsx("div",{className:"flex gap-2",children:["groups","properties"].map(p=>e.jsx(P,{variant:d===p?"secondary":"ghost",onClick:()=>{m(p),u.setPage(1)},children:p==="groups"?"Groups":"Properties"},p))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:u.query,onChange:p=>u.setQuery(p.target.value),className:`${mr} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:d==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:u.rows.map(p=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("button",{className:"min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>r({measurementScope:d==="groups"?"group":"property",measurementScopeKey:p.id,measurementMarketKey:a}),children:p.label})}),e.jsx("td",{children:p.queryCount}),e.jsxs("td",{children:[e.jsx(Cn,{value:p.mentionCoverage,signal:"mentioned"}),e.jsx(Qo,{value:p.mentionCoverage})]}),e.jsxs("td",{children:[e.jsx(Cn,{value:p.citationCoverage,signal:"cited"}),e.jsx(Qo,{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(Gs,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:d,onPageChange:u.setPage})]})}function Mc(t,s,{enabled:n}){return qe({...nr({client:W,path:{name:t},query:si(s)}),enabled:n,staleTime:Bl,retry:!1,placeholderData:wi})}function Lc(t,s){return s&&t.selection.mode==="simple"&&t.selection.measurement.state==="not-measured"}function Og({projectName:t,selection:s,onSelectionChange:n,fallback:a,showUnmeasuredFallback:r=!1}){const[l,i]=o.useState(),[c,d]=o.useState(""),[m,u]=o.useState(),p=hs(),x=o.useMemo(()=>({scope:s.measurementScope,scopeKey:s.measurementScopeKey,marketKey:s.marketKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId}),[s.measurementScope,s.measurementScopeKey,s.marketKey,s.queryClass,s.provider,s.model,s.location,s.from,s.to,s.revision,s.measurementRunId]),h=qe({...nr({client:W,path:{name:t},query:{...si(s),cursor:l,search:c||void 0}}),staleTime:Bl,retry:!1,placeholderData:wi}),y={...x,queryKey:s.queryKey,queryClass:s.answer?.queryClass??s.queryClass,provider:s.answer?.provider??s.provider,model:s.answer?s.answer.model??void 0:s.model,location:s.answer?s.answer.location??"none":s.location,runId:s.answer?.runId??h.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??h.data?.selection.revision??s.revision,limit:50},f=JSON.stringify(y),b=qe({...nr({client:W,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:k}=nr({client:W,path:{name:t},query:si({...s,queryClass:j.queryClass})});p.setQueryData(k,{...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&&Lc(h.data,r))return e.jsx(e.Fragment,{children:a});if(h.error){const j=Ql(zl(h.error)),k=j?.reason===uu["retired-market"];return e.jsxs("section",{className:"page-section-divider",role:"alert",children:[e.jsx("h2",{children:"AI visibility unavailable"}),e.jsx("p",{className:"my-3 text-sm text-secondary",children:k?Ua.retiredMarket:j?Ua.retiredScope:fa(h.error)}),k?e.jsx(P,{variant:"outline",onClick:()=>{i(void 0),n({measurementMarketKey:void 0})},children:Ua.showAllMarkets}):j?e.jsx(P,{variant:"outline",onClick:()=>{i(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:Ua.showWholeSite}):e.jsx(P,{variant:"outline",onClick:()=>{i(void 0),h.refetch()},children:"Retry"})]})}return h.data?e.jsx("div",{"aria-busy":h.isFetching,children:e.jsx(Eg,{report:h.data,isRefreshing:h.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:b.data,isEvidenceLoading:b.isFetching||!!s.queryKey&&b.isPending,evidenceError:b.error?fa(b.error):void 0,onRetryEvidence:()=>{b.refetch()},onEvidencePage:b.isFetching?void 0: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(k=>k!=="measurementQueryKey"&&k!=="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 Fg({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,fallback:l,showUnmeasuredFallback:i=!1}){const c=Mc(t,s,{enabled:!0}),d=c.error?void 0:c.data,m=!c.isPlaceholderData&&d?.selection.availability.state==="available"?d.selection.run.id:null;du(m,null);const u=!!(d&&d.selection.availability.state==="available"&&!Lc(d,i));return e.jsxs(e.Fragment,{children:[u?e.jsx(qg,{report:d,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r}):null,!u&&(d||c.error)?e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsx(Ll,{})}):null,e.jsx(Og,{projectName:t,selection:s,onSelectionChange:n,fallback:l,showUnmeasuredFallback:i},`${t}:${JSON.stringify({...s,queryKey:void 0,answer:void 0})}`)]})}const Kg=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Gg=[{value:"mentioned",label:"Mentioned",description:"Your brand or domain appears in the answer text."},{value:"cited",label:"Cited",description:"Your domain appears in source or grounding links."},{value:"mentionShare",label:"Mention share",description:"Your share of the answer-text brand mentions for you and tracked competitors, in non-brand answers, or in all answers when queries cannot be split by brand."}],qi=lt[2],_g=lt[4],Ug="var(--chart-tooltip-bg)",Bg={up:"text-positive-400",down:"text-negative-400",none:"text-muted"};function $c({direction:t,magnitude:s}){switch(t){case"up":return`up ${s} points`;case"down":return`down ${s} points`;case"none":return"no change"}}function Vg(t){return t.direction==="none"?"no change over the period":`${$c(t)} over the period`}function Qg(t){return t===ka||t===Aa||t===_s}function qc(t){return t===ka?"Cited":t===Aa?"Mentioned":t===_s?"Mention share":ot(t)}function ca(t,s){return t===ka?Jn.positive:t===Aa?lt[1]:t===_s?qi:_h(Na(t),s)}function Ei(t){return t==="non-brand"?"non-brand answers":"all answers"}function gi(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function Di(t,s){return t==="mentionShare"?`Mention share in ${Ei(s)}`:gi(t)}function zg(t){return`Mentioned = share of answers that name you. Cited = share that link to your site. Mention share = your share of tracked-brand mentions in ${t==="non-brand"?"non-brand answers":"all answers"}.`}function Ec(t){return t==="cited"?"citationRate":"mentionRate"}function Oi(t,s){return s==="cited"?t.cited:t.mentionedCount}function Dc(t,s,n){const a=t.byProvider[s];return a?{count:n==="cited"?a.cited:a.mentionedCount,total:a.total,rate:n==="cited"?a.citationRate:a.mentionRate}:null}function Hg(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 Wg(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Oc(t){const s=gc(t);return s===null?[]:Object.entries(s).sort(([n],[a])=>Na(n).localeCompare(Na(a))).map(([n,a])=>`${ot(n)}: ${wa(a)}`)}function Fc(t,s){return new Date(t).toDateString()===new Date(s).toDateString()}function Xo(t){return`${t} ${t===1?"query":"queries"}`}function Fi(t){const{added:s,removed:n}=t;return[...s.length>0?[`${Xo(s.length)} added`]:[],...n.length>0?[`${s.length>0?n.length:Xo(n.length)} removed`]:[]].join(", ")}function Kc(t,s){const n=$s(t),a=Ra(t),r=jc(t,s);if(!n||!a||!r)return null;const l=sx(r.moves),i=Fc(n.start,n.end),c=d=>xr(d,i?n.start:null);return n.sweepCount===2?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes the ",e.jsx("strong",{children:c(n.start)})," sweep and the ",e.jsx("strong",{children:c(n.end)})," sweep, with ",l," between them"]}):r.moves.added.length+r.moves.removed.length>0?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point mixes sweeps with ",l," between them"]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," point pools ",e.jsx("strong",{children:n.sweepCount})," sweeps, with ",l," between the first and last"]})}function Yg(t,s,n){const a=Kc(s,n);return a?e.jsxs(e.Fragment,{children:["Not the same queries: ",a]}):t.changes.length>0?e.jsxs(e.Fragment,{children:["Not the same queries: ",t.changes.map((r,l)=>e.jsxs(o.Fragment,{children:[l>0?", ":"",Fi(r)," ",e.jsx("strong",{children:ja(Bt(r.at))})]},r.at)),"; first and latest points cover different queries"]}):e.jsxs(e.Fragment,{children:["Not the same queries: first and latest points have answers for ",e.jsx("strong",{children:t.firstCount})," and ",e.jsx("strong",{children:t.latestCount})," queries"]})}function Zo(t){return t.replace(/ /g," ")}function hr({state:t,from:s=!1}){return e.jsx("span",{className:s?"av-model av-model-from":"av-model",children:wa(t)})}function Jg(t,s){return t.reroute?"Same preset, answered with a different model.":dr(t.provider,t.to)?t.served?`Preset picks its own model. Answered with ${wa(t.served.to)} (was ${wa(t.served.from)}).`:s&&s.length>0?`Preset picks its own model. Answered with ${s.join(", ")}.`:"Preset picks its own model.":null}function Xg({buckets:t,queryChanges:s,modelRows:n,served:a,pointerNotices:r,truncated:l,incompleteHistory:i,queryName:c,sweepTimes:d}){const m=t.at(-1),u=g=>ja(g),p=new Map;for(const[g,v]of r){const C=n.find(T=>T.provider===g&&!T.reroute&&T.to.status==="known"&&v.modelIds.includes(T.to.model));C&&p.set(g,C)}const x=[];s.length>0&&x.push({key:"queries",label:"Queries",rows:s.map(g=>({key:`queries-${g.at}`,at:g.at,onOrBefore:!1,from:null,to:e.jsx("span",{className:"text-strong",children:Fi(g)}),toHelp:null}))});const h=[...new Set(n.map(g=>g.provider))].sort((g,v)=>ot(g).localeCompare(ot(v)));for(const g of h){const C=a[g]?.latestServedModelIds??null,T=n.filter(I=>I.provider===g);x.push({key:g,label:ot(g),rows:T.map((I,w)=>{const V=p.get(g)===I?r.get(g).text:null,F=[Jg(I,w===0?C:null),V].filter(Boolean).join(" ");return{key:`${g}-${I.at}-${I.reroute?"served":"set"}`,at:I.at,onOrBefore:I.onOrBefore,from:e.jsx(hr,{state:I.from,from:!0}),to:e.jsx(hr,{state:I.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?Ra(m):null;for(const[g,v]of Object.entries(m?gc(m)??{}:{}).sort(([C],[T])=>C.localeCompare(T)))v.status==="mixed"&&b&&f.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:b})," point mixes ",ot(g)," models: ",Op(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: ",xa(v)]}):`Changed before this date range: ${xa(v)}`);for(const g of l)f.push(`${ot(g.provider)}: most recent ${g.shown} of ${g.total} changes`);for(const g of i)f.push(`${ot(g)}: may be missing older changes`);for(const[g,v]of r)p.has(g)||f.push(e.jsxs("span",{className:"inline-flex items-center gap-1",children:[ot(g),": no model updates on record",e.jsx(Oe,{text:v.text})]}));if(y===0&&f.length===0)return null;for(const[g,v]of Object.entries(a).sort(([C],[T])=>ot(C).localeCompare(ot(T)))){const C=v.latestServedModelIds??[],T=C.length>0?C.join(", "):wa(v.latestObservation.state);f.push(e.jsxs(e.Fragment,{children:[ot(g)," last answered with ",e.jsx("strong",{children:T})," on ",e.jsx("strong",{children:u(Bt(v.latestObservation.observedAt))})]}))}const k=x.flatMap(g=>g.rows.map(v=>v.at));let $="First sweep on the new model or query set.";if(k.length>0){const g=u(k.reduce((V,F)=>Date.parse(F)>Date.parse(V)?F:V)),v=[...new Set(k.filter(V=>u(V)===g))].sort(),C=v.map(V=>xr(V,V));$+=` ${g} = the ${xa(C)} ${C.length===1?"sweep":"sweeps"}.`;const T=n.flatMap(V=>V.anchorAt?[V.anchorAt]:[]),I=T.length>0?T.reduce((V,F)=>Date.parse(F)>Date.parse(V)?F:V):null,w=Xp(v[0],d,t,I);w&&($+=` Sweep before: ${u(w)}.`)}const S=Jp({latest:m,queryChanges:s,modelRows:n})??"No changes in this date range";return e.jsxs("details",{className:"av-wc",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"av-card-title",children:"What changed"}),e.jsx("span",{className:"av-wc-summary av-wc-when-closed",children:S}),e.jsxs("span",{className:"av-wc-toggle",children:[e.jsxs("span",{className:"av-wc-when-closed",children:[y>0?`Show all ${y}`:"Details"," ",e.jsx("span",{"aria-hidden":"true",children:"▸"})]}),e.jsxs("span",{className:"av-wc-when-open",children:["Hide ",e.jsx("span",{"aria-hidden":"true",children:"▴"})]})]})]}),e.jsx("div",{className:"av-wc-body",children:y>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"av-change-table",children:[e.jsx("caption",{className:"sr-only",children:"Query and model changes, newest first"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Changed"})}),e.jsx("th",{scope:"col","aria-label":"Date",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:["Date",e.jsx(Oe,{text:$})]})}),e.jsx("th",{scope:"col",children:"From"}),e.jsx("th",{scope:"col",children:"To"})]})}),x.map(g=>e.jsx("tbody",{children:g.rows.map((v,C)=>e.jsxs("tr",{children:[C===0?e.jsx("th",{scope:"row",className:"av-engine",children:g.label}):e.jsx("td",{className:"av-engine",children:e.jsx("span",{className:"sr-only",children:g.label})}),e.jsx("td",{className:"av-date",children:v.onOrBefore?`on or before ${Zo(u(v.at))}`:Zo(u(v.at))}),v.from===null?null:e.jsx("td",{children:v.from}),e.jsx("td",{colSpan:v.from===null?2:void 0,children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[v.to,v.toHelp?e.jsx(Oe,{text:v.toHelp}):null]})})]},v.key))},g.key))]})}),e.jsx(Ca,{items:f})]}):e.jsx("ul",{className:"av-details-list",children:f.map((g,v)=>e.jsx("li",{children:g},v))})})]})}function Zg({substitutions:t}){return t.length===0?null:e.jsx("ul",{className:"space-y-3","aria-label":"Model substitutions",children:t.map(({provider:s,mismatch:n})=>e.jsxs("li",{className:"av-amber-row border border-caution-800/60 bg-caution-950/20",children:[e.jsx("span",{className:"av-engine",children:ot(s)}),e.jsxs("span",{className:"text-secondary",children:["selected ",e.jsx(hr,{state:n.configured})," · answered ",e.jsx(hr,{state:n.served})]}),e.jsx("span",{className:"av-status text-caution-400",children:"substituted"})]},s))})}function ef({active:t,label:s,payload:n,metric:a,mode:r,buckets:l,basketChanges:i}){if(!t)return null;const c=Wg(l,s);if(!c)return null;const d=$s(c),m=d!==null&&Fc(d.start,d.end)?d.start:null,u=bc(c,i),p=Oc(c),x=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-tooltip-label",children:Mi(c)}),u.map(f=>e.jsxs("p",{className:"trend-tooltip-detail trend-tooltip-note",children:[Fi(f)," ",xr(f.at,m)]},f.at))]}),h=p.length>0&&e.jsx("p",{className:"trend-tooltip-detail trend-tooltip-models",children:p.map((f,b)=>e.jsxs(o.Fragment,{children:[b>0?"; ":"",e.jsx("span",{className:"whitespace-nowrap",children:f})]},b))});if(a==="mentionShare"){const f=c.mentionShare.projectMentionSnapshots,b=c.mentionShare.competitorMentionSnapshots,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"?ka:Aa}];return e.jsxs("div",{className:"trend-tooltip",children:[x,y.map((f,b)=>{const j=String(f.dataKey??f.name??""),k=r==="byProvider"?Dc(c,j,a):null,$=k?.count??Oi(c,a),S=k?.total??c.total,g=k?k.rate:c[Ec(a)],v=f.color??ca(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:qc(j)}),e.jsx("span",{className:"trend-tooltip-value",children:tt(g)}),e.jsxs("span",{className:"trend-tooltip-count",children:[$," of ",S]})]})},`${j}-${b}`)}),h]})}function tf({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=Dc(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[Ec(s)])} ${gi(s).toLowerCase()}, ${Oi(l,s)} of ${l.total} answers`;const c=Oc(l);return c.length>0&&(i+=`; models: ${c.join("; ")}`),e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Mi(l)}),e.jsx("td",{children:i})]},l.startDate)})})]})})}function sf({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(()=>Tp(s,n),[s,n]),f=qe({queryKey:["analytics-metrics",t,c,y,a],queryFn:()=>cu(t,c),staleTime:Ri}),b=f.data??null,j=f.error,k=m==="mentionShare"?"overall":p,$=o.useMemo(()=>b?Up(b,m,k):null,[b,m,k]),S=b?$p(b):null,g=o.useMemo(()=>Kp(S??{}),[S]),v=o.useMemo(()=>Gp(S??{}),[S]),C=o.useMemo(()=>Object.entries(S??{}).filter(([,xe])=>xe.anchorUnavailable).map(([xe])=>xe).sort(),[S]),T=o.useMemo(()=>b?qp(b):{},[b]),I=o.useMemo(()=>b?zp(Ep(b)):[],[b]),w=o.useMemo(()=>b?yc(b):[],[b]),V=o.useMemo(()=>b?Hp(b):[],[b]),F=o.useMemo(()=>Yp(S??{},T),[S,T]),z=o.useMemo(()=>b?Dp(b):{},[b]),B=o.useMemo(()=>no(z,{engineName:ot}),[z]),Q=o.useMemo(()=>{const xe=new Map;for(const[Ae,et]of Object.entries(z).sort(([Le],[O])=>Le.localeCompare(O))){const Le=no({[Ae]:et},{engineName:ot});Le?.kind==="no-known-change"&&xe.set(Ae,{text:`${Le.text} ${Le.detail}`,modelIds:et.modelIds??[]})}return xe},[z]),se=o.useMemo(()=>{const xe=new Map(r.map(Ae=>[Bn(Ae),Ae]));return Ae=>xe.get(Bn(Ae))??Ae},[r]),K=m!=="mentionShare"&&k==="byProvider",U=b?.buckets??[],J=U[U.length-1]?.mentionShare.scope??b?.mentionShareScope??"pooled",q=Di(m,J),X=K?ms.textDim:m==="cited"?Jn.positive:m==="mentionShare"?qi:lt[1],L=o.useMemo(()=>{const xe=new Map(U.map(Ae=>[Ae.startDate,Ip(Ae)]));return Ae=>xe.get(String(Ae))??""},[U]),D=m==="mentionShare"?U.filter(xe=>typeof xe.mentionShare.rate=="number"&&Number.isFinite(xe.mentionShare.rate)):U,ee=D.at(-1),oe=(b?Bp(b,m):[]).at(-1)??null,we=b?Vp(b,m):null,Y=tx(D,w),ue=jo(Y,m,J,l),he=oe!==null&&we!==null?Vl(we.delta):null,Z=he!==null&&!ue,me=s.length,G=[];if(ee&&we!==null&&Y&&!ue&&G.push(Yg(Y,ee,w)),ee&&D.length===1){const xe=Kc(ee,w);xe&&!jo(jc(ee,w),m,J,l)&&G.push(xe)}if(he!==null&&D[0]){const xe=Ra(D[0]);xe&&G.push(e.jsxs(e.Fragment,{children:["Base: ",e.jsx("strong",{children:xe})," point"]}))}K&&oe!==null&&G.push(e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:tt(oe)})," pools all answers; not an average of engines"]}));const pe=[...new Set([...g.buckets.map(xe=>xe.bucketStartDate),...U.filter(xe=>bc(xe,w).length>0).map(xe=>xe.startDate)])].sort(),Ee=oe!==null&&ee&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:X},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:q}),e.jsx("span",{className:"visibility-trend-current-value",children:tt(oe)}),he!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${Z?"text-muted":Bg[he.direction]}`,children:[$c(he),Z?" (not the same queries)":""]}),e.jsxs("span",{className:"visibility-trend-current-detail",children:["· ",Hg(ee,m)]})]}),Re=e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(pa,{options:Gg,value:m,onChange:u,label:"Metric",className:"visibility-trend-metric-control"}),m!=="mentionShare"&&e.jsx(pa,{options:Kg,value:p,onChange:x,label:"Series"}),e.jsx(pa,{options:yg,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:fa(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"&&me===0)re=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!b||!$)re=null;else{const{rows:xe,series:Ae,hasData:et}=$;if(!et)re=e.jsx("p",{className:"text-sm text-secondary",children:m==="mentionShare"?`No answer-text brand mentions for you or tracked competitors in ${Ei(J)} in this window yet.`:ds()?Qn:"Run a sweep to start tracking citations and mentions over time."});else if(K&&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 Le=`${q} rate across ${xe.length} ${xe.length===1?"sweep":"sweeps"}. Latest ${tt(oe)}${he!==null?`, ${Vg(he)}${Z?", not the same queries":""}`:""}.`;re=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:Le}),e.jsx(tf,{buckets:U,metric:m,mode:k,series:Ae,mentionShareScope:J}),K&&Ae.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:Ae.map((O,ke)=>{const A=Qp(b,O,m);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:ca(O,ke)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:qc(O)}),A!==null&&e.jsx("span",{className:"trend-legend-value",children:tt(A)})]},O)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${q} trend chart over ${xe.length} ${xe.length===1?"point":"points"}`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:xe,margin:{top:8,right:20,bottom:0,left:0},children:[e.jsx(va,{stroke:ya,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Ut,tickLine:!1,axisLine:{stroke:us},tickFormatter:L,minTickGap:24}),e.jsx(tn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:O=>tt(O,Yn.percent),tick:Ut,tickLine:!1,axisLine:!1,width:40}),e.jsx(sn,{cursor:{stroke:us,strokeWidth:1},content:e.jsx(ef,{metric:m,mode:k,buckets:U,basketChanges:w})}),pe.map(O=>e.jsx(lp,{x:O,stroke:_g,strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`setup-change-${O}`)),Ae.map((O,ke)=>e.jsx(Ks,{type:"monotone",dataKey:O,name:O,stroke:ca(O,ke),strokeDasharray:O===_s?"5 4":void 0,strokeWidth:Qg(O)?2.5:2,dot:O===_s?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:ca(O,ke),strokeWidth:1.5}:{r:2.5,fill:ca(O,ke),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Ug},connectNulls:O!==_s,isAnimationActive:!1},O))]})})}),pe.length>0&&e.jsxs("p",{className:"visibility-trend-key",children:[e.jsx("span",{className:"visibility-trend-key-swatch","aria-hidden":"true"}),"Setup changed"]})]})}}return e.jsxs("div",{className:"visibility-trend-stack",children:[e.jsxs("section",{className:"visibility-trend","aria-labelledby":h,children:[e.jsxs("div",{className:"av-card-head",children:[e.jsxs("div",{className:"inline-flex items-center",children:[e.jsx("h2",{id:h,className:"av-card-title",children:"AI answers over time"}),e.jsx(Oe,{text:zg(J)})]}),ee?e.jsx("p",{className:"av-card-meta",children:Mi(ee)}):null]}),e.jsxs("div",{className:"visibility-trend-body",children:[B?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:B.text}),Ee,Re,re]}),e.jsx(Ca,{items:G})]}),b&&!j?e.jsxs(e.Fragment,{children:[e.jsx(Xg,{buckets:U,queryChanges:V,modelRows:F,served:T,pointerNotices:Q,truncated:v,incompleteHistory:C,queryName:se,sweepTimes:i}),e.jsx(Zg,{substitutions:I})]}):null]})}const el=new Set([ha.queued,ha.running]),_t={queryPlaceholder:"Write one research query per line",runAction:"Run queries",historyTitle:"Research history",historyMore:"Load older runs",historyLoading:"Loading older runs…",historyMoreError:"Could not load older research. Try again.",resultsTitle:"Research results",emptyHistory:"No saved research.",resultsEmpty:"Choose a saved run.",methodologySummary:"How matching works",methodology:"Brand-name matches use configured project names or domains in answer text. Project-domain citations use source links. Neither verifies property identity.",refreshPreview:"Regenerate preview",templateProvenance:"Query pattern details",brandedQuery:"Branded",discoveryQuery:"Discovery",unclassifiedQuery:"Unclassified"};function tl({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d=[],viewerResearchConfig:m=null}){const u=hs(),{account:p,canWrite:x}=nn(),h=p?.role==="viewer"&&m!==null,y=!x,f=Ls(),[b,j]=o.useState(""),[k,$]=o.useState(""),[S,g]=o.useState(null),[v,C]=o.useState([]),T=o.useRef(null),I=o.useRef(!1),[w,V]=o.useState(0),F=qe({...mu({client:W,path:{name:t}}),staleTime:6e4}),z=qe({...hu({client:W}),enabled:!y&&!f,staleTime:6e4}),B={client:W,path:{name:t},query:{limit:20}},Q=Ml({...pu(B),initialData:void 0,initialPageParam:B,getNextPageParam:G=>G.nextCursor?{path:B.path,query:{...B.query,cursor:G.nextCursor}}:void 0,refetchInterval:G=>G.state.data?.pages.some(pe=>pe.runs.some(Ee=>el.has(Ee.status)))?3e3:!1}),se=Q.isError&&!Q.isFetchNextPageError,K=Q.data?.pages.at(-1),U=se?[]:[...new Map((Q.data?.pages.flatMap(G=>G.runs)??[]).map(G=>[G.id,G])).values()],J=K?.access?.canRun??(x||h),q=K?.access?K.access.dailyRunLimit:h?m.viewerDailyRunLimit:null;o.useEffect(()=>{!S&&U[0]&&g(U[0].id)},[U,S]);const X=U.find(G=>G.id===S)??null,L=qe({...xu({client:W,path:{name:t,runId:S??""}}),enabled:!se&&!!S,refetchInterval:X&&el.has(X.status)?3e3:!1}),D=se||L.isError?null:L.data??null,ee=F.data?.locations??[],ne=o.useMemo(()=>{if(y)return(K?.providers??[]).map(pe=>({...pe,catalog:pe}));const G=new Map((z.data?.providerCatalog??[]).map(pe=>[pe.name,pe]));return(z.data?.providers??[]).filter(pe=>pe.configured&&G.get(pe.name)?.mode==="api").map(pe=>({...pe,catalog:{...G.get(pe.name),defaultModel:pe.model||G.get(pe.name).defaultModel}}))},[y,K?.providers,z.data]),oe=!(y?Q.isPending:z.isPending)&&ne.length===0,we=ne.find(G=>G.name===b)??null;o.useEffect(()=>{if(!b&&F.data&&!F.isError&&!z.isError){const G=F.data.providers.find(pe=>ne.some(Ee=>Ee.name===pe));j(G??ne[0]?.name??"")}},[b,ne,F.data,F.isError,z.isError]);const Y=we?.catalog.modelConfigurable??!1,ue=y?we?.catalog.defaultModel:(we?F.data?.providerModels[we.name]:"")||we?.catalog.defaultModel,he=(Y?k.trim():"")||ue,Z=we?[...new Map([{id:we.catalog.defaultModel,displayName:we.catalog.defaultModel},...k.trim()?[{id:k.trim(),displayName:k.trim()}]:[],...we.catalog.knownModels].map(G=>[G.id,G])).values()]:[],me=Et({...gu(),onSuccess:async G=>{T.current=null,V(pe=>pe+1),C(G.runs),g(G.runs[0]?.id??null),await hf(u),De({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(pe=>pe.id).join(":")}`,dedupeMode:"replace"})},onError:G=>{De({title:"Could not start research",detail:G instanceof Error?G.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{I.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[f?e.jsx(je,{className:"surface-card min-w-0",children:e.jsx("p",{className:"text-sm text-secondary",children:"This public demo shows saved research results. Running research is unavailable."})}):e.jsxs(e.Fragment,{children:[e.jsx(nf,{projectName:t,canWrite:x,researchAllowed:J&&!se,limitedAccess:y,isEmbed:ie(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:l,scopeError:i,onRetryScope:c,templates:d,locations:ee,defaultLocation:F.data?.defaultLocation??null,providerOptions:ne,provider:b,onProviderChange:G=>{j(G),$("")},resolvedModel:he,visibilityModel:ue,configurableModel:Y,model:k,onModelChange:$,modelOptions:Z,settingsReady:y?!Q.isPending&&!se:!z.isPending&&!z.isError&&!z.isFetching,projectReady:!F.isPending&&!F.isError&&!F.isFetching,isPending:me.isPending,errorMessage:me.isError?"The request could not be confirmed.":void 0,onSubmit:(G,pe)=>{!J||se||ie()||I.current||(T.current?.fingerprint!==pe&&(T.current={fingerprint:pe,key:crypto.randomUUID()}),I.current=!0,me.mutate({client:W,path:{name:t},body:{...G,idempotencyKey:T.current.key}}))}},`${t}:${w}`),q!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",q," 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(P,{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(P,{variant:"outline",onClick:()=>{F.refetch()},children:"Retry locations"})]}):null,!(y?se: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,pe)=>e.jsxs("span",{children:[pe>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(je,{className:"surface-card min-w-0",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsx("div",{children:e.jsx("h3",{children:_t.historyTitle})}),Q.isFetching&&e.jsx(Ne,{tone:"neutral",children:"Loading"})]}),se?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(P,{variant:"outline",onClick:()=>{Q.refetch()},children:"Retry history"})]}):Q.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):U.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:_t.emptyHistory}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Destination"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:U.map(G=>e.jsxs("tr",{className:S===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:df(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(Ne,{tone:Gc(G.status),children:G.status})})]},G.id))})]})}),Q.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:_t.historyMoreError}),Q.hasNextPage&&e.jsx(P,{className:"mt-3",variant:"outline",disabled:Q.isFetching,onClick:()=>{Q.fetchNextPage()},children:Q.isFetchingNextPage?_t.historyLoading:_t.historyMore})]})]}),!se&&L.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(P,{variant:"outline",onClick:()=>{L.refetch()},children:"Retry results"})]}):se?null:e.jsx(lf,{detail:D,isLoading:L.isFetching,onReviewForTracking:f?void 0:s})]})}const Is="mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50",Fn="__none__";function nf(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:l}=t,i=hs(),[c,d]=o.useState("once"),[m,u]=o.useState(""),[p,x]=o.useState(""),[h,y]=o.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[f,b]=o.useState(null),[j,k]=o.useState([]),[$,S]=o.useState(""),[g,v]=o.useState({}),[C,T]=o.useState(null),[I,w]=o.useState([]),[V,F]=o.useState(null),[z,B]=o.useState(!1),[Q,se]=o.useState(!1),[K,U]=o.useState(""),[J,q]=o.useState(""),X=o.useRef(null),L=o.useRef(!1),D=o.useRef(null),ee=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";o.useEffect(()=>{y(ee),T(null)},[ee]);const ne=t.scopeOptions.filter(R=>R.kind==="market"||R.kind==="property"),oe=c==="markets"?"market":"property",we=ne.filter(R=>R.kind===oe),Y=R=>({kind:R.kind,key:R.id,label:R.label,planRevision:l??t.initialScope?.planRevision??0}),ue=R=>R===Fn?null:n.find($e=>$e.label===R),he=f??t.defaultLocation??Fn,Z=ne.find(R=>`${R.kind}:${R.id}`===h),me=Z?Y(Z):null,G=c==="once"?[{scope:me,location:ue(he)}]:c==="locations"?j.map(R=>({scope:null,location:ue(R)})):j.map(R=>we.find($e=>`${$e.kind}:${$e.id}`===R)).map(R=>R?{scope:Y(R),location:ue(g[`${R.kind}:${R.id}`]??Fn)}:null),pe=[...new Map([...I,...t.templates].map(R=>[R.id,R])).values()],Ee=C?pe.find(R=>R.id===C.id):null,Re=C!==null&&Ee?.version!==C.version,re=c==="once"?m:p,xe=re.split(/\r?\n/).filter(R=>R.trim()),Ae=ao(xe),et=[...new Set([...p.matchAll(/\{([^{}]+)\}/g)].map(R=>R[1]))],Le=/[{}]/.test(p.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),O=[];xe.length||O.push(c==="once"?"Enter at least one query.":"Enter at least one query pattern."),xe.some(R=>R.length>4e3)&&O.push("Keep each query under 4,001 characters."),c!=="once"&&Le&&O.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),G.length||O.push(c==="locations"?"Select at least one location.":"Select at least one destination."),G.some(R=>!R||R.location===void 0)&&O.push("A selected destination or location is no longer available. Update your selection.");const ke=c==="once"&&h!=="project"||c==="markets"||c==="properties";ke&&(t.scopePending||t.scopeError||!l||G.some(R=>!R?.scope))&&O.push("Load the current published markets and properties before running scoped research.");const A=(c==="once"?Ae.length:xe.length)*G.length;if(G.length>Ea&&O.push(`Select at most ${Ea} destinations.`),A>Cr&&O.push(`${A} queries selected. Reduce the selection to ${Cr} or fewer.`),Re&&O.push("This saved pattern changed. Select its current version from Saved patterns."),c!=="once"&&!Le){for(const R of G)if(!(!R||R.location===void 0))try{Sr(C??{pattern:p,variables:et},R.scope,R.location)}catch{O.push(`Choose a location for {location}, or use only variables available for ${c==="markets"?"markets":c==="properties"?"properties":"locations"}.`);break}}const be=JSON.stringify({mode:c,source:re,contexts:G,provider:a,resolvedModel:r,template:C,...ke?{planRevision:l}:{}}),Ke=V!==null&&V.signature!==be,Ve=c==="once"?Ae.map((R,$e)=>({id:String($e),query:R,scope:me,location:G[0]?.location??null})):V?.rows??[],Ge=of(Ve),ge=[];c!=="once"&&V&&(Ke&&ge.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),Ve.some(R=>!R.query.trim()||R.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(R.query))&&ge.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),Ve.some(R=>R.location&&!n.some($e=>JSON.stringify($e)===JSON.stringify(R.location)))&&ge.push("A preview location changed. Regenerate the preview."),Ge.some(R=>ao(R.queries).length!==R.queries.length)&&ge.push("Remove duplicate queries within each destination and location."),Ge.length>Ea&&ge.push(`The preview exceeds ${Ea} runs.`));const vt=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!O.length&&!ge.length&&(c==="once"||V!==null),Qe=()=>({runs:Ge.map(R=>({queries:R.queries,provider:a,model:r,location:R.location,...R.scope?{scope:{kind:R.scope.kind,key:R.scope.key,expectedPlanRevision:R.scope.planRevision}}:{},...R.template?{template:R.template}:{}}))}),Je=()=>{if(B(!0),O.length)return;const R=G.flatMap(($e,Ie)=>xe.map((Fe,dt)=>({id:`${Ie}:${dt}`,scope:$e.scope,location:$e.location,...C?{template:{templateId:C.id,templateVersion:C.version,bindingLocation:$e.location}}:{},query:Sr({pattern:Fe,variables:[...new Set([...Fe.matchAll(/\{([^{}]+)\}/g)].map(ze=>ze[1]))]},$e.scope,$e.location).output})));F({signature:be,rows:R})},Dt=R=>{d(R),k([]),T(null),S(""),B(!1)},ct=R=>{if(q(""),c==="once")try{u(Sr(R,me,ue(he)).output)}catch{q("Select a matching market, property, or location before using this pattern.");return}else x(R.pattern);T(R)},at=R=>{const $e=D.current,Ie=$e?.selectionStart??p.length,Fe=$e?.selectionEnd??Ie;x(`${p.slice(0,Ie)}{${R}}${p.slice(Fe)}`),T(null),requestAnimationFrame(()=>{$e?.focus(),$e?.setSelectionRange(Ie+R.length+2,Ie+R.length+2)})},pt=Et({...yu(),onSuccess:async R=>{const $e={id:R.id,version:R.updatedAt,label:R.name,pattern:R.pattern,variables:R.variables};w(Ie=>[...Ie.filter(Fe=>Fe.id!==R.id),$e]),T($e),se(!1),U(""),q(""),X.current=null,await i.invalidateQueries({queryKey:fu({client:W,path:{name:s}})}),De({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>q("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{L.current=!1}}),Ct=()=>{if(!t.canWrite||t.isEmbed||L.current)return;const R=c==="once"?m:p,$e=c==="once"?[]:et;if(!K.trim()||!R.trim()||R.length>4e3||c!=="once"&&Le){q("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const Ie={name:K.trim(),pattern:R,variables:$e},Fe=JSON.stringify(Ie);X.current?.fingerprint!==Fe&&(X.current={fingerprint:Fe,id:crypto.randomUUID()}),L.current=!0,pt.mutate({client:W,path:{name:s,templateId:X.current.id},body:Ie})},It=[...new Set([...z||re.trim()?O:[],...ge])],He=pe.filter(R=>{const $e=c==="once"?ro(me,ue(he)):ro(c==="markets"?{kind:"market",label:"Market"}:c==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return R.variables.every(Ie=>$e[Ie]!==void 0)});return e.jsxs(je,{className:"surface-card min-w-0",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Test queries"}),e.jsx("p",{className:"mt-1 max-w-prose text-sm text-secondary",children:"See how an answer engine responds. Results are saved separately from tracked queries and AI Visibility metrics."})]})}),e.jsxs("fieldset",{"aria-label":"Research setup",className:"mt-5 min-w-0 space-y-5",disabled:t.isPending||pt.isPending,children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Run mode"}),e.jsxs("select",{className:Is,value:c,disabled:t.isPending,onChange:R=>Dt(R.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!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:Is,value:h,onChange:R=>{y(R.target.value),T(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:he,locations:n,onChange:R=>{b(R),T(null)}})]}),c!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:c==="locations"?"Select locations":`Select ${c}`}),e.jsx("p",{className:"text-sm text-secondary",children:"Choose each destination explicitly. Each selected destination gets its own saved research run."}),e.jsx("input",{type:"search","aria-label":"Search destinations",className:Is,placeholder:`Search ${c}`,value:$,onChange:R=>S(R.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(c==="locations"?n.map(R=>({key:R.label,label:R.label})):we.map(R=>({key:`${R.kind}:${R.id}`,label:R.label}))).filter(R=>R.label.toLocaleLowerCase().includes($.toLocaleLowerCase())).map(R=>{const $e=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:$e,onChange:()=>k(Ie=>$e?Ie.filter(Fe=>Fe!==R.key):[...Ie,R.key])}),R.label]}),$e&&c!=="locations"&&e.jsx(fi,{label:`Answer engine location for ${R.label}`,value:g[R.key]??Fn,locations:n,onChange:Ie=>v(Fe=>({...Fe,[R.key]:Ie}))})]},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(P,{variant:"outline",onClick:t.onRetryScope,children:"Retry destinations"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block",htmlFor:"research-query-editor",children:e.jsx("span",{className:"text-sm font-medium text-heading",children:c==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:c==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${c==="markets"?"market":c==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:D,className:`${Is} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:re,placeholder:c==="once"?_t.queryPlaceholder:c==="markets"?"Best apartments in {market}":c==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:R=>{c==="once"?u(R.target.value):(x(R.target.value),T(null))}}),c!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(P,{size:"sm",variant:"outline",onClick:()=>at(c==="markets"?"market":c==="properties"?"property":"location"),children:["Insert ",c==="markets"?"market":c==="properties"?"property":"location"," name"]}),e.jsx("span",{className:"self-center text-sm text-secondary",children:"One pattern per line."})]}),e.jsxs("p",{id:"research-query-count",className:"mt-2 text-sm text-secondary",children:[A," / ",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."}),He.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:He.map(R=>e.jsx(P,{size:"sm",variant:"outline",onClick:()=>ct(R),children:R.label},R.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),C&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",C.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(P,{size:"sm",variant:"outline",onClick:()=>se(!Q),children:Q?"Cancel save":"Save as a pattern"}),Q&&e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("label",{className:"min-w-48 flex-1 text-sm text-heading",children:["Pattern name",e.jsx("input",{className:Is,value:K,maxLength:120,onChange:R=>U(R.target.value)})]}),e.jsx(P,{size:"sm",disabled:pt.isPending||!K.trim()||!re.trim(),onClick:Ct,children:pt.isPending?"Saving…":"Save pattern"})]})]}),J&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:J})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Answer engine",e.jsxs("select",{className:Is,value:a,onChange:R=>t.onProviderChange(R.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose an answer engine"}),t.providerOptions.map(R=>e.jsx("option",{value:R.name,children:R.displayName??R.name},R.name))]})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Model",t.limitedAccess?e.jsxs("select",{className:Is,value:t.model,disabled:!a||!t.configurableModel,onChange:R=>t.onModelChange(R.target.value),children:[e.jsxs("option",{value:"",children:["Use AI Visibility model · ",t.visibilityModel]}),t.modelOptions.map(R=>e.jsx("option",{value:R.id,children:R.displayName},R.id))]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{"aria-label":"Model",className:Is,list:"research-known-models",placeholder:r??"Choose an answer engine",value:t.model,disabled:!a||!t.configurableModel,onChange:R=>t.onModelChange(R.target.value)}),e.jsx("datalist",{id:"research-known-models",children:t.modelOptions.map(R=>e.jsx("option",{value:R.id,children:R.displayName},R.id))})]})]})]}),It.length>0&&e.jsx(rf,{errors:It}),c!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:Je,children:[e.jsx(ba,{size:14}),V?_t.refreshPreview:"Preview queries"]}),V&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Queries to run"}),e.jsxs("p",{className:"text-sm text-secondary",children:[Ve.length," query executions in ",Ge.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(af,{rows:Ve,locations:n,onChange:(R,$e)=>F(Ie=>Ie&&{...Ie,rows:Ie.rows.map(Fe=>Fe.id===R?{...Fe,...$e}:Fe)})})]})]}),t.errorMessage&&e.jsxs("p",{role:"alert",className:"text-sm text-negative",children:[t.errorMessage," Your entries are preserved. Retry unchanged entries to avoid duplicate work."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!t.isEmbed&&e.jsxs(P,{size:"sm",disabled:!vt,onClick:()=>{if(vt){const R=Qe();t.onSubmit(R,JSON.stringify({projectName:s,...R}))}},children:[e.jsx(lr,{size:14}),t.isPending?"Starting…":_t.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[c==="once"?`${Ae.length} queries`:`${Ve.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function fi({label:t,value:s,locations:n,onChange:a}){return e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:t}),e.jsxs("select",{className:Is,value:s,onChange:r=>a(r.target.value),children:[e.jsx("option",{value:Fn,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function af({rows:t,locations:s,onChange:n}){return e.jsx("ol",{className:"divide-y divide-default",children:t.map((a,r)=>e.jsxs("li",{className:"grid gap-3 py-4 md:grid-cols-[10rem_minmax(0,1fr)_15rem]",children:[e.jsxs("div",{className:"text-sm",children:[e.jsxs("span",{className:"block text-secondary",children:["Query ",r+1]}),e.jsx("span",{className:"font-medium text-heading",children:a.scope?.label??a.location?.label??"Whole site"}),a.scope&&e.jsx("span",{className:"block text-secondary",children:a.scope.kind})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Query",e.jsx("textarea",{className:`${Is} min-h-20`,"aria-label":`Query ${r+1} for ${a.scope?.label??a.location?.label??"Whole site"}`,value:a.query,onChange:l=>n(a.id,{query:l.target.value})})]}),e.jsx(fi,{label:`Location for query ${r+1}`,value:a.location?.label??Fn,locations:s,onChange:l=>n(a.id,{location:s.find(i=>i.label===l)??null})})]},a.id))})}function rf({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 of(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 lf({detail:t,isLoading:s,onReviewForTracking:n}){const[a,r]=o.useState(null);o.useEffect(()=>{r(t?.queries[0]?.id??null)},[t?.id]);const l=t?.queries.find(i=>i.id===a)??t?.queries[0]??null;return e.jsxs(je,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":_t.resultsTitle,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Results"}),e.jsx("h3",{children:t?`Research run ${uf(t.id)}`:_t.resultsEmpty})]}),t&&e.jsx(Ne,{tone:Gc(t.status),children:t.status})]}),t&&e.jsxs("div",{className:"mt-3 space-y-3 text-sm text-secondary",children:[e.jsxs("dl",{className:"flex flex-wrap gap-x-6 gap-y-2 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Answer engine"}),e.jsx("dd",{children:t.provider})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Requested model"}),e.jsx("dd",{className:"font-mono",children:t.requestedModel??t.resolvedModel})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Location"}),e.jsx("dd",{children:t.location?.label??"No location"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Destination"}),e.jsx("dd",{children:t.scope?.label??"Whole site"})]})]}),t.template&&e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:_t.templateProvenance}),e.jsxs("dl",{className:"mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Saved pattern"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.template})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Names used"}),e.jsx("dd",{children:Object.entries(t.template.bindings).map(([i,c])=>`${i}: ${c}`).join(" · ")||"No variables"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Original resolved text"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.output})]})]}),e.jsx("p",{className:"mt-2",children:"The queries below are the final text sent to the answer engine, including any edits."}),e.jsxs("p",{className:"mt-2 font-mono text-xs",children:[t.template.templateId," · ",t.template.templateVersion]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:_t.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:_t.methodology})]})]}),t?e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Class"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Brand-name match"}),e.jsx("th",{children:"Project domain cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:l?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>r(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(Ne,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?_t.brandedQuery:i.queryClass==="non-brand"?_t.discoveryQuery:_t.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(Ne,{tone:mf(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(Ne,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===Nn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===Nn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(Ne,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===Nn.failed?"negative":"caution",children:i.citationState===null?i.status===Nn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(cf,{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 cf({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(Ye,{type:"button",size:"sm",onClick:()=>a({researchRunQueryId:t.id,scope:n}),children:"Review for tracking"}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Only this saved query text enters tracking review. Its answer remains research evidence."})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("div",{className:"mt-1",children:e.jsx(Ti,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===Nn.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r},r))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r.replace(/^www\./,"")},r))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-3",children:t.groundingSources.map((r,l)=>e.jsx("li",{className:"min-w-0",children:e.jsx(ki,{url:r.uri,title:r.title})},`${r.uri}-${l}`))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function df(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 uf(t){return t.length>8?t.slice(0,8):t}function Gc(t){return t===ha.completed?"positive":t===ha.partial?"caution":t===ha.failed?"negative":"neutral"}function mf(t){return t===Nn.completed?"positive":t===Nn.failed?"negative":"neutral"}async function hf(t){await $t(t,"researchRuns")}const yi=new Set(["queued","seeding","probing"]);function pf({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:l={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d}){const{account:m}=nn(),[u,p]=o.useState("tracked"),[x,h]=o.useState("find"),[y,f]=o.useState(null),b=m?.role==="viewer"?Wl():null,j=dc(m?.role,b),$=uc(s??u,j),S=a??x,g=T=>{s===void 0&&p(T),n?.(T)},v=T=>{a===void 0&&h(T),r?.(T)},C=(T,I)=>{const w=I===void 0?{...l}:{...l,measurementScope:I?.kind??"project",measurementScopeKey:I?.key};f({...T,trackingSelection:w}),I!==void 0&&i?.({measurementScope:w.measurementScope,measurementScopeKey:w.measurementScopeKey}),g("tracked")};return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"queries-heading",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"queries-heading",children:"Queries"})}),e.jsxs("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Query workspace",children:[e.jsx(pr,{active:$==="tracked",label:"Tracked",onClick:()=>g("tracked")}),j?e.jsx(pr,{active:$==="research",label:"Research",onClick:()=>g("research")}):null]}),e.jsx("div",{className:"mt-4",children:$==="tracked"?e.jsx($f,{projectName:t,selection:l,onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d,pendingTrackingSource:y,onPendingTrackingSourceHandled:()=>f(null)}):e.jsx(xf,{projectName:t,selection:l,mode:S,onModeChange:v,onReviewSavedSource:C,onSelectionChange:i,viewerResearchConfig:b})})]})}function pr({active:t,label:s,onClick:n}){return e.jsx("button",{type:"button",role:"tab","aria-selected":t,className:`-mb-px border-b-2 px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500 focus-visible:ring-inset ${t?"border-mono-400 text-heading":"border-transparent text-muted hover:border-strong hover:text-strong"}`,onClick:n,children:s})}function xf({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:l}){const{canWrite:i}=nn(),c=!i||n==="test",d=qe({...Ii({client:W,path:{name:t}}),enabled:c,staleTime:6e4}),m=qe({...Yl({client:W,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 k of y.get(j.targetKey)??[])f.get(b.stableKey)?.add(k);return[{id:"project",label:"Whole site",kind:"project",targetCount:h.targets.length},...h.groups.map(b=>({id:b.stableKey,label:b.label,kind:"group",targetCount:b.targetKeys.length,...b.parentGroupKey?{parentGroupIds:[b.parentGroupKey]}:{}})),...h.markets.map(b=>{const 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(pr,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(pr,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(qf,{projectName:t,onReviewDiscoveryProbe:h=>r({source:"discovery",discoveryProbeId:h})}):e.jsx(tl,{...x,onReviewForTracking:({researchRunQueryId:h,scope:y})=>r({source:"research",researchRunQueryId:h},y??null)})})]}):e.jsx(tl,{...x,viewerResearchConfig:l})}function gf({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i,templates:c,preview:d,isPreviewing:m,isCommitting:u,onPreview:p,onCommit:x}){const[h,y]=o.useState(null),[f,b]=o.useState(()=>rr(s)),[j,k]=o.useState(null),$=o.useRef(null),S=o.useRef(null),g=mc(t,s),v=o.useMemo(()=>vf(t.tracked,s,t.mode),[s,t.mode,t.tracked]),C=wn({rows:v,getSearchText:Q=>`${Q.queryText} ${Q.provenance?.source??"legacy"} ${Q.assignments.map(se=>se.queryClass??"unknown").join(" ")}`});o.useEffect(()=>{if(g)return;if(!a){S.current=null;return}const Q=`${a}:${_r(s)}`;if(S.current===Q)return;const se=t.tracked.find(K=>K.queryId===a);se&&(S.current=Q,y({kind:"edit",row:se,audience:t.mode==="advanced"?Kr(s):void 0,scopeLabel:Gr(s,t)}),b(sl(se,s)),k(null))},[s,a,g,t]),o.useEffect(()=>{if(g||!l)return;const Q=rr(l.trackingSelection??s);y({kind:"add"}),b(l.source==="research"?{...Q,source:"research",researchRunQueryId:l.researchRunQueryId}:{...Q,source:"discovery",discoveryProbeId:l.discoveryProbeId}),k(null),i()},[i,l,s,g]),o.useEffect(()=>{g&&(y(null),k(null),a!==void 0&&r?.(void 0))},[r,a,g]),o.useEffect(()=>{if(!h||h.kind==="remove")return;const Q=$.current;Q&&(Q.scrollIntoView?.({block:"start"}),Q.focus({preventScroll:!0}))},[h]);function T(Q="manual"){y({kind:"add"}),b({...rr(s),source:Q}),k(null),r?.(void 0)}function I(Q){S.current=`${Q.queryId}:${_r(s)}`,y({kind:"edit",row:Q,audience:t.mode==="advanced"?Kr(s):void 0,scopeLabel:Gr(s,t)}),b(sl(Q,s)),k(null),r?.(Q.queryId)}function w(Q){S.current=`${Q.queryId}:${_r(s)}`,y({kind:"remove",row:Q,audience:t.mode==="advanced"?Kr(s):void 0,scopeLabel:Gr(s,t)}),k(null),r?.(Q.queryId)}function V(){y(null),k(null),r?.(void 0)}const F=h?ff(h,f,t.mode):null,z=h!==null&&h.kind==="add"&&t.mode==="advanced"&&!Ki(f),B=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(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>n?.({measurementScope:"project",measurementScopeKey:void 0}),children:"Show whole site"})]})}):e.jsxs("div",{className:"query-tracking-workspace space-y-4",children:[e.jsxs("section",{"aria-label":"Tracked queries",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[t.mode==="advanced"?e.jsx(jf,{selection:s,onSelectionChange:n}):null,e.jsx(Js,{value:C.query,onChange:C.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!ie()&&e.jsxs(Ye,{type:"button",size:"sm",onClick:()=>T(),children:[e.jsx(tp,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[C.totalRows.toLocaleString("en-US")," saved query ",C.totalRows===1?"record":"records"," in this view. Each record can have more than one property, group, or market assignment."]}),s.measurementScope==="group"?e.jsx("p",{className:"mt-1 text-xs leading-5 text-secondary",children:"Queries belong to properties, so a shared query can also cover other groups."}):null,t.active?null:e.jsx("p",{className:"mt-3 text-sm text-caution",children:"No published measurement yet."}),C.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:C.hasQuery?"No tracked queries match that search.":"No tracked queries in this scope yet."}):e.jsx("div",{className:"mt-5 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table min-w-[760px] table-auto",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Scope"}),t.mode==="advanced"?e.jsx("th",{children:"Class"}):null,e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Measurement"}),e.jsx("th",{className:"measurement-table-actions",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:C.rows.map(Q=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:Q.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(wf,{row:Q,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Cf,{row:Q})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:Nf(Q)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(kf,{row:Q,outsidePlan:t.mode==="advanced"&&Q.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(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${Q.queryText}`,onClick:()=>I(Q),children:[e.jsx(sp,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${Q.queryText}`,onClick:()=>w(Q),children:[e.jsx(cc,{"aria-hidden":"true",size:13})," Remove"]})]})})]},Q.queryId))})]})}),e.jsx(Gs,{page:C.page,pageSize:C.pageSize,visibleRows:C.rows.length,totalRows:C.totalRows,itemLabel:"queries",onPageChange:C.setPage})]}),h&&!ie()&&e.jsx(Af,{workspace:t,templates:c,action:h,draft:f,onDraftChange:Q=>{b(Q),k(null)},onClose:V,canReview:B,isPreviewing:m,editorHeadingRef:$,onReview:()=>{F&&(k(F),p(F))}}),d&&j&&h&&e.jsx(Tf,{preview:d,workspace:t,isCommitting:u,onConfirm:()=>{x({...j,expectedWorkspaceVersion:d.workspaceVersion,previewToken:d.previewToken,reviewedAt:d.reviewedAt})}})]})}function rr(t){return{source:"manual",text:"",templateId:"",templateVersion:"",template:"",researchRunQueryId:"",discoveryProbeId:"",wholeSite:t.measurementScope==="project"||!t.measurementScopeKey,targetKeys:t.measurementScope==="property"&&t.measurementScopeKey?[t.measurementScopeKey]:[],groupKeys:t.measurementScope==="group"&&t.measurementScopeKey?[t.measurementScopeKey]:[],marketKeys:t.measurementScope==="market"&&t.measurementScopeKey?[t.measurementScopeKey]:[],contexts:[],queryClass:"auto"}}function sl(t,s){return{...rr(s),text:t.queryText,queryClass:"keep"}}function ff(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=yf(s);if(!a||bi(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=bf(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 yf(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 bf(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 vf(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 jf({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 Nf(t){switch(t.provenance?.source){case"manual":return"Manual";case"template":return"Template";case"research":return"Saved research";case"discovery":return"Discovery";default:return"Legacy"}}function _c(t,s,n){const a=new Map(s.targets.map(f=>[f.stableKey,f.label])),r=new Map(s.groups.map(f=>[f.stableKey,f.label])),l=new Map(s.markets.map(f=>[f.stableKey,f.label])),i=new Set(t.assignments.map(f=>f.targetKey));if(i.size===0)return"Whole site";const c=n?t.assignments.filter(f=>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 wf({row:t,workspace:s,selection:n}){const a=Sf(t,s,n);return e.jsxs("details",{className:"group min-w-48",children:[e.jsx("summary",{className:"cursor-pointer rounded px-1 py-1 text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:_c(t,s,n)}),e.jsxs("div",{className:"mt-2 rounded border border-default bg-surface p-2 text-xs leading-5 text-secondary",children:[e.jsx("p",{className:"font-medium text-strong",children:"Assigned relationships"}),e.jsx("ul",{className:"mt-1 list-disc space-y-1 pl-4",children:a.map(r=>e.jsx("li",{children:r},r))})]})]})}function Sf(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 Cf({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(Ne,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function kf({row:t,outsidePlan:s=!1}){return s?e.jsx(Ne,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(Ne,{tone:"positive",children:"Measured"}):e.jsx(Ne,{tone:"caution",children:"Awaiting sweep"})}function Af({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:l,canReview:i,isPreviewing:c,editorHeadingRef:d,onReview:m}){const u=s.length>0;return n.kind==="remove"?e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Remove query"}),e.jsxs("p",{className:"mt-1 text-sm leading-6 text-secondary",children:["Remove “",n.row.queryText,"” from future tracking?"]}),e.jsxs("p",{className:"mt-1 text-sm leading-5 text-secondary",children:[n.audience?`Only assignments in ${n.scopeLabel} will be removed.`:"All assignments will be removed."," Earlier results stay unchanged."]})]})}),e.jsx(Ur,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]}):n.kind==="edit"?e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Edit query"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("p",{className:"mt-3 text-sm leading-6 text-secondary",children:[n.audience?`Changes apply only to assignments in ${n.scopeLabel}.`:"Changes apply to every assignment of this query."," Earlier results stay unchanged."]}),e.jsxs("div",{className:"mt-4 max-w-2xl space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Query text"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.text,onChange:p=>r({...a,text:p.target.value})})]}),t.mode==="advanced"&&e.jsxs("label",{className:"block",htmlFor:"tracking-query-class",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:p=>r({...a,queryClass:p.target.value}),children:[e.jsx("option",{value:"keep",children:"Keep existing classifications"}),e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Existing locations and engines are preserved. Use Add query to create assignments in another scope."})]}),e.jsx(Ur,{canReview:i,isPreviewing:c,onCancel:l,onReview:m})]}):e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Add query"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Cancel"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-[minmax(250px,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[a.source==="manual"?e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Question"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",placeholder:"e.g. How do teams compare AEO platforms?",value:a.text,onChange:p=>r({...a,text:p.target.value})})]}):null,a.source==="template"?e.jsx(Rf,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(nl,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(p=>({id:p.researchRunQueryId,label:p.queryText,detail:p.researchRunId})),onChange:p=>r({...a,researchRunQueryId:p})}):null,a.source==="discovery"?e.jsx(nl,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(p=>({id:p.discoveryProbeId,label:p.queryText,detail:p.discoverySessionId})),onChange:p=>r({...a,discoveryProbeId:p})}):null,e.jsxs("label",{className:"block",htmlFor:"tracking-query-source",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Query source"}),e.jsxs("select",{id:"tracking-query-source","aria-describedby":u?void 0:"tracking-query-source-no-templates",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.source,onChange:p=>r({...a,source:p.target.value}),children:[e.jsx("option",{value:"manual",children:"Write a question"}),u?e.jsx("option",{value:"template",children:"Saved template"}):null,e.jsxs("option",{value:"research",disabled:t.savedSources.research.length===0,children:["Saved research",t.savedSources.research.length===0?" (none available)":""]}),e.jsxs("option",{value:"discovery",disabled:t.savedSources.discovery.length===0,children:["Discovery result",t.savedSources.discovery.length===0?" (none available)":""]})]})]}),u?null:e.jsx("p",{id:"tracking-query-source-no-templates",className:"text-sm leading-6 text-secondary",children:"No saved templates are set up for this portfolio. Write a question, or use saved research or a discovery result."})]}),e.jsx(If,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!Ki(a)?e.jsx("div",{className:"mt-4",children:e.jsx(Pf,{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 Rf({templates:t,draft:s,onDraftChange:n}){return e.jsxs("div",{children:[e.jsxs("label",{className:"block",htmlFor:"tracking-template-source",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Saved template"}),e.jsxs("select",{id:"tracking-template-source","aria-describedby":bi(s)?"tracking-template-market-required":void 0,className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:s.templateId,onChange:a=>{const r=t.find(l=>l.id===a.target.value);n({...s,templateId:r?.id??"",templateVersion:r?.updatedAt??"",template:r?.pattern??""})},children:[e.jsx("option",{value:"",children:"Choose a template"}),t.map(a=>e.jsx("option",{value:a.id,children:a.name},a.id))]}),s.template?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-muted",children:s.template}):null]}),bi(s)?e.jsx("p",{id:"tracking-template-market-required",role:"status",className:"mt-2 text-sm leading-5 text-caution",children:"Choose a Market under Apply to for this template. A location alone does not select a market."}):null]})}function nl({id:t,label:s,value:n,options:a,onChange:r}){return e.jsxs("label",{className:"block",htmlFor:t,children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:s}),e.jsxs("select",{id:t,className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:n,onChange:l=>r(l.target.value),children:[e.jsx("option",{value:"",children:"Choose a saved query"}),a.map(l=>e.jsxs("option",{value:l.id,children:[l.label," · ",l.detail]},l.id))]})]})}function _i(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function da(t){return JSON.stringify({providers:[...t.providers].sort(),models:Object.fromEntries(Object.entries(t.models).sort(([s],[n])=>s.localeCompare(n))),location:t.location})}function Uc(t){return[...new Map(t.map(s=>[da(s),s])).values()]}function Ui(t){const s=t.providers.map(n=>{const a=t.models[n];return a?`${n} (${a})`:n}).join(", ");return`${t.location??"No location"} · ${s}`}function Pf({workspace:t,draft:s,onDraftChange:n}){const a=o.useMemo(()=>Uc([...t.defaultContexts.map(_i),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?da(s.contexts[0]):s.contexts.length>1?"__existing__":"";return e.jsxs("label",{className:"block",htmlFor:"tracking-query-context",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location and engines"}),e.jsxs("select",{id:"tracking-query-context","aria-label":"Location and engines",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:r,onChange:l=>{const i=a.find(d=>da(d)===l.target.value),c=l.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:c})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(l=>e.jsx("option",{value:da(l),children:Ui(l)},da(l)))]}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-secondary",children:a.length===0?"No configured measurement context is available.":"Choose where this query will be measured."})]})}function If({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(k=>k!==y)})}function x(h,y){return(h==="target"?s.targetKeys:h==="group"?s.groupKeys:s.marketKeys).includes(y)}if(!l){const h=t.targets.find(y=>y.stableKey===s.targetKeys[0]);return e.jsxs("fieldset",{className:"self-start rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-sm text-strong",children:["Property: ",h?.label??s.targetKeys[0]]}),e.jsx(P,{type:"button",variant:"ghost",size:"sm","aria-label":"Change tracking destination",onClick:()=>i(!0),children:"Change"})]})]})}return e.jsxs("fieldset",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Choose where this question should be tracked."}),e.jsxs("label",{className:"mt-3 flex min-h-9 items-center gap-2 rounded px-1 text-sm text-strong",children:[e.jsx("input",{type:"checkbox",checked:s.wholeSite,onChange:h=>{n({...s,wholeSite:h.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),"Whole site"]}),!s.wholeSite&&!u?e.jsx("p",{role:"status",className:"mt-2 text-sm text-caution",children:"Choose Whole site or at least one property, group, or market."}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:"Group: properties grouped together. Market: search context."}),e.jsx(Js,{value:a,onChange:r,label:"Filter assignments",placeholder:"Search Properties, Groups, Markets",className:"mt-3"}),e.jsx("div",{className:"mt-3 max-h-64 space-y-1 overflow-y-auto pr-1",children:m.length===0?e.jsx("p",{className:"px-1 py-2 text-sm text-muted",children:"No assignment matches that search."}):m.map(h=>e.jsxs("label",{className:"flex min-h-9 items-center gap-2 rounded px-1 py-1 text-sm text-strong hover:bg-surface-hover",children:[e.jsx("input",{type:"checkbox","aria-label":`${h.label}, ${h.detail}`,checked:x(h.kind,h.key),onChange:y=>p(h.kind,h.key,y.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:h.label}),e.jsx("span",{className:"text-xs text-muted",children:h.detail})]},`${h.kind}:${h.key}`))})]})}function Ur({canReview:t,isPreviewing:s,onCancel:n,onReview:a}){return e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[e.jsx(Ye,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),e.jsx("p",{className:"text-sm leading-5 text-secondary",children:"Publishing does not run a sweep."})]})}function Tf({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=o.useRef(null);o.useEffect(()=>{const c=r.current;c&&(typeof c.scrollIntoView=="function"&&c.scrollIntoView({block:"start"}),c.focus({preventScroll:!0}))},[t]);const l=!t.diff.noOp,i=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(c=>c.rows.length>0);return e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{ref:r,tabIndex:-1,children:l?"Confirm tracked query changes":"No tracking changes"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:l?"Changes apply to future sweeps. Earlier results stay unchanged.":"This request leaves tracking unchanged."})]}),e.jsx(Ne,{tone:l?"caution":"neutral",children:l?"Ready to confirm":"No-op"})]}),i.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:i.map(c=>e.jsx(al,{label:c.label,rows:c.rows,workspace:s,tracked:t.tracked},c.label))}):null,t.diff.unchanged.length>0?e.jsxs("details",{className:"mt-4 border-t border-default pt-2 text-sm text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3",children:[t.diff.unchanged.length," unchanged ",t.diff.unchanged.length===1?"query":"queries"]}),e.jsx(al,{label:"Unchanged",rows:t.diff.unchanged,workspace:s,tracked:t.tracked})]}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Next sweep workload"}),e.jsxs("p",{className:"leading-6",children:["Next sweep: ",t.workload.nextSweepProviderCalls," provider requests (+",t.workload.addedProviderCalls,", −",t.workload.removedProviderCalls,")."]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:e.jsx(Ye,{type:"button",size:"sm",disabled:!l||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function al({label:t,rows:s,workspace:n,tracked:a}){return e.jsxs("section",{"aria-label":`${t} queries`,children:[e.jsxs("p",{className:"text-xs font-medium text-secondary",children:[s.length," ",t.toLocaleLowerCase(),s.length===1?"":"s"]}),e.jsx("ul",{className:"mt-2 divide-y divide-default",children:s.map(r=>e.jsxs("li",{className:"py-2 text-sm",children:[e.jsx("p",{className:"font-medium text-strong",children:r.queryText}),e.jsx("p",{className:"mt-1 text-secondary",children:t==="Removed"?`${r.assignmentCount} ${r.assignmentCount===1?"assignment":"assignments"} removed`:Lf(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(Mf,{row:a.find(l=>l.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function Mf({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 Lf(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=Uc(a.assignments.flatMap(i=>i.contexts).map(_i)),l=r.length===1?Ui(r[0]):r.length>1?`${r.length} contexts`:null;return[_c(a,n),l].filter(i=>i!==null).join(" · ")}function $f({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:l,onPendingTrackingSourceHandled:i}){const c=hs(),[d,m]=o.useState(null),u=qe({...Ii({client:W,path:{name:t}})}),p=qe({...Yl({client:W,path:{name:t}}),staleTime:6e4}),x=Et({...vu(),onSuccess:y=>m(y),onError:async y=>{m(null),await c.invalidateQueries({queryKey:bu({client:W,path:{name:t}})}),De({title:"Could not review tracking changes",detail:y instanceof Error?y.message:"Update the draft and review it again.",tone:"negative"})}}),h=Et({...ju(),onSuccess:async y=>{m(null),r?.(void 0),await io(c,t),De({title:y.committed?"Tracked queries updated":"No tracked-query change",detail:y.active?`Measurement revision ${y.active.revision}.`:"No measurement revision is published yet.",tone:y.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async y=>{m(null),await io(c,t),De({title:"Could not confirm tracking changes",detail:y instanceof Error?y.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return u.isLoading?e.jsx(je,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):u.isError||!u.data?e.jsxs(je,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{u.refetch()},children:"Try again"})]}):e.jsx(gf,{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:W,path:{name:t},body:{...y,expectedWorkspaceVersion:u.data.workspaceVersion}})},onCommit:y=>h.mutate({client:W,path:{name:t},body:y})})}function qf({projectName:t,onReviewDiscoveryProbe:s}){const n=hs(),[a,r]=o.useState(null),[l,i]=o.useState(""),[c,d]=o.useState("100"),m=qe({...Nu({client:W,path:{name:t},query:{limit:"10"}}),refetchInterval:k=>k.state.data?.some(S=>yi.has(S.status))?3e3:!1}),u=m.data??[];o.useEffect(()=>{!a&&u[0]&&r(u[0].id)},[a,u]);const p=u.find(k=>k.id===a)??null,x=qe({...wu({client:W,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:p&&yi.has(p.status)?3e3:!1}),h=x.data??null,y=Et({mutationFn:()=>{const k={},$=l.trim();$&&(k.icpDescription=$);const S=Number.parseInt(c,10);return Number.isFinite(S)&&S>0&&(k.maxProbes=S),Su(t,k)},onSuccess:async k=>{r(k.sessionId),i(""),await Ff(n,t,k.sessionId),De({title:"Discovery started",detail:`Run ${Br(k.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${k.sessionId}`,dedupeMode:"replace"})},onError:k=>{De({title:"Discovery failed to start",detail:k instanceof Error?k.message:"Could not start discovery.",tone:"negative"})}}),f=h??p,b=o.useMemo(()=>(h?.probes??[]).slice(0,30),[h?.probes]);async function j(){try{const k=await m.refetch();if(k.error)throw k.error;const $=k.data?.length??0;De({title:"Discovery sessions refreshed",detail:`${$} recent session${$===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(k){De({title:"Discovery refresh failed",detail:k instanceof Error?k.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children: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(P,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{j()},children:[e.jsx(ba,{className:`size-3.5 ${m.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(Ne,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:l,onChange:k=>i(k.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:c,onChange:k=>d(k.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!ie()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:y.isPending,onClick:()=>y.mutate(),children:[e.jsx(lr,{size:14}),y.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),m.isFetching&&e.jsx(Ne,{tone:"neutral",children:"Loading"})]}),u.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:u.map(k=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===k.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(k.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:Br(k.id)}),e.jsx(Ne,{tone:rl(k.status),children:k.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",k.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",k.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",k.wastedCount??0]})]})]},k.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:f?Br(f.id):"No run selected"})]}),f&&e.jsx(Ne,{tone:rl(f.status),children:f.status})]}),f?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Va,{label:"Questions tested",value:f.probeCount??0}),e.jsx(Va,{label:"Cited queries",value:f.citedCount??0,tone:"positive"}),e.jsx(Va,{label:"Worth tracking",value:f.aspirationalCount??0,tone:"caution"}),e.jsx(Va,{label:"Skip",value:f.wastedCount??0,tone:"negative"})]}),f.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:f.error}),f.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:f.warning}),f.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:f.icpDescription})]}),f.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:f.competitorMap.slice(0,8).map(k=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[k.domain," ",e.jsx("span",{className:"text-muted",children:k.hits})]},k.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),f?.status==="completed"&&e.jsxs(je,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Review a discovery question for tracking"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:"Choose a Cited query or Worth tracking result below. Tracking opens with the saved discovery source, where you choose its scope and review the exact next-sweep change."})]})}),e.jsx("p",{className:"mt-3 text-xs leading-5 text-muted",children:"Discovery remains research. This review does not add competitors or start a sweep."})]}),e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),x.isFetching&&e.jsx(Ne,{tone:"neutral",children:"Loading"})]}),b.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Tracking review"})})]})}),e.jsx("tbody",{children:b.map(k=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:k.query}),e.jsx("td",{children:e.jsx(Ne,{tone:Ef(k.bucket),children:Of(k.bucket)})}),e.jsx("td",{className:"text-secondary",children:k.citedDomains.length>0?k.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!ie()&&s&&(k.bucket==="cited"||k.bucket==="aspirational")&&e.jsx(Ye,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(k.id),children:"Review for tracking"})})]},k.id))})]})})]})]})]})]})}function Va({label:t,value:s,tone:n="neutral"}){const a=n==="positive"?"text-positive":n==="caution"?"text-caution":n==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s})]})}function rl(t){return t==="completed"?"positive":t==="failed"?"negative":yi.has(t)?"caution":"neutral"}function Ef(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Df={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Of(t){return t?Df[t]:"Not classified"}function Br(t){return t.length>8?t.slice(0,8):t}async function Ff(t,s,n){await Promise.all([$t(t,"discovery"),t.invalidateQueries({queryKey:Cu({client:W})})])}function Kf({projectName:t}){const[s,n]=o.useState("changes"),[a,r]=o.useState(null),[l,i]=o.useState(null),c=qe({...ku({client:W,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=qe({...Au({client:W,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({...Ru({client:W,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(cp,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),c.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!c.isLoading&&y.length===0?e.jsxs(je,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:ds()?Qn:"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(je,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:ds()?Qn:"Run another answer visibility sweep before comparing historical evidence."})]}):null,h.data&&f.length===0?e.jsxs(je,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,f.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:f.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:b.query??"Archived query"}),e.jsx("td",{children:e.jsxs(Ne,{tone:b.changed?"caution":"neutral",children:[b.run1State??"none"," → ",b.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(Ne,{tone:b.visibilityChanged?"caution":"neutral",children:[b.run1MentionState??"none"," → ",b.run2MentionState??"none"]})})]},b.queryId??b.query??"unknown"))})]})}):null]}):null]})}const il={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},Gf={contract:null,assessment:null,googleAds:il,gtm:il,snapshots:[]};function _f(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Qf(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Uf(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 Bf(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 Vf(t){switch(t.gtm.state){case"not-connected":return{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."};case"selection-required":return{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."};case"stale":return{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."};default:return null}}function Bc(t){return t.googleAds.state==="not-connected"?{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."}:t.googleAds.state==="unavailable"||t.gtm.state==="unavailable"?{id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."}:t.googleAds.state==="selection-required"?{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."}:t.googleAds.state==="stale"?{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."}:t.gtm.state==="not-connected"?{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."}:t.gtm.state==="selection-required"?{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."}:t.gtm.state==="stale"?{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."}:t.contractSelectionRequired?{id:"select-contract",label:"Select conversion",detail:"Choose the declared conversion Canonry should assess."}:t.contract?t.assessmentState==="loading"?{id:"waiting-for-integrity",label:"Checking configuration…",detail:"Canonry is loading the selected conversion assessment."}:t.assessmentState==="unavailable"?{id:"retry-integrity",label:"Retry assessment",detail:"Retry the selected conversion assessment before acting on its evidence."}:t.assessment?.status==="runtime-unverified"?{id:"review-runtime-verification",label:"Review runtime verification",detail:"Static configuration is aligned. Verify a real browser event separately."}:t.assessment?.status==="configured"&&zf(t)?{id:"review-findings",label:"Review findings",detail:"Resolve the mismatched or unknown checks before treating this conversion as ready."}:{id:"sync-static-evidence",label:"Refresh static evidence",detail:"Queue fresh read-only Google Ads and Tag Manager observations."}:{id:"declare-contract",label:"Declare conversion",detail:"Name the website event, Google Ads action, and Tag Manager tag that must agree."}}function Qf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function zf(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Vc(t){switch(t){case"connected":return{label:"Connected",tone:"positive"};case"stale":return{label:"Needs refresh",tone:"caution"};case"selection-required":return{label:"Selection needed",tone:"caution"};case"not-connected":return{label:"Not connected",tone:"neutral"};case"unavailable":return{label:"Unavailable",tone:"negative"}}}function Hf(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 Wf(t,s){return t==="configured"?s==="not-configured"?"Not declared":s==="contract-selection-required"?"Choose conversion":"Declared":t==="static"?s==="assessment-unavailable"?"Unavailable":s==="assessment-loading"?"Checking":s==="static-mismatch"?"Mismatch":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"Consistent":s==="configured"?"Needs review":"Not checked":s==="observed"?"Observed":s==="runtime-unverified"?"Not observed":"Not checked"}function xn(t){return t.length<=12?t:`…${t.slice(-10)}`}function Yf(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 Jf(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"No additional event fields required"}const Vr={"ads-connection-missing":"Google Ads connection is available","ads-conversion-action-missing":"Google Ads conversion action exists and is enabled","ads-goal-missing":"Google Ads goal includes the conversion action","ads-goal-not-biddable":"Google Ads goal is available for bidding","ads-action-not-primary":"Google Ads action is primary","gtm-connection-missing":"Tag Manager connection is available","gtm-live-graph-missing":"Tag Manager configuration is available","gtm-tag-missing":"Required Tag Manager tag exists","gtm-tag-unrecognized":"Tag Manager tag type is supported","gtm-tag-paused":"Tag Manager tag is active","gtm-trigger-missing":"Required Tag Manager trigger is linked","gtm-variable-missing":"Required Tag Manager variable is linked","gtm-event-mismatch":"Tag Manager event matches the declaration","gtm-hostname-mismatch":"Tag Manager host matches the production site","gtm-value-mapping-missing":"Conversion value mapping is present","gtm-transaction-id-mapping-missing":"Transaction ID mapping is present","gtm-currency-mapping-missing":"Currency mapping is present","gtm-conversion-id-mismatch":"Google conversion ID matches","gtm-conversion-label-mismatch":"Google conversion label matches","runtime-event-not-observed":"Website event was observed","runtime-gtm-not-observed":"Tag Manager firing was observed","runtime-ads-not-observed":"Google Ads conversion was observed"};function ol(t){return t.outcome==="pass"?{label:Vr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Vr[t.code],tone:"negative",outcome:"Fail"}:{label:Vr[t.code],tone:"caution",outcome:"Unknown"}}function Xf(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Zf(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 ey(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function ll({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const l=Vc(s.state),i=s.snapshotState==="loading"?"Loading stored snapshots":s.snapshotState==="unavailable"?"Stored snapshots unavailable":s.snapshotCount===0?"No stored snapshots":null;return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:t}),e.jsx("td",{children:e.jsx(Ne,{tone:l.tone,children:l.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),i?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:i}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Jt(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const ty="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.",sy="Available once Google Ads and Tag Manager are connected.",ny="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 ay({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:Bf(t)},{title:"Tag Manager",state:t.gtm.state,ready:c,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:m?p:Vf(t)}],y=i&&c&&!u?Bc(t):null;return e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("h2",{id:"conversion-integrity-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx(Oe,{text:"Canonry reads your Google configuration and never changes or publishes it. Connect Google Ads and Tag Manager, then choose one website conversion to check across both."})]}),x?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:ny}):null]})}),e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-y border-default py-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Conversion to check"}),e.jsx(Oe,{text:ty})]}),y&&s?e.jsx(Ye,{type:"button",disabled:r,onClick:()=>s(y.id),children:r?"Working…":y.label}):e.jsx("p",{className:"text-sm text-secondary",children:sy})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:h.map(f=>{const b=f.ready?{label:"Ready",tone:"positive"}:Vc(f.state),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(Ne,{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(P,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(j.id),children:r?"Working…":j.label}):e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(j.id),children:r?"Working…":j.label}):null,f.summary&&f.onChange?e.jsx(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":f.changeLabel,disabled:r,onClick:f.onChange,children:"Change"}):null]},f.title)})}),l?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:l}):null]})]})}function ry({workspace:t=Gf,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:l=null,onSelectContract:i,contractError:c=null,onRetryContracts:d,onRetryEvidence:m,onChangeGoogleAdsSelection:u,onChangeGtmSelection:p,onAddContract:x}){const h=_f(t),y=Uf(h),f=Bc(t),b=t.assessment?.findings??[],j=b.filter(g=>g.outcome!=="pass"),k=b.filter(g=>g.outcome==="pass"),$=j.some(g=>g.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&c===null?e.jsx(ay,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:u,onChangeGtmSelection:p,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ne,{tone:y.tone,children:y.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Jt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:y.detail}),t.assessmentEvidenceSnapshots?.length?e.jsxs("details",{className:"inline-disclosure mt-3 max-w-2xl",children:[e.jsx("summary",{children:"Evidence used for this assessment"}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm leading-6 text-secondary",children:t.assessmentEvidenceSnapshots.map(g=>e.jsxs("li",{className:"break-words",children:[ey(g)," ",g.kind,", captured ",Jt(g.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",g.id,")"]})]},g.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?f.id==="review-findings"||f.id==="review-runtime-verification"||f.id==="retry-connection-status"||f.id==="select-contract"||f.id==="retry-integrity"||f.id==="waiting-for-integrity"?e.jsx(P,{type:"button",disabled:n||f.id==="waiting-for-integrity",onClick:()=>s(f.id),children:n?"Working…":f.label}):e.jsx(Ye,{type:"button",disabled:n,onClick:()=>s(f.id),children:n?"Working…":f.label}):f.id==="review-findings"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):h==="runtime-unverified"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:f.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),r.length>0&&x?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:x,children:"Add conversion"}):null]}),r.length>1?e.jsxs("label",{htmlFor:"conversion-integrity-contract-select",className:"mb-5 block max-w-xl text-sm font-medium text-secondary",children:["Conversion to inspect",e.jsxs("select",{id:"conversion-integrity-contract-select",className:"mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",value:l??"",onChange:g=>i?.(g.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]})]}):null,t.contract?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Website event"}),e.jsx("dd",{className:"mt-1 text-sm font-medium text-heading",children:t.contract.eventName})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Google Ads goal"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:Yf(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:Jf(t.contract)})]})]}),e.jsxs("details",{className:"inline-disclosure mt-5",children:[e.jsx("summary",{children:"Show declared identifiers"}),e.jsxs("dl",{className:"mt-3 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads customer"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:xn(t.contract.googleAds.customerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads conversion action"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:xn(t.contract.googleAds.conversionActionId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager container"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:xn(t.contract.gtm.containerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager tag"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:xn(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),c?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:c}),d?e.jsx(P,{type:"button",variant:"outline",onClick:d,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),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(Ne,{tone:$,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=ol(g);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:v.label}),e.jsx(Ne,{tone:v.tone,children:v.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",g.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",g.code]}),g.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",g.evidenceIds.join(", ")]}):null]},`${g.code}:${g.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(Oe,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(g=>{const v=Hf(g.key,h);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${v==="positive"?"bg-positive-fill":v==="caution"?"bg-caution-fill":v==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:g.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:g.detail}),e.jsx(Ne,{tone:v,children:Wf(g.key,h)})]},g.key)})})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-connections-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection evidence"}),e.jsx("h3",{id:"conversion-integrity-connections-title",className:"text-base font-semibold text-heading",children:"Google Ads and Tag Manager"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads and Tag Manager connection and stored evidence state"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Connection"}),e.jsx("th",{scope:"col",children:"Selection"}),e.jsx("th",{scope:"col",children:"Stored evidence"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsxs("tbody",{children:[ll({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:u}:{},actionPending:n}),ll({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:p}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&m?e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:m,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:g.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:g.kind}),e.jsx("td",{className:"text-secondary",children:Jt(g.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:xn(g.id)})]},g.id))})]})})]}):null,k.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[k.length," ",k.length===1?"passing check":"passing checks"," from the latest assessment"]}),e.jsx("div",{className:"findings-table-wrap mt-3",children:e.jsxs("table",{className:"findings-table",children:[e.jsx("caption",{className:"sr-only",children:"Conversion integrity findings"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Check"}),e.jsx("th",{scope:"col",children:"Result"}),e.jsx("th",{scope:"col",children:"Subject"})]})}),e.jsx("tbody",{children:k.map(g=>{const v=ol(g);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:v.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",g.code]}),g.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",g.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(Ne,{tone:v.tone,children:v.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:g.subject})]},`${g.code}:${g.subject}`)})})]})})]}):null,h==="runtime-unverified"?e.jsxs("section",{id:"conversion-integrity-runtime-guidance",className:"page-section-divider","aria-labelledby":"conversion-integrity-runtime-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Runtime verification"}),e.jsx("h3",{id:"conversion-integrity-runtime-title",className:"text-base font-semibold text-heading",children:"Runtime verification checklist"})]})}),e.jsxs("ol",{className:"max-w-2xl list-decimal space-y-2 pl-5 text-sm leading-6 text-secondary marker:text-muted",children:[e.jsxs("li",{children:["Use a controlled browser session on ",Xf(t.contract)," and complete the conversion that emits ",e.jsx("span",{className:"font-mono text-heading",children:t.contract.eventName}),"."]}),e.jsxs("li",{children:["In Tag Manager preview or debugging, confirm tag ",e.jsx("span",{className:"font-mono text-heading",children:xn(t.contract.gtm.tagId)})," fires with ",Zf(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:xn(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const gn=3e4,cl={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Gt="mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",ls="text-sm font-medium text-secondary";function dl(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:St(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function Qa(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function iy(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 oy(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function ly(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:oy(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 cy(t,s,n){return{name:t.name.trim(),eventName:t.eventName.trim(),googleAds:{customerId:s,conversionActionId:t.conversionActionId.trim(),...t.conversionId.trim()?{conversionId:t.conversionId.trim()}:{},...t.conversionLabel.trim()?{conversionLabel:t.conversionLabel.trim()}:{},campaignIds:Qa(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:Qa(t.triggerIds),variableIds:Qa(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:Qa(t.productionHosts)}}}function ul(t,s){const n=window.open(t,"_blank","width=600,height=700");if(!n){window.location.assign(t);return}const a=window.setInterval(()=>{n.closed&&(window.clearInterval(a),s())},1e3)}function za(t,s,n){if(!s)return null;const a=s.totalAccessible===1?t:`${t}s`;return s.truncated?`Incomplete result: showing ${n} of ${s.totalAccessible} accessible ${a}. Use the CLI or API if the resource is not shown.`:`${s.totalAccessible} accessible ${a} found.`}function Ha(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Wa({id:t,label:s,value:n,onChange:a,children:r,disabled:l=!1}){return e.jsxs("label",{htmlFor:t,className:ls,children:[s,e.jsx("select",{id:t,className:Gt,value:n,onChange:i=>a(i.target.value),disabled:l,children:r})]})}function qn({id:t,checked:s,onChange:n,children:a}){return e.jsxs("label",{htmlFor:t,className:"flex items-start gap-2 text-sm text-secondary",children:[e.jsx("input",{id:t,type:"checkbox",checked:s,onChange:r=>n(r.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function ml({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1),[c,d]=o.useState(null),m=o.useRef(null),u=o.useRef(null),p=o.useRef(!1);o.useEffect(()=>{const f=p.current;p.current=a,a?u.current?.focus():f&&m.current?.querySelector("button")?.focus()},[a]);function x(){d(null),r(!0)}function h(){d(null),r(!1)}async function y(){i(!0),d(null);try{await n()}catch(f){d(St(f)),i(!1)}}return e.jsx("div",{ref:m,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(P,{ref:u,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:l,onClick:h,children:"Keep connected"}),e.jsx(Ye,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||l,onClick:()=>{y()},children:l?"Disconnecting…":`Disconnect ${t}`})]}),c?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:c}):null]}):e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:x,children:["Disconnect ",t]})})}function hl({id:t,label:s,options:n,synced:a,loading:r,failed:l,onRetry:i,emptyHint:c,value:d,onChange:m}){const u=n.some(f=>f.id===d),[p,x]=o.useState(!1),h=p||d!==""&&!u&&n.length>0,y=e.jsx("label",{htmlFor:t,className:ls,children:s});return r?e.jsxs("div",{children:[y,e.jsx("select",{id:t,className:Gt,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):l?e.jsxs("div",{children:[y,e.jsx("input",{id:t,required:!0,className:Gt,value:d,onChange: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:Gt,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:Gt,value:d,onChange:f=>m(f.target.value)}):e.jsxs("select",{id:t,required:!0,className:Gt,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 dy({projectId:t,projectName:s}){const n=nn(),[a,r]=o.useState(null),[l,i]=o.useState(null),[c,d]=o.useState(!1),[m,u]=o.useState(""),[p,x]=o.useState(null),[h,y]=o.useState(!1),[f,b]=o.useState(!1),[j,k]=o.useState(""),[$,S]=o.useState(""),[g,v]=o.useState(""),[C,T]=o.useState(""),[I,w]=o.useState(""),[V,F]=o.useState(!1),[z,B]=o.useState(cl),[Q,se]=o.useState(null),K=o.useRef(null),U=qe({...Pu({client:W,path:{name:s}}),staleTime:gn}),J=qe({...Iu({client:W,path:{name:s}}),staleTime:gn}),q=qe({...Tu({client:W,path:{name:s}}),staleTime:gn}),X=qe({...Mu({client:W,path:{name:s}}),staleTime:gn}),L=X.data,D=qe({...Lu({client:W,path:{name:s},query:{limit:5}}),staleTime:gn}),ee=qe({...$u({client:W,path:{name:s},query:{limit:5}}),staleTime:gn}),ne=q.data??[],we=(Q?ne.find(E=>E.id===Q)??null:null)??(ne.length===1?ne[0]??null:null),Y=ne.length>1&&!we,ue=qe({...qu({client:W,path:{name:s,contractId:we?.id??""}}),enabled:!!we,staleTime:gn}),he=qe({...Eu({client:W,path:{name:s}}),enabled:p==="google-ads"&&U.data?.connected===!0,staleTime:0}),Z=qe({...Du({client:W,path:{name:s}}),enabled:p==="gtm"&&J.data?.connected===!0,staleTime:0}),me=qe({...Ou({client:W,path:{name:s,accountId:g}}),enabled:p==="gtm"&&!!g,staleTime:0}),G=qe({...Fu({client:W,path:{name:s,accountId:g,containerId:C}}),enabled:p==="gtm"&&!!g&&!!C,staleTime:0}),pe=Et(Ku({client:W})),Ee=Et(Gu({client:W})),Re=Et(_u({client:W})),re=Et(Uu({client:W})),xe=Et(Bu({client:W})),Ae=Et(Vu({client:W})),et=Et(Qu({client:W})),Le=Et(zu({client:W})),O=Et(Hu({client:W}));o.useEffect(()=>{if(p!=="google-ads"||h||!U.isSuccess)return;const E=U.data.connection?.selection;k(E?.customerId??""),S(E?.loginCustomerId??""),y(!0)},[h,U.data,U.isSuccess,p]),o.useEffect(()=>{if(p!=="gtm"||f||!J.isSuccess)return;const E=J.data.selection;v(E?.accountId??""),T(E?.containerId??""),w(E?.workspaceId??""),b(!0)},[f,J.data,J.isSuccess,p]),o.useEffect(()=>{!Q||!q.data||q.data.some(E=>E.id===Q)||se(null)},[q.data,Q]);const ke=o.useMemo(()=>{const E=D.data?.snapshots??[],Se=ee.data?.snapshots??[],st=[...E.map(wt=>({id:wt.id,provider:"google-ads",kind:wt.kind,capturedAt:wt.capturedAt})),...Se.map(wt=>({id:wt.id,provider:"gtm",kind:wt.kind,capturedAt:wt.capturedAt}))].sort((wt,qs)=>qs.capturedAt.localeCompare(wt.capturedAt)).slice(0,5),qt=[],Ft=ue.data?.googleAdsSnapshot,Be=ue.data?.gtmSnapshot;return Ft&&qt.push({id:Ft.id,provider:"google-ads",kind:Ft.kind,capturedAt:Ft.capturedAt}),Be&&qt.push({id:Be.id,provider:"gtm",kind:Be.kind,capturedAt:Be.capturedAt}),{contract:ue.data?.assessment.contract??we,assessment:ue.data?.assessment??null,contractSelectionRequired:Y,assessmentState:we?ue.isError?"unavailable":ue.isLoading?"loading":void 0:void 0,assessmentError:ue.isError?St(ue.error):null,googleAds:iy(U.data,dl(D.data?.total??0,D.isLoading,D.isError,D.error),U.isError),gtm:ly(J.data,dl(ee.data?.total??0,ee.isLoading,ee.isError,ee.error),J.isError),snapshots:st,assessmentEvidenceSnapshots:qt}},[we,Y,D.data,D.error,D.isError,D.isLoading,U.data,U.isError,ee.data,ee.error,ee.isError,ee.isLoading,J.data,J.isError,ue.data,ue.error,ue.isError,ue.isLoading]),A=o.useSyncExternalStore(_l,ir,ir),be=Object.values(A.runs).some(E=>E.projectId===t&&(E.kind===Us["google-ads-sync"]||E.kind===Us["gtm-sync"])),Ke=pe.isPending||Ee.isPending||Re.isPending||re.isPending||xe.isPending||Ae.isPending||et.isPending||Le.isPending||O.isPending||be;async function Ve(){await Promise.all([U.refetch(),J.refetch(),q.refetch(),D.refetch(),ee.refetch(),X.refetch(),we?ue.refetch():Promise.resolve()])}async function Ge(E){await Ve();for(let Se=0;Se<10&&!E();Se+=1)await new Promise(st=>setTimeout(st,1500)),await Ve()}function ge(){const E=document.activeElement;K.current=E instanceof HTMLElement?E:null}function vt(E){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(E);return}globalThis.setTimeout(E,0)}function Qe(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Je(E){if(!E)return;!E.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!E.hasAttribute("tabindex")&&(E.tabIndex=-1),E.focus({preventScroll:!0})}function Dt(E,Se=E){const st=document.getElementById(E);st instanceof HTMLDetailsElement&&(st.open=!0);const qt=st?.scrollIntoView;typeof qt=="function"&&qt.call(st,{behavior:Qe()?"auto":"smooth",block:"start"}),Je(document.getElementById(Se)??st)}function ct(E,Se){ge(),vt(()=>Dt(E,Se))}function at(){const E=K.current;K.current=null,E&&vt(()=>{E.isConnected&&E.focus({preventScroll:!0})})}function pt(){r(null),d(!1),at()}function Ct(){r(null),x(null),at()}function It(){r(null),F(!1),at()}function He(){r(null),x(null),d(!0),ct("google-ads-connect-panel","google-ads-connect-title")}function R(){r(null),k(""),S(""),y(!1),x("google-ads"),d(!1),ct("google-ads-selection-panel","google-ads-selection-title")}function $e(){r(null),v(""),T(""),w(""),b(!1),x("gtm"),d(!1),ct("gtm-selection-panel","gtm-selection-title")}function Ie(){r(null),F(!0),ct("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Fe(E,Se){Gl({id:E.id,projectId:E.projectId,kind:E.kind,projectLabel:s,sourceAction:Se}),De({title:Se==="google-ads-sync"?"Google Ads sync queued":"Tag Manager sync queued",detail:`${s} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`google-marketing-sync:${E.id}`,dedupeMode:"replace"})}async function dt(){Cs(n),r(null);try{const E=await pe.mutateAsync({path:{name:s},body:{provider:"google-ads",...m.trim()?{developerToken:m.trim()}:{}}});u(""),d(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),ul(E.authorizationUrl,()=>{Ve(),i(null),at()})}catch(E){r(St(E))}}async function ze(){Cs(n),r(null);try{const E=await Ee.mutateAsync({path:{name:s},body:{provider:"gtm"}});i("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),ul(E.authorizationUrl,()=>{Ve(),i(null),at()})}catch(E){r(St(E))}}async function yt(){if(Cs(n),!j){r("Select a Google Ads customer before saving.");return}r(null);try{await Re.mutateAsync({path:{name:s},body:{customerId:j,...$.trim()?{loginCustomerId:$.trim()}:{}}}),x(null),at(),await Ge(()=>U.data?.selectedCustomer!=null)}catch(E){r(St(E))}}async function te(){if(Cs(n),!g||!C){r("Select a Tag Manager account and container before saving.");return}r(null);try{await re.mutateAsync({path:{name:s},body:{accountId:g,containerId:C,...I?{workspaceId:I}:{}}}),x(null),at(),await Ge(()=>J.data?.status==="connected")}catch(E){r(St(E))}}async function _e(){Cs(n),r(null),await et.mutateAsync({path:{name:s}}),x(null),d(!1),k(""),S(""),y(!1),i(null),await Ve(),De({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),K.current=null,vt(()=>Je(document.getElementById("conversion-integrity-title")))}async function Pe(){Cs(n),r(null),await Le.mutateAsync({path:{name:s}}),x(null),v(""),T(""),w(""),b(!1),i(null),await Ve(),De({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),K.current=null,vt(()=>Je(document.getElementById("conversion-integrity-title")))}async function ve(){Cs(n),r(null);try{const E=await xe.mutateAsync({path:{name:s}});Fe(E,"google-ads-sync")}catch(E){r(St(E))}}async function Tt(){Cs(n),r(null);try{const E=await Ae.mutateAsync({path:{name:s}});Fe(E,"gtm-sync")}catch(E){r(St(E))}}async function Xt(){Cs(n),r(null);try{const E=await Promise.allSettled([xe.mutateAsync({path:{name:s}}),Ae.mutateAsync({path:{name:s}})]),[Se,st]=E;Se.status==="fulfilled"&&Fe(Se.value,"google-ads-sync"),st.status==="fulfilled"&&Fe(st.value,"gtm-sync");const qt=E.find(Ft=>Ft.status==="rejected");if(qt?.status==="rejected")throw qt.reason}catch(E){r(St(E))}}async function Zt(){Cs(n);const E=U.data?.connection?.selection.customerId,Se=J.data?.selection;if(!E||!Se?.accountId||!Se.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const st=await O.mutateAsync({path:{name:s},body:cy(z,E,{accountId:Se.accountId,containerId:Se.containerId})});B(cl),F(!1),at(),(await q.refetch()).data?.some(Ft=>Ft.id===st.id)&&se(st.id)}catch(st){r(St(st))}}function Ot(E){switch(E){case"connect-google-ads":He();return;case"connect-gtm":ge(),ze();return;case"select-google-ads":R();return;case"select-gtm":$e();return;case"sync-google-ads":ve();return;case"sync-gtm":Tt();return;case"sync-static-evidence":Xt();return;case"declare-contract":Ie();return;case"review-findings":ct("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":ct("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Ve();return;case"select-contract":ct("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ue.refetch();return;case"waiting-for-integrity":return}}const ut=he.data?.customers??[],es=Z.data?.accounts??[],it=me.data?.containers??[],gs=G.data?.workspaces??[],ps=!!j&&!ut.some(E=>E.customerId===j),Bs=!!g&&!es.some(E=>E.id===g),bt=!!C&&!it.some(E=>E.id===C),Vs=!!I&&!gs.some(E=>E.id===I),Mt=ps&&he.isSuccess&&he.data.truncated===!1,as=Bs&&Z.isSuccess&&Z.data.truncated===!1,Vt=bt&&me.isSuccess&&me.data.truncated===!1,xt=Vs&&G.isSuccess&&G.data.truncated===!1,ts=as||Vt||xt,Qt=as?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Vt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":xt?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,fs=Ha(Mt,he.data,he.isError),zt=Ha(as,Z.data,Z.isError),gt=Ha(Vt,me.data,me.isError),Lt=Ha(xt,G.data,G.isError),Nt=he.isError?St(he.error):null,ys=Z.isError?St(Z.error):me.isError?St(me.error):G.isError?St(G.error):null,bs=p==="google-ads"?Nt:p==="gtm"?ys:null,_=za("customer",he.data,ut.length),ae=za("account",Z.data,es.length),de=za("container",me.data,it.length),le=za("draft workspace",G.data,gs.length),Te=Z.isError||me.isError||G.isError&&!!I,Ue=c||p!==null||V;function mt(){he.refetch()}function kt(){if(Z.isError){Z.refetch();return}if(me.isError){me.refetch();return}G.isError&&G.refetch()}return U.isLoading||J.isLoading||q.isLoading?e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("div",{"aria-hidden":"true",className:"mt-5 grid gap-4 sm:grid-cols-2",children:[0,1].map(E=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"skeleton-text-sm w-full"}),e.jsx("div",{className:"skeleton-text-sm w-3/4"})]},E))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):q.isError&&!q.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",St(q.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{q.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ry,{workspace:ke,onPrimaryAction:Ot,actionPending:Ke,actionError:Ue?null:a,contracts:ne,selectedContractId:we?.id??null,onSelectContract:E=>se(E||null),contractError:q.isError?St(q.error):null,onRetryContracts:()=>{q.refetch()},onRetryEvidence:()=>{Promise.all([D.refetch(),ee.refetch()])},onChangeGoogleAdsSelection:R,onChangeGtmSelection:$e,onAddContract:()=>Ot("declare-contract")}),l?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:l}):null,c?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:Ze(async E=>{E.preventDefault(),await dt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:ls,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:m,onChange:E=>u(E.target.value),className:Gt,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:pe.isPending,children:pe.isPending?"Starting…":"Continue to Google"}),e.jsx(P,{type:"button",variant:"outline",onClick:pt,children:"Cancel"})]})]})]}):null,p==="google-ads"?e.jsxs("section",{id:"google-ads-selection-panel",className:"page-section-divider","aria-labelledby":"google-ads-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select customer context"})]})}),bs?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:bs}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:mt,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Mt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:"The saved customer is no longer accessible. Choose another customer before saving."}):null,e.jsxs("div",{className:"grid max-w-2xl gap-4 sm:grid-cols-2",children:[e.jsxs(Wa,{id:"google-ads-customer",label:"Customer account",value:j,onChange:E=>{y(!0),k(E);const Se=ut.find(st=>st.customerId===E);S(Se?.parentCustomerId??"")},disabled:he.isLoading,children:[e.jsx("option",{value:"",children:he.isLoading?"Loading accessible customers…":"Select a customer"}),ps?e.jsxs("option",{value:j,disabled:Mt,children:["Saved customer ",j," (",fs,")"]}):null,ut.map(E=>e.jsx("option",{value:E.customerId,children:E.descriptiveName??`Customer ${E.customerId}`},E.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:ls,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Gt,value:$,onChange:E=>{y(!0),S(E.target.value)},placeholder:"Use only when a manager context is required"})]})]}),_?e.jsx("p",{role:"status",className:`mt-3 text-sm ${he.data?.truncated?"text-caution":"text-secondary"}`,children:_}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:Re.isPending||he.isLoading||he.isError||Mt||!j,onClick:Ze(yt),children:Re.isPending?"Saving…":"Save customer selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:Ct,children:"Cancel"})]}),U.data?.connected?e.jsx(ml,{providerLabel:"Google Ads",disabled:Ke,onDisconnect:_e}):null]}):null,p==="gtm"?e.jsxs("section",{id:"gtm-selection-panel",className:"page-section-divider","aria-labelledby":"gtm-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Tag Manager"}),e.jsx("h3",{id:"gtm-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select container context"})]})}),bs?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:bs}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:kt,children:Z.isError?"Retry account list":me.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Qt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Qt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Wa,{id:"gtm-account",label:"Account",value:g,onChange:E=>{b(!0),E!==g&&(T(""),w("")),v(E)},disabled:Z.isLoading,children:[e.jsx("option",{value:"",children:Z.isLoading?"Loading accounts…":"Select an account"}),Bs?e.jsxs("option",{value:g,disabled:as,children:["Saved account ",g," (",zt,")"]}):null,es.map(E=>e.jsx("option",{value:E.id,children:E.name},E.id))]}),e.jsxs(Wa,{id:"gtm-container",label:"Container",value:C,onChange:E=>{b(!0),E!==C&&w(""),T(E)},disabled:!g||me.isLoading,children:[e.jsx("option",{value:"",children:me.isLoading?"Loading containers…":"Select a container"}),bt?e.jsxs("option",{value:C,disabled:Vt,children:["Saved container ",C," (",gt,")"]}):null,it.map(E=>e.jsx("option",{value:E.id,children:E.name},E.id))]}),e.jsxs(Wa,{id:"gtm-workspace",label:"Draft workspace (optional)",value:I,onChange:E=>{b(!0),w(E)},disabled:!C||G.isLoading,children:[e.jsx("option",{value:"",children:G.isLoading?"Loading workspaces…":"No draft workspace"}),Vs?e.jsxs("option",{value:I,disabled:xt,children:["Saved draft workspace ",I," (",Lt,")"]}):null,gs.map(E=>e.jsx("option",{value:E.id,children:E.name},E.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[ae?e.jsx("p",{role:"status",className:Z.data?.truncated?"text-caution":"text-secondary",children:ae}):null,de?e.jsx("p",{role:"status",className:me.data?.truncated?"text-caution":"text-secondary",children:de}):null,le?e.jsx("p",{role:"status",className:G.data?.truncated?"text-caution":"text-secondary",children:le}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:re.isPending||Z.isLoading||me.isLoading||G.isLoading&&!!I||Te||ts||!g||!C,onClick:Ze(te),children:re.isPending?"Saving…":"Save container selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:Ct,children:"Cancel"})]}),J.data?.connected?e.jsx(ml,{providerLabel:"Tag Manager",disabled:Ke,onDisconnect:Pe}):null]}):null,V?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:Ze(async E=>{E.preventDefault(),await Zt()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:ls,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Gt,value:z.name,onChange:E=>B(Se=>({...Se,name:E.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:ls,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Gt,value:z.eventName,onChange:E=>B(Se=>({...Se,eventName:E.target.value})),placeholder:"booking_complete"})]}),e.jsx(hl,{id:"contract-conversion-action",label:"Google Ads conversion action",options:L?.googleAds.conversionActions??[],synced:L?.googleAds.syncedAt!=null,loading:X.isLoading,failed:X.isError,onRetry:()=>{X.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:z.conversionActionId,onChange:E=>B(Se=>({...Se,conversionActionId:E}))}),e.jsx(hl,{id:"contract-gtm-tag",label:"Tag Manager tag",options:L?.gtm.tags??[],synced:L?.gtm.syncedAt!=null,loading:X.isLoading,failed:X.isError,onRetry:()=>{X.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:z.tagId,onChange:E=>B(Se=>({...Se,tagId:E}))})]}),e.jsxs("details",{className:"inline-disclosure mt-5 max-w-3xl",children:[e.jsx("summary",{children:"Additional matching rules"}),e.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-conversion-id",className:ls,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Gt,value:z.conversionId,onChange:E=>B(Se=>({...Se,conversionId:E.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:ls,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Gt,value:z.conversionLabel,onChange:E=>B(Se=>({...Se,conversionLabel:E.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:ls,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Gt,value:z.triggerIds,onChange:E=>B(Se=>({...Se,triggerIds:E.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:ls,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Gt,value:z.variableIds,onChange:E=>B(Se=>({...Se,variableIds:E.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:ls,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Gt,value:z.campaignIds,onChange:E=>B(Se=>({...Se,campaignIds:E.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:ls,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Gt,value:z.productionHosts,onChange:E=>B(Se=>({...Se,productionHosts:E.target.value})),placeholder:"example.com"})]})]}),e.jsxs("fieldset",{className:"mt-5 border-t border-subtle pt-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Required evidence"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsx(qn,{id:"contract-primary-action",checked:z.requirePrimaryAction,onChange:E=>B(Se=>({...Se,requirePrimaryAction:E})),children:"Google Ads action is primary"}),e.jsx(qn,{id:"contract-biddable-goal",checked:z.requireBiddableGoal,onChange:E=>B(Se=>({...Se,requireBiddableGoal:E})),children:"Google Ads goal is biddable"}),e.jsx(qn,{id:"contract-runtime-verification",checked:z.verificationRequired,onChange:E=>B(Se=>({...Se,verificationRequired:E})),children:"Runtime proof is required"}),e.jsx(qn,{id:"contract-transaction-id",checked:z.requireTransactionId,onChange:E=>B(Se=>({...Se,requireTransactionId:E})),children:"Transaction ID is required"}),e.jsx(qn,{id:"contract-value",checked:z.requireValue,onChange:E=>B(Se=>({...Se,requireValue:E})),children:"Conversion value is required"}),e.jsx(qn,{id:"contract-currency",checked:z.requireCurrency,onChange:E=>B(Se=>({...Se,requireCurrency:E})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:O.isPending,children:O.isPending?"Saving…":"Save conversion contract"}),e.jsx(P,{type:"button",variant:"outline",onClick:It,children:"Cancel"})]})]})]}):null]})}const uy=6e4,my=["7d","14d","30d"],Bi="not available",hy='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%.',py="No Google Ads snapshot stored yet",xy="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.",gy="No closed days yet",fy="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.",yy={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},zs=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),Qr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),by=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function En(t,s){return t===null||!Number.isFinite(t)?Bi:s===null?by.format(t/1e6):up(t,s)}function zr(t){return t===null||!Number.isFinite(t)?Bi:tt(t)}function vy(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 jy(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function Ny(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function wy(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 Sy({projectName:t}){const[s,n]=o.useState("14d"),[a,r]=o.useState(()=>new Set(["costMicros","conversions"])),l=qe({...Wu({client:W,path:{name:t},query:{window:s}}),staleTime:uy}),i=l.data,c=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Oe,{text:hy})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Pt(i.startDate)," to ",Pt(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(gr,{windows:my,value:s,onChange:n,label:"Google Ads time period"})]});if(l.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[c,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(g=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-20"}),e.jsx("div",{className:"skeleton-text-sm w-28"})]},g))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(l.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",St(l.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{l.refetch()},children:"Retry performance"})]});const{totals:d,daily:m,campaigns:u,comparison:p,comparisonUnavailableReason:x,source:h}=i;if(!h){const g=x==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:g?gy:py}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:g?fy:xy})]})]})}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:En(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":En(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}],k=[{key:"clicks",label:"Clicks",value:zs.format(d.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:zs.format(d.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:zr(d.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:En(d.cpcMicros,y),seriesKey:null}],$={costMicros:{label:"Spend",color:lt[1],axisId:"spend",formatValue:g=>En(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=>zs.format(g)},impressions:{label:"Impressions",color:lt[3],axisId:"impressions",formatValue:g=>zs.format(g)}},S=[...a].map(g=>({dataKey:g,...$[g]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,f!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",zs.format(f.queried)," of"," ",zs.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:yy["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),C=v&&a.size===1,T=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[g.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?$[g.seriesKey].color:"var(--color-mono-600)"}}):null,g.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:g.value}),p&&g.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${wy(g.change,g.direction)}`,children:vy(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:T},g.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:C,onClick:()=>r(I=>{const w=new Set(I);return w.has(g.seriesKey)?w.delete(g.seriesKey):w.add(g.seriesKey),w.size===0?I:w}),className:`rounded-md border px-3 py-2 text-left transition-colors ${v?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${C?"cursor-default":""}`,children:T},g.key)})}),e.jsx("dl",{className:"mt-2 flex flex-wrap gap-x-6 gap-y-1 rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:k.map(g=>{const v=g.seriesKey!==null&&a.has(g.seriesKey),C=v&&a.size===1,T=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[g.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?$[g.seriesKey].color:"var(--color-mono-600)"}}):null,g.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:g.value})]});return g.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:T},g.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:C,onClick:()=>r(I=>{const w=new Set(I);return w.has(g.seriesKey)?w.delete(g.seriesKey):w.add(g.seriesKey),w.size===0?I:w}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${C?"cursor-default":"hover:bg-surface-hover"}`,children:T},g.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(oc,{data:m,xKey:"date",series:S,xTickFormatter:Sn,labelFormatter:Pt}),e.jsx("ul",{className:"sr-only",children:m.map(g=>e.jsxs("li",{children:[Pt(g.date),":"," ",S.map(v=>`${v.label} ${$[v.dataKey].formatValue(g[v.dataKey])}`).join(", "),g.origin==="filled"?", no delivery reported":""]},g.date))})]}),e.jsxs("div",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"By campaign"}),e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Campaign performance"})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads campaign performance for the selected window"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Campaign"}),e.jsx("th",{className:"text-left",children:"Status"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Clicks"}),e.jsx("th",{className:"text-right",children:"Spend"}),e.jsx("th",{className:"text-right",children:"Conversions"}),e.jsx("th",{className:"text-right",children:"CTR"}),e.jsx("th",{className:"text-right",children:"Cost / conv."})]})}),e.jsx("tbody",{children:u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):u.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:g.name??g.campaignId,children:g.name??e.jsx("span",{className:"font-mono text-secondary",children:g.campaignId})}),e.jsx("td",{children:e.jsx(Ne,{tone:jy(g.status),children:Ny(g.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:zs.format(g.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:zs.format(g.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:En(g.totals.costMicros,y)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children: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(Ne,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:En(g.totals.costPerConversionMicros,y)})})]},g.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Sa(Bt(h.capturedAt))," · ","customer ",h.customerId," · ","latest closed day ",Pt(h.asOfDate),h.openDate?e.jsxs(e.Fragment,{children:[" · ",Pt(h.openDate)," still open, excluded"]}):null,h.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",h.timeZone]}):null]})]})]})}const Hr=20,Fs=50,Cy=50,ky=50;function Vi(t){return t==="viewer"}function Qi(t){return t?.status==="unavailable"}function Qc(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function zc(t,s){const n=new Map(s.map(r=>[r.id,r.label])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function Ya(t,s,n){if(t.kind==="all")return s.map(l=>l.id);if(t.kind==="specific")return s.filter(l=>t.propertyIds.includes(l.id)).map(l=>l.id);const a=new Set(t.groupIds),r=new Set(n.filter(l=>a.has(l.id)).flatMap(l=>l.propertyIds));return s.filter(l=>r.has(l.id)).map(l=>l.id)}function Ay(t,s,n){if(t.kind==="all")return`all ${n} ${n===1?"Property":"Properties"}`;if(t.kind==="specific")return n===1?"1 Property":`${n} Properties`;const a=t.groupIds.map(r=>s.find(l=>l.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function Wr(t,s){const n=new Set(s.map(r=>r.id)),a=t.propertyIds.filter(r=>n.has(r)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function pl(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function xl(t){return t==="matched"?"Matched":t==="duplicate"?"Duplicate":t==="ambiguous"?"Ambiguous":t==="proposed"?"Property needs review":t==="excluded"?"Property excluded":t==="invalid"?"Invalid row":"Not matched"}function Ja(t){return t.status==="duplicate"&&t.duplicateOfRow?`Duplicates row ${t.duplicateOfRow}.`:t.status==="matched"?null:t.reason==="group-label-ambiguous"?`More than one group matches “${t.group}”. Rename duplicate groups, then preview again.`:t.status==="ambiguous"?"More than one Property matches this row. Add an exact URL to choose one.":t.status==="unmatched"?"No included Property matches this row.":t.reason==="group-key-conflict"?`The group name “${t.group}” conflicts with an existing setup identity. Rename the group, then preview again.`:t.status==="invalid"?"Check the Property, group, and optional URL fields.":t.status==="proposed"?"Review this proposed Property before importing it.":t.status==="excluded"?"Include this Property before importing it.":t.reason??null}function vi(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Yr(t){return vi(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ji({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[l,i]=o.useState(""),[c,d]=o.useState(!1),m=l.trim().toLocaleLowerCase(),u=m?t.filter(y=>y.label.toLocaleLowerCase().includes(m)):t,p=c?u:u.slice(0,Cy),x=p.length<u.length;function h(){const y=new Set([...s,...p.map(f=>f.id)]);n(t.filter(f=>y.has(f.id)).map(f=>f.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:l,onChange:y=>i(y.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p.length===0,onClick:h,children:"Select all shown"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),u.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",p.length," of ",u.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:p.map(y=>{const f=s.includes(y.id);return e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-sm text-primary",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{"aria-label":`Select ${y.label}`,checked:f,type:"checkbox",onChange:b=>n(Qc(s,y.id,b.currentTarget.checked))}),e.jsx("span",{children:y.label})]}),y.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[y.urlCount," URLs"]})]},y.id)})}),x?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function zi(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(Ne,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Hi({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function Ry({value:t}){const[s,n]=o.useState(0),[a,r]=o.useState(0),[l,i]=o.useState(null),c=t.preview,d=c?.counts.needsAttention??0,m=c?.rows.filter(C=>C.status==="matched")??[],u=c?.rows??[],p=u.filter(C=>C.status!=="matched"),x=Math.max(1,Math.ceil(u.length/Fs)),h=Math.min(s,x-1),y=u.slice(h*Fs,(h+1)*Fs),f=Math.max(1,Math.ceil(p.length/Fs)),b=Math.min(a,f-1),j=p.slice(b*Fs,(b+1)*Fs),k=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,$=m.length>0&&!t.isApplying,S=c!==null&&l===c.previewChecksum,g=p.length>0&&b===f-1;o.useEffect(()=>{n(0),r(0),i(null)},[c?.previewChecksum]);async function v(C){if(C)try{t.onCsvChange(await C.text())}catch{}}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-group-import-title",className:"border-y border-default py-4",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h4",{id:"advanced-measurement-group-import-title",className:"text-sm font-medium text-heading",children:"Import groups from CSV"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Import market membership once instead of selecting the same Properties for every group."})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"CSV file"}),e.jsx("input",{"aria-label":"Group membership CSV file",type:"file",accept:".csv,text/csv",disabled:t.isReviewing||t.isApplying,onChange:C=>{v(C.currentTarget.files?.[0])},className:"mt-1 block min-h-11 w-full text-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary"})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Or paste CSV"}),e.jsx("textarea",{"aria-label":"Group membership CSV",rows:5,value:t.csv,disabled:t.isReviewing||t.isApplying,onChange:C=>t.onCsvChange(C.currentTarget.value),placeholder:`property,group,url
|
|
3
|
-
Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!k,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),c?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[c.counts.matchedRows," matched · ",c.counts.groupsReady," group",c.counts.groupsReady===1?"":"s"," ready",d>0?` · ${d} need${d===1?"s":""} attention`:""]}),c.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:c.groupChanges.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:C.label}),e.jsx("td",{className:"text-secondary",children:C.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:C.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[C.addedTargetKeys.length,C.unchangedTargetKeys.length>0?` · ${C.unchangedTargetKeys.length} already members`:""]})]},C.groupKey))})]})}):null,c.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",c.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:y.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(Ne,{tone:pl(C.status),children:xl(C.status)}),Ja(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Ja(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",h+1," of ",x," · ",c.rows.length," rows"]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h===0,onClick:()=>n(C=>Math.max(0,C-1)),children:"Previous 50 rows"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h===x-1,onClick:()=>n(C=>Math.min(x-1,C+1)),children:"Next 50 rows"})]})]}):null,d>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",d," row",d===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:j.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(Ne,{tone:pl(C.status),children:xl(C.status)}),Ja(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Ja(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",b+1," of ",f]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===0,onClick:()=>r(C=>Math.max(0,C-1)),children:"Previous 50 exceptions"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===f-1,onClick:()=>r(C=>Math.min(f-1,C+1)),children:"Review next 50 exceptions"})]}),e.jsxs("label",{className:"mt-3 flex min-h-11 max-w-xl items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:S,disabled:t.isApplying||!g,onChange:C=>i(C.currentTarget.checked?c.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",d," row",d===1?"":"s"," will be skipped."]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!$||!S,onClick:()=>{t.onApply(m.map(C=>C.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${m.length} matched row${m.length===1?"":"s"}`})]}):e.jsx(P,{type:"button",className:"mt-3 min-h-11",disabled:!$,onClick:()=>{t.onApply(m.map(C=>C.dataRow))},children:t.isApplying?"Creating groups…":`Create ${c.counts.groupsReady} group${c.counts.groupsReady===1?"":"s"} with ${m.length} membership${m.length===1?"":"s"}`})]}):null]})}const Py="—";function Iy({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:k,onAudienceChange:$,assignmentImpact:S=null,isPreviewingAssignmentImpact:g=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:C,assignmentNotice:T=null,onReplaceAssignments:I,isReplacingAssignments:w=!1,onBack:V,onContinue:F}){const[z,B]=o.useState(""),[Q,se]=o.useState(!1),[K,U]=o.useState(!1),[J,q]=o.useState(""),[X,L]=o.useState(""),[D,ee]=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=k,we=$,Y=Ya(oe,n,j),ue=Y.length,he=ue>0&&r.length>0&&!l&&!i&&!g&&S!==null&&v===null,Z=u??p,me=z.trim().toLocaleLowerCase(),G=me?a.filter(A=>Yr(A).toLocaleLowerCase().includes(me)):a,pe=G.filter(A=>(A.propertyIds?.length??0)===0),Ee=K?pe:G,Re=Q?Ee:Ee.slice(0,ky),re=Re.filter(A=>!vi(A)),xe=[...new Set(J.split(`
|
|
4
|
-
`).map(A=>A.trim()).filter(Boolean))],Ae=[...X.matchAll(/\{([a-z][\w-]*)\}/gi)].map(A=>A[1]),et=n.filter(A=>Y.includes(A.id)),Le=Ae.length===0||X.trim()===""?[]:et.map(A=>({propertyId:A.id,text:Ae.reduce((be,Ke)=>be.replaceAll(`{${Ke}}`,A.label),X.trim())})),O=[...new Set(Le.map(A=>A.text))];function ke(){const A=new Set([...r,...re.map(be=>be.id)]);d(a.filter(be=>A.has(be.id)).map(be=>be.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:A=>{const be=A.currentTarget.value;be==="all"?we({kind:"all"}):be==="specific"?we({kind:"specific",propertyIds:[]}):be.startsWith("group:")&&we({kind:"groups",groupIds:[be.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(A=>{const be=Ya({kind:"groups",groupIds:[A.id]},n,j).length;return e.jsx("option",{value:`group:${A.id}`,disabled:be===0,children:Wr(A,n)},A.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(A=>{const be=j.find(Ke=>Ke.id===A);return be?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(be,n),e.jsx("button",{type:"button","aria-label":`Remove ${be.name}`,className:"-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>{const Ke=oe.groupIds.filter(Ve=>Ve!==be.id);we(Ke.length>0?{kind:"groups",groupIds:Ke}:{kind:"all"})},children:"×"})]},be.id):null})}),j.some(A=>!oe.groupIds.includes(A.id)&&Ya({kind:"groups",groupIds:[A.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:A=>{A.currentTarget.value&&we({kind:"groups",groupIds:[...oe.groupIds,A.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(A=>!oe.groupIds.includes(A.id)).map(A=>{const be=Ya({kind:"groups",groupIds:[A.id]},n,j).length;return e.jsx("option",{value:A.id,disabled:be===0,children:Wr(A,n)},A.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:A=>{we({kind:"specific",propertyIds:A})}})}):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:J,onChange:A=>q(A.currentTarget.value),placeholder:`best apartments in dallas
|
|
5
|
-
luxury apartments atlanta
|
|
6
|
-
pet friendly apartments austin`}),f?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:f}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:xe.length===0||y||i,onClick:()=>{Promise.resolve(x(xe)).then(()=>q(""),()=>{})},children:y?"Adding…":`Add ${xe.length||""} ${xe.length===1?"query":"queries"}`.replace(" "," ")}),b?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:b,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:X,onChange:A=>L(A.target.value),placeholder:"apartments near {property}"}),X.trim()===""?null:Ae.length===0?e.jsxs("p",{className:"mt-2 text-sm text-caution",children:["Add ","{property}"," to the pattern, or use the box above for a single query."]}):et.length===0?e.jsx("p",{className:"mt-2 text-sm text-caution",children:"Select at least one Property to write queries for."}):e.jsxs("div",{className:"mt-2 rounded-md border border-base bg-bg-elevated p-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:[O.length," ",O.length===1?"query":"queries",", one per selected Property:"]}),e.jsx("ul",{className:"mt-1 mb-0 list-none space-y-0.5 p-0",children:O.slice(0,3).map(A=>e.jsx("li",{className:"text-sm text-strong",children:A},A))}),O.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",O.length-3," more"]}):null]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Le.length===0||y||i||!h,onClick:()=>{h&&Promise.resolve(h(Le)).then(()=>L(""),()=>{})},children:y?"Adding…":`Add ${Le.length||""} ${Le.length===1?"query":"queries"}`.replace(" "," ")}),Le.length>0?e.jsxs("p",{className:"mt-2 mb-0 text-sm text-secondary",children:["Each query is measured on the one Property it names, so this adds"," ",Le.length," assignment",Le.length===1?"":"s","."]}):null]})]})]}),ne?null:e.jsx("div",{className:"space-y-3 border-y border-default py-4",children:a.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:re.length===0,onClick:ke,children:"Select all shown queries"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>d([]),children:"Clear query selection"}),e.jsx(P,{type:"button",size:"sm",className:"min-h-11",disabled:!he,onClick:()=>{m({queryIds:r,propertyIds:Y,...oe.kind==="groups"?{groupIds:oe.groupIds}:{}})},children:l?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${Ay(oe,j,ue)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[g?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,S?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",S.assignmentCount," Property assignment",S.assignmentCount===1?"":"s"," · ",S.addedAssignments," new, ",S.alreadyPresentAssignments," already assigned"," · ",S.fullRunProviderCalls," provider request",S.fullRunProviderCalls===1?"":"s"," per full run"," · ",S.addedProviderCalls," new",oe.kind==="groups"?` · ${S.resolvedPropertyCount} unique ${S.resolvedPropertyCount===1?"Property":"Properties"}${S.overlapCount>0?`, ${S.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):v?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:v}),C?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:C,children:"Retry impact"}):null,V?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:V,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",ue," Properties = ",r.length*ue," assignments"]})]}),T?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:T}):null]})}),a.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search queries"}),e.jsx("input",{type:"search",value:z,onChange:A=>{B(A.currentTarget.value),se(!1)},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400",placeholder:"Query text"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:["Showing ",Re.length," of ",Ee.length," queries,"," ",G.length-pe.length," of ",G.length," applied"]}),ne||pe.length===0?null:e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{U(A=>!A),se(!1)},children:K?"Show all queries":`Show the ${pe.length} not applied`})]})]}):null,Re.length>0?e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[ne?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),ne?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:Re.map(A=>{const be=vi(A),Ke=Yr(A),Ve=r.includes(A.id),Ge=(A.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[ne?null:be?e.jsx("td",{"aria-hidden":"true"}):e.jsx("td",{className:"p-0",children:e.jsx("label",{className:"flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{"aria-label":`Select query ${Ke}`,checked:Ve,type:"checkbox",onChange:ge=>d(Qc(r,A.id,ge.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:Ke})}),e.jsx("td",{className:"text-secondary",children:zc(A.propertyIds??[],n)}),ne?null:e.jsx("td",{className:"text-right",children:Ge?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[I?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||w,onClick:()=>ee({queryId:A.id,propertyIds:[...A.propertyIds??[]]}),"aria-label":`Replace query assignments for ${Ke}`,children:"Replace assignments"}):null,e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{Z(A.id)},"aria-label":`Clear query assignments for ${Ke}`,children:"Clear assignments"})]}):null})]},A.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,ne||!D?null:(()=>{const A=a.find(Ve=>Ve.id===D.queryId),be=A?Yr(A):"this query",Ke=D.propertyIds.filter(Ve=>n.some(Ge=>Ge.id===Ve));return e.jsxs("section",{"aria-labelledby":"advanced-measurement-replace-assignments-title",className:"border-y border-default py-4",children:[e.jsx("h4",{id:"advanced-measurement-replace-assignments-title",className:"text-sm font-medium text-heading",children:"Replace assigned Properties"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:["This replaces every Property assigned to “",be,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(ji,{legend:"Properties for this query",properties:n,selectedPropertyIds:Ke,onSelectedPropertyIdsChange:Ve=>ee(Ge=>Ge&&{...Ge,propertyIds:[...Ve]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:w||i,onClick:()=>ee(null),children:"Keep current assignments"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ke.length===0||w||i||!I,onClick:()=>{I&&Promise.resolve(I({queryId:D.queryId,propertyIds:Ke}))},children:w?"Replacing assignments…":`Replace with ${Ke.length} ${Ke.length===1?"Property":"Properties"}`})]})]})})(),Re.length<Ee.length?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>se(!0),children:"Show all queries"}):null,ne?null:e.jsxs(e.Fragment,{children:[c?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${V?"justify-between":"justify-end"}`,children:[V?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:V,children:"Back"}):null,e.jsx(P,{type:"button",variant:he?"outline":"default",className:"min-h-11",disabled:!c||i,onClick:F,children:"Continue"})]})]})]})}function Ty({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:l=!1,onGroupDraftChange:i,onSaveGroup:c,onEditGroup:d,onRemoveGroup:m,onClearGroupDraft:u,membershipImport:p,onBack:x,onContinue:h}){if(Qi(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(Hi,{message:s.message})});const y=Vi(t),f=r.name.trim().length>0&&r.propertyIds.length>0&&!l,b=n.filter(S=>r.propertyIds.includes(S.id)).length,j=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,k=!y&&(d!==void 0||m!==void 0);function $(){if(u){u();return}i({name:"",propertyIds:[],competitorDomains:""})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-groups-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-groups-title",children:"Groups"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Use groups to assign queries by market and compare competitors."})]})}),y?e.jsx(zi,{}):null,y||!p?null:e.jsx(Ry,{value:p}),y?null:e.jsxs("div",{className:"space-y-4 border-y border-default py-4",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Group name"}),e.jsx("input",{"aria-label":"Group name",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.name,onChange:S=>i({...r,name:S.currentTarget.value}),placeholder:"Waterfront venues"})]}),e.jsxs("details",{children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:[b," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(ji,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:S=>i({...r,propertyIds:S})})})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Competitor domains"}),e.jsx("input",{"aria-label":"Competitor domains",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.competitorDomains,onChange:S=>i({...r,competitorDomains:S.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!f,onClick:()=>{c(r)},children:l?"Saving group…":"Save group"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!j,onClick:$,children:"Clear form"}),e.jsx("p",{className:"text-sm text-secondary",children:"Competitor domains are used only in this group's competitor report. Membership changes affect future assignments only."})]}),j?e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Save this group or clear the form before continuing."}):null]}),e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Competitors"}),k?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.name}),e.jsx("td",{className:"text-secondary",children:zc(S.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:S.competitors.length>0?S.competitors.join(", "):"None"}),k?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[d?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${S.name}`,onClick:()=>d(S),children:"Edit"}):null,m?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${S.name}`,onClick:()=>{m(S.id)},children:"Remove"}):null]})}):null]},S.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,y?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${x?"justify-between":"justify-end"}`,children:[x?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:x,children:"Back"}):null,e.jsx(P,{type:"button",className:"min-h-11",disabled:j,onClick:h,children:a.length===0&&!j?"Continue without groups":"Continue"})]})]})}function My({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:l,onReviewChanges:i,isReviewing:c=!1,canReviewChanges:d=!0,reviewedChanges:m,reviewChangesError:u,canPublish:p,isPublishing:x=!1,onPublish:h}){const[y,f]=o.useState(Hr),[b,j]=o.useState(Hr),[k,$]=o.useState(Hr);if(Qi(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(Hi,{message:s.message})});const S=Vi(t),g=r?.items??[],v=r?.coverageItems??[],C=g.slice(0,y),T=v.slice(0,b),I=a.slice(0,k),w=i!==void 0,V=m!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),S?e.jsx(zi,{}):null,r?e.jsx("section",{"aria-labelledby":"advanced-measurement-sitemap-review-title",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:e.jsxs("div",{className:"max-w-2xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{id:"advanced-measurement-sitemap-review-title",className:"text-sm font-medium text-heading",children:"Sitemap changes need review"}),r.exceptionCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.exceptionCount," sitemap ",r.exceptionCount===1?"entry needs":"entries need"," review."]}):null,r.coverageReviewCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.coverageReviewCount," ",r.coverageReviewCount===1?"Property has":"Properties have"," URL coverage changes."]}):null]}),r.exceptionCount>0?e.jsxs("details",{className:"border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["URLs not added to Properties (",r.exceptionCount,")"]}),g.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:C.map(F=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:F.url}),e.jsx("p",{className:"mt-1 text-secondary",children:F.reason})]},`${F.url}-${F.reason}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected sitemap URLs before confirming."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",C.length," of ",g.length]}),C.length<g.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>f(F=>F+Fs),children:"Show next 50 URLs"}):null]})]}):null,S?e.jsx("p",{className:"text-sm text-secondary",children:"An editor must finish this review before publishing."}):e.jsxs(e.Fragment,{children:[r.coverageReviewCount>0?e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"For changed Property URLs"}),e.jsxs("p",{className:"text-sm text-secondary",children:["This choice applies to all ",r.coverageReviewCount," changed ",r.coverageReviewCount===1?"Property":"Properties","."]}),e.jsxs("details",{className:"border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review Property URL changes (",r.coverageReviewCount,")"]}),T.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[T.map(F=>e.jsxs("section",{"aria-label":`${F.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:F.property}),e.jsxs("div",{className:"mt-2 grid gap-3 text-sm md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Saved URLs"}),e.jsx("ul",{className:"mt-1 space-y-1",children:F.savedUrls.map(z=>e.jsx("li",{className:"break-all text-secondary",children:z},z))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),F.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:F.currentSitemapUrls.map(z=>e.jsx("li",{className:"break-all text-secondary",children:z},z))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},F.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",T.length," of ",v.length]}),T.length<v.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>j(F=>F+Fs),children:"Show next 50 URL changes"}):null]})]}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected Properties before confirming."})]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="keep-existing",onChange:()=>r.onCoverageResolutionChange("keep-existing")}),"Keep existing Property URLs"]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="replace-with-imported",onChange:()=>r.onCoverageResolutionChange("replace-with-imported")}),"Use current sitemap URLs"]})]}):null,e.jsx(P,{type:"button",className:"min-h-11",onClick:()=>{r.onResolve()},children:"Confirm sitemap changes"})]})]})}):null,e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Groups"}),e.jsx("th",{children:"Assignments"}),e.jsx("th",{children:"Provider requests / run"})]})}),e.jsx("tbody",{children:e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-heading",children:n.properties}),e.jsx("td",{className:"tabular-nums text-heading",children:n.queries}),e.jsx("td",{className:"tabular-nums text-heading",children:n.groups}),e.jsx("td",{className:"tabular-nums text-heading",children:n.assignments??"—"}),e.jsx("td",{className:"tabular-nums text-heading",children:n.providerCalls??Py})]})})]})}),n.providerCalls===void 0?e.jsx("p",{className:"supporting-copy",children:"Review changes to see how many provider requests one run will make."}):null,n.assignments!==void 0&&n.assignments>n.queries?e.jsxs("p",{className:"supporting-copy",children:[n.queries," ",n.queries===1?"query":"queries"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a query aimed at a market is measured on every Property in it."]}):null,m?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:m.title}),m.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:m.items.map((F,z)=>e.jsx("li",{children:F},`${F}-${z}`))}):null]}):null,e.jsxs("section",{"aria-labelledby":"advanced-measurement-flagged-exceptions-title",className:"space-y-3",children:[e.jsx("h4",{id:"advanced-measurement-flagged-exceptions-title",className:"text-sm font-medium text-heading",children:"Flagged exceptions"}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No flagged exceptions."}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"divide-y divide-default border-y border-default",children:I.map(F=>e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-heading",children:F.title}),F.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:F.detail}):null]}),e.jsx(Ne,{tone:F.tone??"caution",children:"Needs attention"})]},F.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",I.length," of ",a.length]}),I.length<a.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>$(F=>F+Fs),children:"Show next 50 exceptions"}):null]})]})]}),S?null:e.jsxs(e.Fragment,{children:[w&&u?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:u}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${l?"justify-between":"justify-end"}`,children:[l?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:l,children:"Back"}):null,i!==void 0&&!V?e.jsx(P,{type:"button",className:"min-h-11",disabled:c||!d,onClick:()=>{i()},children:c?"Reviewing changes…":"Review changes"}):e.jsx(P,{type:"button",className:"min-h-11",disabled:!p||x,onClick:()=>{h()},children:x?"Publishing setup…":"Publish setup"})]})]})]})}const Ly={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function $y(t){return t.trim().toLocaleLowerCase()}function qy(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function Ey({property:t}){const s=t.urls??[t.url];return s.length<=1?e.jsx("span",{children:s[0]??"No URL"}):e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-xs font-medium text-primary",children:[s.length," URLs"]}),e.jsx("ul",{className:"mt-2 space-y-1",children:s.map(n=>e.jsx("li",{className:"break-all font-mono text-xs text-secondary",children:n},n))})]})}function Dy({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const l=!t||r==="reviewing",i=l||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function c(d,m){n({...s,[d]:m})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":r==="reviewing",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-import-heading",className:"text-lg font-semibold text-heading",children:"Import Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review sitemap entries before choosing the Properties to measure."})]}),t?null:e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm text-secondary",children:[e.jsx(Ne,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:d=>{d.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:l,onChange:d=>c("sitemapUrl",d.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:l,onChange:d=>c("examplePropertyUrl",d.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:l,onChange:d=>c("preferredHost",d.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:l,onChange:d=>c("propertyPathPattern",d.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:l,onChange:d=>c("additionalHost",d.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:l,onChange:d=>c("additionalPathPattern",d.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:l,onChange:d=>c("excludedPaths",d.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(P,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function Oy({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:l,onSelectedPropertyIdsChange:i,onContinue:c,isContinuing:d=!1,onRetryProperties:m,onReturnToImport:u,maxVisibleProperties:p,onShowAllProperties:x}){const h=$y(a),y=s.filter(I=>qy(I,h)),f=Math.max(1,p??y.length),b=y.slice(0,f),j=new Set(l),k=s.filter(I=>j.has(I.id)).map(I=>I.id),$=b.length<y.length;function S(I){const w=new Set(I);i(s.filter(V=>w.has(V.id)).map(V=>V.id))}function g(I,w){if(!t||d)return;const V=new Set(k);w?V.add(I):V.delete(I),S(V)}function v(){!t||d||S([...k,...b.map(I=>I.id)])}function C(){!t||d||i([])}function T(){!t||d||k.length===0||c(k)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||d,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:m,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:m,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):null,n==="ready"&&s.length>0?e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:a,disabled:d,onChange:I=>r(I.target.value),className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),t?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:d,onClick:v,children:"Select all shown"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:d||k.length===0,onClick:C,children:"Clear selection"})]}):null]}),y.length===0?e.jsxs("div",{className:"mt-4 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties match this search."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Clear the search or review the sitemap again."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",b.length," of ",y.length," Properties"]}),e.jsxs("p",{children:[k.length," of ",s.length," selected"]})]}),e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"w-full min-w-150 text-left text-sm","aria-label":"Properties to review",children:[e.jsx("thead",{className:"bg-surface-subtle text-xs font-medium uppercase tracking-wide text-secondary",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-3 py-2",children:"Property"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"URL"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"State"}),t?e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Include"}):null]})}),e.jsx("tbody",{children:b.map(I=>{const w=Ly[I.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:I.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(Ey,{property:I})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(Ne,{tone:w.tone,children:w.label})}),t?e.jsx("td",{className:"p-0 text-right",children:e.jsx("label",{className:"ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{type:"checkbox","aria-label":`Select ${I.name}`,checked:k.includes(I.id),disabled:d,onChange:V=>g(I.id,V.target.checked),className:"size-6 accent-accent"})})}):null]},I.id)})})]})}),$&&x?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:d,onClick:x,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(P,{type:"button",variant:"ghost",disabled:d,onClick:u,children:"Back"}),e.jsx(P,{type:"button",disabled:d||k.length===0,onClick:T,children:d?"Saving Properties…":"Continue"})]}):null]}):null]})}function Fy(t){return t.activeStep==="import"?e.jsx(Dy,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(Oy,{...t})}const Ky=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function Gy({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:l}){const i=o.useRef(null),c=o.useRef(null),d=o.useRef(null),m=o.useRef(null),u=o.useRef(!1),[p,x]=o.useState(!1);return o.useEffect(()=>{s||x(!1)},[s]),o.useEffect(()=>{const h=u.current;u.current=p,p?d.current?.focus():h&&m.current?.focus()},[p]),o.useEffect(()=>{const h=i.current;if(i.current=t,h===null||h===t)return;const y=c.current?.querySelector('h1, h2, h3, [role="heading"]');y&&(y.tabIndex=-1,y.focus())},[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 w-full sm:flex-1",children:[e.jsx("h2",{children:"Advanced measurement setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties and queries you want to measure."})]}),s?e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end",children:[e.jsx(Ne,{tone:"caution",children:"Unpublished changes"}),n&&a?p?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",role:"group","aria-label":"Confirm discard",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Discard all unpublished changes?"}),e.jsx(P,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>x(!1),children:"Keep editing"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(P,{ref:m,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>x(!0),children:"Discard changes"}):null]}):null]}),e.jsx("div",{role:"group","aria-label":"Advanced measurement setup progress",className:"overflow-x-auto border-b border-default",children:e.jsx("ol",{className:"flex min-w-max gap-6",children:Ky.map(h=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===h.id?"step":void 0,onClick:()=>r(h.id),className:`block min-h-11 border-b-2 bg-transparent px-1 py-3 text-left text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${t===h.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:h.label}):e.jsx("span",{"aria-current":t===h.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===h.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:h.label})},h.id))})}),e.jsx("div",{ref:c,children:l})]})}function _y(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Fy,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(Iy,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(Ty,{...t.groups,access:s}):"review"in t?e.jsx(My,{...t.review,access:s}):null}function Xa(t){return e.jsx(Gy,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:_y(t)})}function Hc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Wt(t){return{"If-Match":t,"Idempotency-Key":Hc()}}function fn(t){return t instanceof Vn&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function os(t,s){return t instanceof Vn?s:(t instanceof Error?t.message.trim():"")||s}function Uy(t){const s="Could not calculate assignment impact.";if(!(t instanceof Vn)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const By={loadSetup:t=>jt(()=>fm({client:W,path:{name:t}})),loadDraft:t=>jt(()=>gm({client:W,path:{name:t}})),createDraft:(t,s)=>jt(()=>xm({client:W,path:{name:t},headers:{"Idempotency-Key":Hc()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>jt(()=>pm({client:W,path:{name:t},headers:Wt(s),body:n})),applySitemapSelection:(t,s,n,a)=>jt(()=>hm({client:W,path:{name:t},headers:Wt(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>jt(()=>mm({client:W,path:{name:t},body:s})),applyAssignments:(t,s,n)=>jt(()=>um({client:W,path:{name:t},headers:Wt(s),body:n})),replaceAssignments:(t,s,n)=>jt(()=>dm({client:W,path:{name:t},headers:Wt(s),body:n})),applyPairedAssignments:(t,s,n)=>jt(()=>cm({client:W,path:{name:t},headers:Wt(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>jt(()=>lm({client:W,path:{name:t},headers:Wt(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>jt(()=>om({client:W,path:{name:t},headers:Wt(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>jt(()=>im({client:W,path:{name:t},headers:Wt(s),body:{target:n}})),upsertGroup:(t,s,n)=>jt(()=>rm({client:W,path:{name:t},headers:Wt(s),body:{group:n}})),removeGroup:(t,s,n)=>jt(()=>am({client:W,path:{name:t},headers:Wt(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>jt(()=>nm({client:W,path:{name:t},headers:Wt(s),body:n})),removeCompetitor:(t,s,n,a)=>jt(()=>sm({client:W,path:{name:t},headers:Wt(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>jt(()=>tm({client:W,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>jt(()=>em({client:W,path:{name:t},headers:Wt(s),body:n})),compilePreview:t=>jt(()=>Zu({client:W,path:{name:t}})),diffPreview:t=>jt(()=>Xu({client:W,path:{name:t}})),publish:(t,s,n)=>jt(()=>Ju({client:W,path:{name:t},headers:Wt(s),body:n})),discard:(t,s)=>jt(()=>Yu({client:W,path:{name:t},headers:Wt(s)}))},gl={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},oa={name:"",propertyIds:[],competitorDomains:""},fl=50;function ua(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Vy(t){const s=t.trim();if(!s)throw new Error("Add a sitemap URL.");let n;try{n=new URL(s.includes("://")?s:`https://${s}`)}catch{throw new Error("Sitemap URL must be a valid web address.")}return(n.pathname===""||n.pathname==="/")&&(n.pathname="/sitemap.xml"),n.toString()}function yl(t){const s=t.propertyPathPattern.trim();if(s){const r=(s.startsWith("/")?s:`/${s}`).split("/").slice(1);if(r.filter(i=>i==="*"||i==="{slug}").length!==1||r.some(i=>i.includes("*")&&i!=="*"))throw new Error("Property URL pattern must contain exactly one * or {slug} segment.");return`/${r.map(i=>i==="*"?"{slug}":i).join("/")}`}const n=t.examplePropertyUrl.trim();if(!n)throw new Error("Add one example Property page so Canonry can identify the matching URLs.");try{const a=new URL(n).pathname.split("/").filter(Boolean);if(a.length===0)throw new Error;return a[a.length-1]="{slug}",`/${a.join("/")}`}catch{throw new Error("Example Property page must be a valid web address.")}}function Qy(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,c=i.startsWith("*"),d=i.endsWith("*"),m=i.slice(c?1:0,d?-1:void 0).trim();if(!m)throw new Error("Ignored URL patterns must include text besides *.");const u=c&&d?"contains":c?"suffix":d?"prefix":"exact",p=`${u}:${m}`;n.has(p)||(n.add(p),s.push({kind:u,value:m}))}return s}function zy(t){const s=Vy(t.sitemapUrl),n=t.examplePropertyUrl.trim()?ua(t.examplePropertyUrl):null,a=ua(t.preferredHost)??n??ua(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=ua(t.additionalHost),l=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(l!==i||l&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const c=Qy(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:yl(t)},...r?{aliases:[{host:r,pathTemplate:yl({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...c.length>0?{excludedSlugPatterns:c}:{}}}}function Hy(t){return!t||t.authoring.targets.length===0?"import":t.authoring.targets.some(s=>s.status==="proposed")?"properties":t.authoring.assignments.length===0?"groups":t.baseActiveRevision===null?"review":"properties"}function Wy(t,s){return!t||t.authoring.targets.length===0?"import":!t.authoring.targets.some(n=>n.status!=="excluded")||t.authoring.targets.some(n=>n.status==="proposed")?"properties":t.authoring.assignments.length===0&&s==="review"?"groups":s}function bl(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function Yy(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Jr(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function Ni(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function vl(t){return ua(t)}function Wc(t,s){if(s[0]!=="targets")return;const n=s[1];if(typeof n=="number")return t?.targets[n];if(typeof n=="string")return t?.targets.find(a=>a.stableKey===n)}function Yc(t,s){if(s[0]!=="groups")return;const n=s[1];if(typeof n=="number")return t?.groups[n];if(typeof n=="string")return t?.groups.find(a=>a.stableKey===n)}function Jc(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Xc(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Jy(t,s){const n=Wc(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="urlMatchers"&&typeof r=="number"){const l=n.urlMatchers[r];return l?`${n.label} — ${l}`:n.label}if(a==="aliases"&&typeof r=="number"){const l=n.aliases[r];return l?`${n.label} — ${l}`:n.label}return n.label}function Xy(t,s){const n=Yc(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="competitors"&&typeof r=="number"){const l=n.competitors.at(r)?.domain;return l?`${n.label} — ${l}`:n.label}if(a==="targetKeys"&&typeof r=="number"){const l=Xc(t.authoring,n.targetKeys[r]);return`${n.label} — ${l}`}return n.label}function Zy(t,s){const n=Jc(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${Xc(t.authoring,n.targetKey)} — ${a}`}function eb(t,s){return s.path[0]==="identities"?"Project domain":Jy(t,s)??Xy(t,s)??Zy(t,s)}function jl(t,s,n){const a=Jc(t.authoring,s.path);if(!a)return;const r={...t.authoring?.defaultContext,...a.contextOverride},l=s.path.at(-1);if(n==="models"&&typeof l=="string")return r.models?.[l];if(n==="locations"&&typeof l=="number")return r.locations?.[l]}function tb(t,s){const n=eb(s,t);switch(t.ruleId){case"invalid-project-identity":return{title:"Fix the project domain",detail:"The project domain is not valid. Update it in project settings, then review again.",tone:"negative",affected:n};case"target-limit-exceeded":return{title:"Reduce Properties",detail:"This setup exceeds the Properties publishing limit. Remove some Properties, then review again.",tone:"negative"};case"duplicate-target-key":return{title:"Resolve duplicate Properties",detail:"Two Properties use the same setup identifier. Rename or recreate one, then review again.",tone:"negative",affected:n};case"no-included-targets":return{title:"Include a Property",detail:"Include at least one Property before publishing.",tone:"negative"};case"target-url-matcher-invalid":return{title:"Fix a Property URL",detail:"Use a valid web address, site-wide address, or URL pattern for this Property.",tone:"negative",affected:n};case"target-url-matcher-unowned":return{title:"Use a project domain",detail:"This Property URL must use the project domain or one of its subdomains.",tone:"negative",affected:n};case"target-url-matcher-ambiguous":return{title:"Separate Property URL coverage",detail:"This URL is assigned to more than one Property at the same specificity. Update one of the URLs.",tone:"negative",affected:n};case"target-alias-ambiguous":return{title:"Use distinct Property names",detail:"This name or alias matches another Property. Make each Property name and alias distinct.",tone:"negative",affected:n};case"execution-context-no-provider":return{title:"Choose a provider",detail:"Choose at least one provider before publishing.",tone:"negative",affected:n};case"invalid-provider-model":return{title:"Fix provider settings",detail:"Choose the provider that runs this model, or remove the model setting.",tone:"negative",affected:[n,jl(s,t,"models")].filter(Boolean).join(" — ")||void 0};case"invalid-location":return{title:"Fix a location",detail:"Choose a location configured for this project, or remove it from the query.",tone:"negative",affected:[n,jl(s,t,"locations")].filter(Boolean).join(" — ")||void 0};case"target-without-aliases":return{title:"Add Property aliases",detail:"Add a name or alias to measure mentions.",tone:"caution",affected:n};case"duplicate-group-key":return{title:"Resolve duplicate groups",detail:"Two groups use the same setup identifier. Rename one group, then review again.",tone:"negative",affected:n};case"group-unknown-target":return{title:"Fix group Properties",detail:"This group contains a Property that is no longer in setup. Remove it or add the Property back.",tone:"negative",affected:n};case"group-excluded-target":return{title:"Include or remove a grouped Property",detail:"This group contains an excluded Property. Include it or remove it from the group.",tone:"negative",affected:n};case"competitor-invalid-domain":return{title:"Fix a competitor domain",detail:"Enter a valid competitor domain.",tone:"negative",affected:n};case"competitor-matches-project":return{title:"Remove a project domain",detail:"A competitor cannot use the project domain.",tone:"negative",affected:n};case"competitor-duplicate":return{title:"Remove a duplicate competitor",detail:"List each competitor domain only once in a group.",tone:"negative",affected:n};case"duplicate-assignment":return{title:"Remove a duplicate query",detail:"Assign each query to a Property only once.",tone:"negative",affected:n};case"assignment-unknown-target":return{title:"Fix a query assignment",detail:"This query is assigned to a Property that is no longer in setup. Remove the assignment or add the Property back.",tone:"negative",affected:n};case"assignment-excluded-target":return{title:"Include or unassign a Property",detail:"This query is assigned to an excluded Property. Include it or remove the assignment.",tone:"negative",affected:n};case"assignment-unknown-query":return{title:"Remove an unavailable query",detail:"This assignment refers to a tracked query that is no longer available. Remove it or add the query back to the project.",tone:"negative",affected:n};case"assignment-unclassified":return{title:"Classify a query",detail:"Choose Branded or Non-brand for this query before publishing.",tone:"negative",affected:n};case"query-limit-exceeded":return{title:"Reduce queries",detail:"This setup exceeds the distinct-query publishing limit. Remove some query assignments, then review again.",tone:"negative"};case"target-without-assignments":return{title:"Assign queries",detail:"Assign at least one query to measure a Property.",tone:"caution",affected:n};case"invalid-compiled-plan":return{title:"Fix setup details",detail:"A setup value could not be validated. Review the affected item, then review again.",tone:"negative",affected:n};case"compiled-plan-too-large":return{title:"Reduce setup size",detail:"This setup is too large to publish. Remove Properties, queries, or groups, then review again.",tone:"negative"};case"active-revision-schema-v1":return{title:"Historical results will be kept",detail:"Existing results remain visible after you publish this setup.",tone:"neutral"}}return{title:t.severity==="fail"?"An unexpected setup issue blocks publishing":"An unexpected setup issue needs review",detail:t.severity==="fail"?"Review the affected item, make a correction, and review again. If it remains blocked, contact support.":"Review the affected item before publishing. If it remains, contact support.",tone:t.severity==="fail"?"negative":"caution",affected:n}}function Za(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function Zc(t){const s=[...new Set(t)];return s.length===0?"":s.length===1?` Affected: ${s[0]}.`:s.length<=3?` Affected: ${s.join(", ")}.`:` Affected: ${s.slice(0,3).join(", ")}, and ${s.length-3} more.`}function sb(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${Za(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${Za(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${Za(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${Za(n,"item")} need review.`:s}})()}${Zc(a)}`}function nb(t,s){const n=new Map;for(const a of t){const r=tb(a,s),l=[a.ruleId,a.severity,r.title,r.detail].join("\0"),i=n.get(l)??{ruleId:a.ruleId,severity:a.severity,meaning:r,paths:new Set,affected:new Set};i.paths.add(JSON.stringify(a.path)),r.affected&&i.affected.add(r.affected),n.set(l,i)}return[...n.values()].map((a,r)=>({id:`${a.ruleId}-${a.severity}-${r}`,title:a.meaning.title,detail:sb(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function Xr(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function Zr(t,s,n){const a=Wc(n,t.path),r=Yc(n,t.path),l=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=l?n?.targets.find(u=>u.stableKey===l):void 0,c=a?.label??r?.label,d=Zc(c?[c]:[]),m={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...m,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${d}`};case"excluded-target-has-assignments":return{...m,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${d}`};case"group-unknown-target":return{...m,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${d}`};case"measurement.discovery.proposed_new_target":{const u=Xr(a)??"the proposed Property";return{...m,title:"Review a new Property",detail:`Review ${u}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const u=Xr(a)??"the proposed Property",p=i?.label??"an existing Property";return{...m,title:"Review a moved Property",detail:`Review ${u}. It may be the same Property as ${p}.`}}case"measurement.discovery.rebind_ambiguous":{const u=Xr(a)??"the proposed Property",p=i?.label??"an existing Property";return{...m,title:"Choose an existing Property",detail:`Review ${u}. It may match ${p}; choose the correct Property.`}}default:return{...m,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function ab(t,s=!1){const n=[],a=t.targets.added.length+t.targets.removed.length+t.targets.changed.length,r=t.groups.added.length+t.groups.removed.length+t.groups.changed.length,l=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),l>0&&n.push(`${l} query assignment ${l===1?"change":"changes"}`),r>0&&n.push(`${r} group ${r===1?"change":"changes"}`),s&&n.unshift("Existing results remain visible after you publish this setup."),{title:s?"Historical results will be kept":t.activeRevision===null?"New setup ready":"Changes ready",items:n.length>0?n:["No changes from the published setup."]}}function Rs(t){return[...new Set(t)]}function Ys(t){return Rs(t).sort()}function rb(t,s,n){return t.kind==="groups"?{groupKeys:Ys(t.groupIds),queryIds:Ys(n)}:{targetKeys:Ys(t.kind==="all"?s:t.propertyIds),queryIds:Ys(n)}}function ib(t){return{assignmentCount:t.assignments.requested,addedAssignments:t.assignments.added,alreadyPresentAssignments:t.assignments.alreadyPresent,resolvedPropertyCount:t.resolvedTargetKeys.length,overlapCount:t.overlapCount,addedProviderCalls:t.execution.addedProviderCalls,fullRunProviderCalls:t.execution.fullRunProviderCalls}}function Nl(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function ob(t){const s=t.plan;if(s.schemaVersion===2)return{defaultContext:{providers:[],locations:[]},targets:s.targets.map(a=>({stableKey:a.stableKey,label:a.label,status:"included",aliases:[...a.aliases],urlMatchers:a.urlMatchers.map(Nl).filter(Boolean),source:a.discoveryIdentity?"sitemap":"manual",...a.discoveryIdentity?{discoveryIdentity:a.discoveryIdentity}:{}})),assignments:s.assignments.map(a=>({targetKey:a.targetKey,queryId:a.queryId,queryClass:a.queryClass,classificationSource:"operator"})),groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:a.competitors.map(r=>({...r,aliases:[...r.aliases]}))}))};const n=s.targetQuerySelections.flatMap(a=>a.queryIds.map(r=>({targetKey:a.targetKey,queryId:r,queryClass:"unclassified",classificationSource:"rule"})));return{defaultContext:{providers:[],locations:[]},targets:s.targets.map(a=>({stableKey:a.stableKey,label:a.label,status:"included",aliases:[...a.aliases],urlMatchers:a.urls.map(Nl).filter(Boolean),source:"manual"})),assignments:n,groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:(a.competitors??[]).map(r=>({stableKey:Ni(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function lb({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:l,canEdit:i=!0,onCreateQueries:c,onManageProjectQueries:d,onPublished:m,service:u=By}){const[p,x]=o.useState(null),[h,y]=o.useState(null),[f,b]=o.useState("import"),[j,k]=o.useState(!0),[$,S]=o.useState(null),[g,v]=o.useState(null),[C,T]=o.useState([]),[I,w]=o.useState({...gl}),[V,F]=o.useState("idle"),[z,B]=o.useState(""),[Q,se]=o.useState(fl),[K,U]=o.useState([]),[J,q]=o.useState([]),[X,L]=o.useState({kind:"all"}),[D,ee]=o.useState(null),[ne,oe]=o.useState(null),[we,Y]=o.useState(!1),[ue,he]=o.useState(null),[Z,me]=o.useState(0),[G,pe]=o.useState(null),[Ee,Re]=o.useState({...oa}),[re,xe]=o.useState(null),[Ae,et]=o.useState(""),[Le,O]=o.useState(null),[ke,A]=o.useState(!1),[be,Ke]=o.useState(!1),[Ve,Ge]=o.useState(null),[ge,vt]=o.useState(null),[Qe,Je]=o.useState(null),[Dt,ct]=o.useState(null),[at,pt]=o.useState(null),Ct=o.useRef(0),It=o.useRef(0),He=h?.draft??null,R=h?.etag??null,$e=o.useMemo(()=>!i&&l?{baseActiveRevision:l.revision,authoring:ob(l)}:null,[i,l]),Ie=He??$e;async function Fe(_){const ae=++Ct.current;k(!0),S(null);try{let[de,le]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);if(!le.draft&&_&&i&&(await u.createDraft(t,de.activeRevision),[de,le]=await Promise.all([u.loadSetup(t),u.loadDraft(t)])),ae!==Ct.current)return;x(de),y(le),b(Hy(le.draft));const Te=Jr(le.draft);U(Te)}catch(de){if(ae!==Ct.current)return;S(os(de,"Could not load advanced measurement setup."))}finally{ae===Ct.current&&k(!1)}}o.useEffect(()=>(Fe(!0),()=>{Ct.current+=1}),[t,i,u]),o.useEffect(()=>{!j&&!He&&$e&&b("properties")},[He,j,$e]);async function dt(){const _=await u.loadDraft(t);return y(_),_}async function ze(_){pt(null);try{const[ae,de]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);x(ae),y(de);const le=Jr(de.draft);U(le),b(Te=>Wy(de.draft,Te)),v(_)}catch(ae){v(os(ae,_))}}async function yt(_,ae,de,le={}){const{preserveBusyAction:Te=!1}=le;if(!i||!R||Qe&&!Te)return null;Te||Je(_),v(null),pt(null);try{const Ue=await ae(R),mt=await dt();return T((Ue.warnings??[]).map((kt,vs)=>Zr(kt,vs,mt.draft?.authoring))),mt}catch(Ue){return fn(Ue)?await ze("This setup changed in another session. The latest draft is loaded; review your changes again."):v(os(Ue,de)),null}finally{Te||Je(null)}}const te=o.useMemo(()=>(Ie?.authoring.targets??[]).map(_=>{const ae=bl(_);return{id:_.stableKey,name:_.label,url:ae[0]??"No URL",urls:ae,state:Yy(_.status)}}),[Ie]),_e=o.useMemo(()=>Ie?.authoring.targets.filter(_=>_.status==="included")??[],[Ie]),Pe=o.useMemo(()=>_e.map(_=>({id:_.stableKey,label:_.label,urlCount:bl(_).length})),[_e]),ve=Ie?.authoring.assignments.length??0,Tt=o.useMemo(()=>{if(!Ie)return[];const _=new Set(s.map(le=>le.id)),ae=s.map(le=>({id:le.id,text:le.query,source:"saved-project-queries",propertyIds:Rs(Ie.authoring.assignments.filter(Te=>Te.queryId===le.id).map(Te=>Te.targetKey))})),de=Rs(Ie.authoring.assignments.map(le=>le.queryId).filter(le=>!_.has(le))).map(le=>({id:le,source:"unavailable-tracked-query",state:"missing",propertyIds:Rs(Ie.authoring.assignments.filter(Te=>Te.queryId===le).map(Te=>Te.targetKey))}));return[...ae,...de]},[s,Ie]),Xt=o.useMemo(()=>(Ie?.authoring.groups??[]).map(_=>({id:_.stableKey,name:_.label,propertyIds:_.targetKeys,competitors:_.competitors.map(ae=>ae.domain)})),[Ie]),Zt=o.useMemo(()=>{if(J.length===0)return null;const _=rb(X,Pe.map(de=>de.id),J);return(_.groupKeys?.length??_.targetKeys?.length??0)>0?_:null},[X,Pe,J]),Ot=Zt?JSON.stringify(Zt):"";o.useEffect(()=>{const _=Zt,ae=++It.current;if(!i||!He||!R||!_){ee(null),oe(null),he(null),Y(!1);return}ee(null),oe(null),he(null),Y(!0);const de=window.setTimeout(()=>{u.previewAssignments(t,_).then(le=>{if(ae===It.current){if(le.draftEtag!==R){ee(null),oe(null),he("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}ee(le),oe(Ot)}}).catch(le=>{ae===It.current&&(ee(null),oe(null),he(Uy(le)))}).finally(()=>{ae===It.current&&Y(!1)})},250);return()=>{window.clearTimeout(de),It.current+=1}},[Zt,Ot,Z,i,He,R,t,u]);const ut=o.useMemo(()=>[...ve===0?[{id:"no-query-assignments",title:"Assign at least one query",detail:"Apply a tracked query to at least one Property before publishing.",tone:"negative"}]:[],...Ie?.authoring.assignments.some(_=>_.queryClass==="unclassified")&&!($e&&l?.plan.schemaVersion===1)?[{id:"unclassified-query-assignments",title:"Remove an unavailable query",detail:"One or more saved assignments no longer have a tracked query. Clear them before publishing.",tone:"negative"}]:[],...C],[ve,$e,l,C,Ie]),es=n?{status:"unavailable",message:"Tracked queries are loading."}:a?{status:"unavailable",message:"Tracked queries could not be loaded. Retry before assigning Properties."}:{status:"available"};async function it(_){let ae;try{ae=zy(_)}catch(le){v(os(le,"Check the sitemap details and try again."));return}w(_),F("reviewing");const de=await yt("import",le=>u.importSitemap(t,le,ae),"Could not review this sitemap.");if(de?.draft){const le=de.draft.authoring.targets.filter(Ue=>Ue.status==="proposed").map(Ue=>Ue.stableKey),Te=de.draft.authoring.targets.filter(Ue=>Ue.status==="included").map(Ue=>Ue.stableKey);U([...Te,...le]),B(""),se(fl),b("properties"),F("idle")}else F("error")}async function gs(_){if(!c||_.length===0||Qe)return[];Je("create-queries"),ct(null);try{return await c(_)}catch(ae){throw ct(St(ae)),ae}finally{Je(null)}}async function ps(_){if(!He||!R||Qe)return;const ae=new Set(_),le=He.authoring.targets.filter(Ue=>Ue.status==="proposed"&&Ue.discoveryIdentity).map(Ue=>({discoveryIdentity:Ue.discoveryIdentity,action:ae.has(Ue.stableKey)?"create":"ignore"})),Te=le.length>0||He.authoring.targets.some(Ue=>Ue.status!=="proposed"&&Ue.status==="included"!==ae.has(Ue.stableKey));Je("properties"),v(null),pt(null);try{if(!Te){U([...ae]),L({kind:"all"}),b("groups");return}await u.applySitemapSelection(t,R,le,[...ae]);const Ue=await dt(),mt=Jr(Ue.draft);U(mt),L({kind:"all"}),b("groups")}catch(Ue){fn(Ue)?await ze("This setup changed in another session. The latest Properties are loaded."):v(os(Ue,"Could not save the selected Properties."))}finally{Je(null)}}async function Bs(_){const ae=_.groupIds&&_.groupIds.length>0?{groupKeys:Ys(_.groupIds),queryIds:Ys(_.queryIds)}:{targetKeys:Ys(_.propertyIds),queryIds:Ys(_.queryIds)};if(!D||ne!==JSON.stringify(ae)||!R||D.draftEtag!==R){v("Review the latest assignment impact before assigning queries.");return}await yt("assignments",le=>u.applyAssignments(t,le,ae),"Could not apply these queries.")&&(q([]),pe(`${D.assignments.added} new assignment${D.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function bt(_){if(_.propertyIds.length===0)return;await yt("replace-assignments",de=>u.replaceAssignments(t,de,{targetKeys:Rs(_.propertyIds),queryIds:[_.queryId]}),"Could not replace this query assignment.")&&(q(de=>de.filter(le=>le!==_.queryId)),pe("Query assignments replaced."))}async function Vs(_,ae=!1){if(_.length===0)return;if(!await yt("paired-assignments",le=>u.applyPairedAssignments(t,le,[..._]),"Could not assign these queries.",{preserveBusyAction:ae}))throw new Error("Could not assign these queries.")}async function Mt(_){if(!(!i||!c||_.length===0||Qe)){Je("create-and-pair-questions"),ct(null);try{let ae;try{ae=await c(Rs(_.map(Te=>Te.text)))}catch(Te){throw ct(St(Te)),Te}const de=new Map(ae.map(Te=>[Te.query,Te.id])),le=_.map(Te=>({targetKey:Te.propertyId,queryId:de.get(Te.text)})).filter(Te=>Te.queryId!==void 0);if(le.length!==_.length){const Te=new Error("The created queries could not be matched to their Properties.");throw ct("The queries were added, but could not be paired with every Property. Try again to pair them."),Te}try{await Vs(le,!0)}catch(Te){throw ct("The queries were added, but could not be assigned to their Properties. Try again to pair them."),Te}}finally{Je(null)}}}async function as(_){if(!He)return;const ae=Rs(He.authoring.assignments.filter(le=>le.queryId===_).map(le=>le.targetKey));if(ae.length===0)return;await yt(`remove-${_}`,le=>u.removeAssignment(t,le,ae,_),"Could not clear this query assignment.")&&q(le=>le.filter(Te=>Te!==_))}async function Vt(_){if(!He||!R||Qe)return;const ae=_.name.trim();if(!ae)return;const de=re??Ni(ae,"group"),le=He.authoring.groups.find(kt=>kt.stableKey===de);if(le&&re===null){v(`A group named "${le.label}" already exists. Edit it or choose a different name.`);return}const Te=_.competitorDomains.split(/[\s,]+/).map(kt=>kt.trim()).filter(Boolean),Ue=Te.find(kt=>vl(kt)===null);if(Ue){v(`"${Ue}" is not a valid competitor domain.`);return}const mt=Rs(Te.map(kt=>vl(kt)));Je("group"),v(null),pt(null);try{const kt=await u.upsertGroup(t,R,{stableKey:de,label:ae,targetKeys:Rs(_.propertyIds),competitors:mt.map(E=>le?.competitors.find(Se=>Se.domain===E)??{stableKey:Ni(E,"competitor"),label:E,domain:E,aliases:[]})}),vs=await dt();T(kt.warnings.map((E,Se)=>Zr(E,Se,vs.draft?.authoring))),Re({...oa}),xe(null)}catch(kt){fn(kt)?await ze("This setup changed in another session. The latest groups are loaded."):v(os(kt,"Could not save this group."))}finally{Je(null)}}function xt(_){const ae=He?.authoring.groups.find(de=>de.stableKey===_);ae&&(xe(_),Re({name:ae.label,propertyIds:[...ae.targetKeys],competitorDomains:ae.competitors.map(de=>de.domain).join(", ")}))}async function ts(_){await yt("remove-group",de=>u.removeGroup(t,de,_),"Could not remove this group.")&&(L(de=>de.kind==="groups"&&de.groupIds.includes(_)?{kind:"all"}:de),re===_&&(xe(null),Re({...oa})))}function Qt(_){et(_),O(null),Ge(null),vt(null)}async function fs(){if(!(!i||!Ae.trim()||ke||be)){A(!0),Ge(null),vt(null);try{O(await u.previewGroupMembership(t,{csv:Ae}))}catch(_){O(null),Ge(os(_,"Could not review this CSV."))}finally{A(!1)}}}async function zt(_){if(!(!i||!R||!Le||_.length===0||Qe)){if(Le.draftEtag!==R){Ge("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}Ke(!0),Je("group-import"),Ge(null),vt(null),pt(null);try{const ae=await u.applyGroupMembership(t,R,{csv:Ae,sourceChecksum:Le.sourceChecksum,previewChecksum:Le.previewChecksum,acceptedRows:Rs(_.map(String)).map(Number)}),de=await dt();T(ae.warnings.map((le,Te)=>Zr(le,Te,de.draft?.authoring))),et(""),O(null),vt(`${ae.addedMemberships} membership${ae.addedMemberships===1?"":"s"} added${ae.unchangedMemberships>0?`; ${ae.unchangedMemberships} already present`:""}.`)}catch(ae){fn(ae)?(await ze("This setup changed in another session. The latest draft is loaded; review the CSV again."),Ge("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Ge(os(ae,"Could not apply this CSV."))}finally{Je(null),Ke(!1)}}}async function gt(){if(!(!He||!R||Qe||ve===0)){Je("review"),v(null),pt(null);try{const[_,ae]=await Promise.all([u.compilePreview(t),u.diffPreview(t)]),de=[..._.checks,...ae.checks],le=de.some(Te=>Te.ruleId==="active-revision-schema-v1");if(T(nb(de.filter(Te=>Te.ruleId!=="active-revision-schema-v1"),{authoring:Ie?.authoring,queries:s})),!_.ok||!ae.ok)return;if(ae.diff.activeRevision!==He.baseActiveRevision){await ze("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(_.compiledChecksum!==ae.compiledChecksum){v("The setup changed while it was being reviewed. Review the latest changes again.");return}pt({etag:R,baseActiveRevision:He.baseActiveRevision,compiledChecksum:_.compiledChecksum,changes:ab(ae.diff,le),providerCalls:_.plan.executionNodes.reduce((Te,Ue)=>Te+Ue.expectedSnapshots,0)})}catch(_){v(os(_,"Could not review this setup."))}finally{Je(null)}}}async function Lt(){if(!(!He||!R||!at||Qe)){if(R!==at.etag||He.baseActiveRevision!==at.baseActiveRevision){pt(null),v("The setup changed after review. Review the latest changes before publishing.");return}Je("publish"),v(null);try{await u.publish(t,R,{expectedActiveRevision:at.baseActiveRevision,expectedCompiledChecksum:at.compiledChecksum}),y({draft:null,etag:null}),pt(null),m?.()}catch(_){fn(_)?await ze("The setup changed before it could be published. Review the latest draft and publish again."):v(os(_,"Could not publish this setup."))}finally{Je(null)}}}async function Nt(){if(!(!R||Qe)){Je("discard"),v(null);try{await u.discard(t,R),y({draft:null,etag:null}),pt(null),m?.()}catch(_){fn(_)?await ze("This setup changed in another session. The latest draft is loaded."):v(os(_,"Could not discard these changes."))}finally{Je(null)}}}async function ys(){if(!(!He||!R||!p||Qe)){Je("restart"),v(null),pt(null);try{await u.discard(t,R),await u.createDraft(t,p.activeRevision),w({...gl}),B(""),U([]),q([]),L({kind:"all"}),ee(null),he(null),pe(null),Re({...oa}),xe(null),et(""),O(null),Ge(null),vt(null),await Fe(!1)}catch(_){fn(_)?await ze("The setup changed again. Reloaded the latest draft and published setup."):v(os(_,"Could not restart this setup."))}finally{Je(null)}}}if(j)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-loading-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-loading-title",children:"Advanced measurement setup"})}),e.jsx("div",{className:"h-28 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement setup"})]});if($)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-error-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-error-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:$}),e.jsx(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Fe(!0)},children:"Try again"})]})]});if(!Ie||i&&!R)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-empty-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-empty-title",children:"Advanced measurement setup"})}),e.jsx("p",{className:"text-sm text-secondary",children:i?"Start setup from the project Overview.":"No advanced setup is available to review."})]});if(i&&He&&p&&He.baseActiveRevision!==p.activeRevision)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-stale-draft-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-stale-draft-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"This draft is based on an older published setup."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Restart from the latest setup before making more changes."}),e.jsx(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:Qe==="restart",onClick:()=>{ys()},children:Qe==="restart"?"Restarting…":"Discard draft and restart"})]}),g?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:g}):null]});const bs=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:r,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[p?.mode==="active-v1"?e.jsx("p",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-3 text-sm text-secondary",children:"Review and publish this setup to enable class-filtered reporting."}):null,g?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:g}):null,bs,f==="import"||f==="properties"?e.jsx(Xa,{currentStep:f,hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},importProperties:{importDraft:I,onImportDraftChange:_=>{w(_),F("idle"),v(null)},onReviewSitemap:_=>{it(_)},reviewState:V,properties:te,propertiesState:"ready",propertiesSearch:z,onPropertiesSearchChange:B,maxVisibleProperties:Q,onShowAllProperties:()=>se(te.length),selectedPropertyIds:K,onSelectedPropertyIdsChange:_=>U([..._]),onContinue:_=>{ps(_)},isContinuing:Qe==="properties",onRetryProperties:()=>{dt()},onReturnToImport:()=>b("import")}}):f==="queries"?e.jsx(Xa,{currentStep:"queries",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},onManageProjectQueries:d,queries:{onCreateQueries:c?_=>gs(_):void 0,isCreatingQueries:Qe==="create-queries"||Qe==="create-and-pair-questions",isBusy:Qe!==null,createQueriesError:Dt,availability:es,properties:Pe,queries:Tt,selectedQueryIds:J,isApplying:Qe==="assignments"||Qe==="paired-assignments",onSelectedQueryIdsChange:_=>q([..._]),onApplySelectedQueries:_=>Bs(_),groups:Xt,audience:X,onAudienceChange:_=>{L(_),pe(null)},assignmentImpact:D&&ne===Ot&&D.draftEtag===R?ib(D):null,isPreviewingAssignmentImpact:we,assignmentImpactError:ue,onRetryAssignmentImpact:()=>me(_=>_+1),assignmentNotice:G,onReplaceAssignments:bt,isReplacingAssignments:Qe==="replace-assignments",onCreateAndPairQuestions:i&&c?Mt:void 0,onClearQueryAssignments:as,onRemoveQuery:as,canContinue:ve>0,onBack:()=>b("groups"),onContinue:()=>b("review")}}):f==="groups"?e.jsx(Xa,{currentStep:"groups",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},groups:{properties:Pe,groups:Xt,groupDraft:Ee,isSaving:Qe==="group",onGroupDraftChange:Re,onSaveGroup:Vt,onEditGroup:_=>xt(_.id),onRemoveGroup:ts,onClearGroupDraft:()=>{xe(null),Re({...oa})},membershipImport:{csv:Ae,preview:Le,isReviewing:ke,isApplying:be,error:Ve,notice:ge,onCsvChange:Qt,onReview:fs,onApply:zt},onBack:()=>{b("properties")},onContinue:()=>b("queries")}}):e.jsx(Xa,{currentStep:"review",hasDraft:He!==null,canEdit:i,onStepChange:i?void 0:b,onDiscard:()=>{Nt()},review:{counts:{properties:_e.length,queries:new Set(Ie.authoring.assignments.map(_=>_.queryId)).size,groups:Ie.authoring.groups.length,assignments:Ie.authoring.assignments.length,providerCalls:at?.providerCalls},flaggedExceptions:ut,reviewedChanges:at?.changes,isReviewing:Qe==="review",canReviewChanges:ve>0&&!Qe,onReviewChanges:gt,onBack:()=>b("queries"),canPublish:at!==null&&!Qe,isPublishing:Qe==="publish",onPublish:Lt}})]})}const cb=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function wl(t){return t.label!=="Complete"}const yn="__all_properties__",db=50,ed=50,ub=20,mb=50,hb=250,pb=5,xb=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],gb={"this-property":"Matches this Property","another-property":"Matches another Property","owned-unassigned":"Site URL not included in a Property",external:"External URL","multiple-properties":"Matches multiple Properties","invalid-url":"Invalid URL"},td={plan_v1:"Setup update required.",no_completed_run:"Not measured yet.",no_population:"No matching queries.",evidence_incomplete:"Evidence incomplete.",identity_ambiguous:`${oo}.`,"identity-ambiguous":`${oo}.`,not_applicable:"Not applicable.",incomplete:"The latest measurement is incomplete.","evidence-incomplete":"Some source evidence is incomplete.","no-population":"No measurements are available for this selection.",unavailable:"This measurement is unavailable."},fb={numerator:null,denominator:null,reason:"plan_v1"};function Kn(t){return t.numerator===null?!1:Number.isFinite(t.numerator)&&Number.isFinite(t.denominator)&&t.numerator>=0&&t.denominator>0&&t.numerator<=t.denominator}function yb(t){return Kn(t)?`${t.numerator} of ${t.denominator} (${tt(t.numerator/t.denominator)})`:"N/A"}function sd(t){if(Kn(t))return"";const s=t.reason??"unavailable";return td[s]??s}function Sl(t){const s=[];return t.market&&s.push(t.market),t.urls.length>0&&s.push(`${t.urls.length} ${t.urls.length===1?"URL":"URLs"}`),s.join(" · ")}function bb(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function vb(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function jb(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function ma({metric:t,signal:s,compact:n=!1}){const a=n?Kn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Kn(t)?"text-lg font-semibold text-heading":"text-lg font-semibold text-secondary",r=Kn(t)?Pi(t,s):null;return e.jsxs("span",{className:"inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums",...Kn(t)?{}:{title:sd(t)},children:[e.jsx("span",{className:a,children:yb(t)}),r?e.jsx("span",{className:"text-xs text-secondary",children:r}):null]})}function Wi({shown:t,total:s,onShowAll:n,itemLabel:a}){return t>=s?null:e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",t," of ",s]}),e.jsxs(P,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Cl({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,l]=o.useState(ed),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((c,d)=>e.jsx("li",{className:a,children:c},`${c}:${d}`))}),e.jsx(Wi,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>l(Number.MAX_SAFE_INTEGER)})]})]})}function Nb({evidence:t,state:s="ready",onRetry:n}){const[a,r]=o.useState(ed),l=t.slice(0,a);return e.jsxs("section",{"aria-label":"Evidence",children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:"Evidence"}),s==="loading"?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Loading evidence…"}):s==="error"?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsx("span",{children:"Evidence could not be loaded."}),n?e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:n,children:"Retry evidence"}):null]}):t.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"No source evidence is available."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[640px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children:l.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(Ne,{tone:i.tone,children:gb[i.kind]}),i.historical?e.jsx(Ne,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:i.query}),i.provider||i.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[i.provider,i.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:i.url})]},i.id))})]})}),e.jsx(Wi,{shown:l.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function wb({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Cl,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Cl,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(Nb,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function Sb({values:t}){return e.jsxs("section",{"aria-labelledby":"advanced-measurement-share-of-voice",className:"border-y border-default py-4",children:[e.jsx("h2",{id:"advanced-measurement-share-of-voice",className:"text-sm font-medium text-heading",children:"Brand share of voice"}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[420px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Name"}),e.jsx("th",{children:"Share of voice"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.name}),e.jsx("td",{className:"text-secondary",children:e.jsx(ma,{metric:s.coverage,signal:"mentioned",compact:!0})})]},s.name))})]})})]})}function kl({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function l(i){if(r)return;const c=n.findIndex(u=>u.value===s);let d=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?d=(c+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?d=(c-1+n.length)%n.length:i.key==="Home"?d=0:i.key==="End"&&(d=n.length-1),d===null)return;i.preventDefault();const m=n[d];a(m.value),i.currentTarget.querySelectorAll('[role="radio"]')[d].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:l,children:n.map(i=>{const c=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":c,tabIndex:c?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${c?"segmented-option-active":""}`,children:i.label},i.value)})})}function Cb({outcomes:t}){const s=[{key:"both",count:t.bothSignals,label:"mentioned and cited",tone:"text-primary"},{key:"mentioned-only",count:t.mentionedOnly,label:"mentioned only",tone:"text-primary"},{key:"cited-only",count:t.citedOnly,label:"cited only",tone:"text-primary"},{key:"neither",count:t.neither,label:"neither signal",tone:"text-negative"},...t.notMeasured>0?[{key:"not-measured",count:t.notMeasured,label:"not measured",tone:"text-faint"}]:[]];return e.jsx("div",{"aria-label":"Property outcomes",className:"flex flex-wrap gap-x-8 gap-y-3 py-3",children:s.map(n=>e.jsxs("div",{className:"whitespace-nowrap",children:[e.jsx("p",{className:`font-mono text-xl font-semibold leading-none tabular-nums ${n.tone}`,children:n.count}),e.jsxs("p",{className:"mt-1 text-[13px] text-secondary",children:[n.label,n.key==="not-measured"?e.jsx(Oe,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function kb({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:l=!1,isViewLoading:i=!1,isLoadingMore:c=!1,isLoadMoreError:d=!1,viewSearch:m,onViewChange:u,onLoadMore:p,onPropertyExpand:x,onRetryEvidence:h,renderPropertyLink:y}){const f=t.currentView!=null,b=t.classReporting==="available"&&(f||t.classScopes!=null),[j,k]=o.useState(t.currentView?.queryClass??"all"),[$,S]=o.useState(t.currentView?.scope.key??yn),[g,v]=o.useState(m??""),[C,T]=o.useState(db),[I,w]=o.useState(ub),[V,F]=o.useState(t.currentView?.sort??"label-asc"),[z,B]=o.useState(null),Q=o.useRef(m??""),se=b&&!f&&j!=="all"?j==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,K=f?{aggregate:t.currentView.aggregate,groups:[]}:se,U=o.useCallback(O=>{if(!f||!u)return;const ke=O.scope??($===yn?"all":"group"),A=O.search??g;Q.current=A,u({scope:ke,...ke==="group"?{groupKey:O.groupKey??$}:{},queryClass:O.queryClass??j,...A?{search:A}:{},...O.sort?{sort:O.sort}:{}})},[u,g,j,$,f]);o.useEffect(()=>{!t.currentView||i||(k(t.currentView.queryClass),S(t.currentView.scope.key??yn),t.currentView.sort&&F(t.currentView.sort))},[i,t.currentView]),o.useEffect(()=>{m!==void 0&&(Q.current=m,v(O=>O.trim()===m.trim()?O:m))},[m]),o.useEffect(()=>{if(!f||!u||g===Q.current)return;const O=window.setTimeout(()=>U({search:g}),hb);return()=>window.clearTimeout(O)},[u,U,g,f]);const J=t.availableGroups??K.groups;o.useEffect(()=>{$===yn||J.some(O=>O.id===$)||S(yn)},[J,$]);const q=f?void 0:K.groups.find(O=>O.id===$),X=q?.aggregate??K.aggregate,L=O=>b?O:fb,D=V,ee=g.trim().toLocaleLowerCase(),ne=o.useMemo(()=>!f&&ee?X.properties.filter(O=>O.name.toLocaleLowerCase().includes(ee)):X.properties,[X.properties,ee,f]),oe=f?ne:ne.slice(0,C),we=(f?t.currentView?.scope.kind==="group":q!=null)&&j==="non-brand"&&b&&(f||q.confirmedCompetitorCount>0)&&(X.shareOfVoice?.length??0)>0,Y=b?X.unavailablePropertyCount??0:0,ue=t.flaggedResults.reduce((O,ke)=>O+(ke.count??1),0),he=t.flaggedResultsTotal??ue,Z=[L(X.metrics.propertiesMentioned),L(X.metrics.mentionCoverage),L(X.metrics.citationCoverage)].map(sd).find(Boolean),me=b?t.nextActionText??Z??(Y>0?`${Y} ${Y===1?"property is":"properties are"} unavailable.`:he>0?`${he} flagged ${he===1?"result needs":"results need"} review.`:null):td.plan_v1,Ee=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?bb(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Re=vb(t.latestMeasurement.date),re=[{value:yn,label:"All properties"},...J.map(O=>({value:O.id,label:O.label}))],xe=J.length>pb;function Ae(O){S(O),U(O===yn?{scope:"all"}:{scope:"group",groupKey:O})}function et(O){k(O),U({queryClass:O})}function Le(O){const ke=z!==O;B(ke?O:null),ke&&x?.(O)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":i,className:"space-y-5",children:[e.jsx("header",{className:"border-b border-default pb-4",children:e.jsx("div",{role:"status","aria-label":"Measurement status and next action",className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:i?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(Ne,{tone:"caution",children:"Includes historical data"}):null,Ee?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:Ee}):null,Re?e.jsx("span",{className:"text-sm text-secondary",children:Re}):null,me?e.jsx("span",{className:"text-sm text-secondary",children:me}):null,s&&b&&n?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!b?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||l,children:l?"Opening setup…":"Republish setup"}):null]})})}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4 border-b border-default pb-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-group-label",htmlFor:xe?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),xe?e.jsx("select",{id:"advanced-measurement-group",value:$,onChange:O=>Ae(O.target.value),className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-mono-400",children:re.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))}):e.jsx(kl,{ariaLabelledBy:"advanced-measurement-group-label",value:$,options:re,onChange:Ae})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-class-label",className:"block text-sm font-medium text-heading",children:"Query type"}),e.jsx(kl,{ariaLabelledBy:"advanced-measurement-class-label",value:j,options:xb,onChange:et,disabled:!b})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:g,onChange:O=>v(O.target.value),placeholder:"Search properties",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]})]}),!i&&we?e.jsx(Sb,{values:X.shareOfVoice??[]}):null,i?e.jsx("div",{className:"h-44 animate-pulse rounded-md bg-surface-subtle","aria-label":"Updating Property results"}):e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-title",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{id:"advanced-measurement-properties-title",className:"text-base font-semibold text-heading",children:["Properties",e.jsx(Oe,{text:"Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other."})]}),e.jsxs("span",{className:"text-sm text-secondary",children:[t.currentView?.propertyTotal??ne.length," ",(t.currentView?.propertyTotal??ne.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(Cb,{outcomes:t.currentView.outcomes}):null,e.jsx("div",{className:"overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("caption",{className:"sr-only",children:"Property measurement results"}),e.jsx("thead",{children:e.jsxs("tr",{children:[cb.map(O=>{const ke=D.startsWith(`${O.key}-`),A=ke&&D.endsWith("-desc")?"descending":ke?"ascending":"none";return e.jsx("th",{"aria-sort":A,className:(O.numeric,void 0),children:u?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const be=`${O.key}-${ke&&D.endsWith("-asc")?"desc":"asc"}`;F(be),U({sort:be})},"aria-label":`Sort by ${O.label.toLowerCase()}`,children:[O.label,e.jsx(zn,{className:`h-3 w-3 transition-transform ${ke?"opacity-100":"opacity-0"} ${A==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):O.label},O.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[oe.map(O=>{const ke=z===O.id;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:A=>{jb(A.target)||Le(O.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[y?y({id:O.id,name:O.name}):O.name,wl(O.status)||O.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[wl(O.status)?e.jsx(Ne,{tone:O.status.tone,children:O.status.label}):null,O.historical?e.jsx(Ne,{tone:"caution",children:"Historical"}):null]}):null,Sl(O)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Sl(O)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(ma,{metric:O.mentionCoverage,signal:"mentioned",compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(ma,{metric:O.citationCoverage,signal:"cited",compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{size:"icon",variant:"ghost","aria-expanded":ke,"aria-label":ke?`Hide details for ${O.name}`:`Show details for ${O.name}`,onClick:()=>Le(O.id),children:e.jsx(zn,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${ke?"rotate-180":""}`,"aria-hidden":"true"})})})]},O.id),ke?(O.providers??[]).map(A=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:A.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(ma,{metric:A.mentionCoverage,signal:"mentioned",compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(ma,{metric:A.citationCoverage,signal:"cited",compact:!0})}),e.jsx("td",{})]},`${O.id}:${A.provider}`)):null,ke?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(wb,{property:O,onRetryEvidence:h})})},`${O.id}:details`):null]},O.id)}),oe.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"py-8 text-center text-sm text-secondary",children:"No properties match this search."})}):null]})]})}),f&&t.currentView.nextCursor&&p?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",oe.length," of ",t.currentView.propertyTotal]}),d?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(P,{size:"sm",variant:"outline",disabled:c,onClick:()=>p(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more properties":"Show 50 more"})]}):f?oe.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",oe.length," of ",t.currentView.propertyTotal]}):null:e.jsx(Wi,{shown:oe.length,total:ne.length,itemLabel:"properties",onShowAll:()=>T(Number.MAX_SAFE_INTEGER)})]}),!i&&!ee&&he>0?e.jsx("section",{"aria-label":"Flagged results",className:"border-t border-default pt-4",children:e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:["Flagged results (",he,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,I).map(O=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(Ne,{tone:O.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:O.property}),e.jsx("span",{className:"text-secondary",children:O.summary})]},O.id))}),I<t.flaggedResults.length?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",t.flaggedResults.slice(0,I).reduce((O,ke)=>O+(ke.count??1),0)," of ",he," flagged results"]}),e.jsx(P,{size:"sm",variant:"outline",onClick:()=>w(O=>Math.min(t.flaggedResults.length,O+mb)),children:"Show 50 more"})]}):ue<he?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",ue," of ",he," flagged results"]}),f&&t.currentView.nextCursor&&p?e.jsx(P,{size:"sm",variant:"outline",disabled:c,onClick:()=>p(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function nd(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function Ab(t){return t.activePlanSchemaVersion===null?{surface:"simple-overview",setupAction:t.hasDraft?"continue":"set-up"}:t.activePlanSchemaVersion<2?{surface:"advanced-overview-v1",setupAction:"republish"}:{surface:"advanced-overview",setupAction:t.hasDraft?"continue":"edit"}}function Rb({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:l,onRunMeasurement:i,onRetryReport:c,onViewChange:d,onLoadMore:m,onPropertyExpand:u,onRetryEvidence:p,renderPropertyLink:x,isRunningMeasurement:h,isOpeningSetup:y,isViewLoading:f,isLoadingMore:b,isLoadMoreError:j,viewSearch:k}){return t.surface==="simple-overview"?n:e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&l?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",disabled:y,onClick:l,children:y?"Opening setup…":nd(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,r==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):r==="error"&&!a?e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load the advanced measurement report."}),c?e.jsx(P,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:c,children:"Retry report"}):null]}):a?e.jsx(kb,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:l,onViewChange:d,onLoadMore:m,onPropertyExpand:u,onRetryEvidence:p,renderPropertyLink:x,isRunningMeasurement:h,isRepublishingSetup:y,isViewLoading:f,isLoadingMore:b,isLoadMoreError:j,viewSearch:k}):e.jsx("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-secondary",children:"No advanced measurement report is available yet."})]})}const Dn={numerator:null,denominator:null,reason:"plan_v1"};function Pb(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Al(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator,...t.unattributed===void 0?{}:{unattributed:t.unattributed},...t.unchecked===void 0?{}:{unchecked:t.unchecked}}}function Ib(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function Tb(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Mb(t){if(!t)return"Date unavailable";const s=new Date(t);return Number.isFinite(s.getTime())?s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}):"Date unavailable"}function Lb(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function $b(t){const s=new Map;for(const n of t){const a=Lb(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function qb(t,s){if(t.plan.schemaVersion!==1)throw new Error("Version-one report adapter received a different setup version.");const n=t.plan,a=new Map(n.targets.map(y=>[y.stableKey,y])),r=new Map(n.querySnapshots.map(y=>[y.queryId,y.queryText])),l=new Map;for(const y of n.targetQuerySelections){const f=l.get(y.targetKey)??[];f.push(...y.queryIds.map(b=>r.get(b)).filter(b=>!!b)),l.set(y.targetKey,[...new Set(f)])}const i=$b(s.evidence),c=n.executionNodes.reduce((y,f)=>y+f.expectedSnapshots,0),d=s.run?.status==="completed"&&c>0,m=d?c:0,u=d?c:0,p=s.targets.map(y=>{const f=a.get(y.id),b=i.get(y.id)??[],j=b.map(S=>({id:`${S.observationId}:${S.usageEdgeId}:${S.sourceUrl}`,kind:Ib(S.classification),query:S.queryText,url:S.sourceUrl,tone:Tb(S.classification),historical:S.historical||S.bridged})),k=b.some(S=>S.historical||S.bridged),$=s.run?y.completeness.complete?f?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${y.completeness.executed} of ${y.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:y.id,name:y.label,mentionCoverage:Al(y.mentionCoverage),citationCoverage:Al(y.citationCoverage),status:$,assignedQueries:l.get(y.id)??[],urls:f?.urls.map(Pb)??[],evidence:j,historical:k}}),x=new Map(p.map(y=>[y.id,y])),h=new Map(n.groups.map(y=>[y.stableKey,y]));return{classReporting:"plan-v1",latestMeasurement:{status:s.run?.status==="completed"?{label:"Complete",tone:"positive"}:s.run?.status==="partial"?{label:"Partial result",tone:"caution"}:{label:"Not measured",tone:"neutral"},completedSlots:m,totalSlots:u,date:Mb(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Dn,mentionCoverage:Dn,citationCoverage:Dn},properties:p},groups:s.groups.map(y=>({id:y.id,label:y.label,confirmedCompetitorCount:h.get(y.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Dn,mentionCoverage:Dn,citationCoverage:Dn},properties:y.targetIds.map(f=>x.get(f)).filter(f=>!!f)}}))},flaggedResults:[]}}function Eb({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=o.useState(!1),[l,i]=o.useState(!1),[c,d]=o.useState(null),[m,u]=o.useState(t.displayName),[p,x]=o.useState(t.canonicalDomain),[h,y]=o.useState(t.country),[f,b]=o.useState(t.language),[j,k]=o.useState(t.ownedDomains??[]),[$,S]=o.useState(""),[g,v]=o.useState(t.aliases??[]),[C,T]=o.useState(""),[I,w]=o.useState(null),[V,F]=o.useState(!1),[z,B]=o.useState(!1),[Q,se]=o.useState(""),[K,U]=o.useState(""),[J,q]=o.useState(""),[X,L]=o.useState(""),[D,ee]=o.useState(""),[ne,oe]=o.useState(null),[we,Y]=o.useState(null);o.useEffect(()=>{a||(u(t.displayName),x(t.canonicalDomain),y(t.country),b(t.language),k(t.ownedDomains??[]),v(t.aliases??[]))},[t,a]);function ue(){r(!1),d(null),u(t.displayName),x(t.canonicalDomain),y(t.country),b(t.language),k(t.ownedDomains??[]),v(t.aliases??[]),S(""),T("")}function he(){const A=$.trim();A&&(j.includes(A)||k([...j,A]),S(""))}function Z(A){k(j.filter(be=>be!==A))}function me(){const A=C.trim();if(!A)return;const be=A.toLowerCase();g.some(Ke=>Ke.toLowerCase()===be)||v([...g,A]),T("")}function G(A){v(g.filter(be=>be!==A))}async function pe(){if(!(!m.trim()||!p.trim()||!h.trim()||!f.trim())){i(!0),d(null);try{await s(t.name,{displayName:m.trim(),canonicalDomain:p.trim(),ownedDomains:j,aliases:g,country:h.trim(),language:f.trim()}),r(!1),De({title:"Project settings saved",detail:`${m.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(A){d(A instanceof Error?A.message:"Failed to save")}finally{i(!1)}}}async function Ee(){const A=Q.trim(),be=K.trim(),Ke=J.trim(),Ve=X.trim();if(!(!A||!be||!Ke||!Ve)){F(!0),w(null);try{const Ge={label:A,city:be,region:Ke,country:Ve};D.trim()&&(Ge.timezone=D.trim()),await vm(t.name,Ge),n(),se(""),U(""),q(""),L(""),ee(""),B(!1),De({title:"Location added",detail:`${A} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${A}`,dedupeMode:"drop"})}catch(Ge){w(Ge instanceof Error?Ge.message:"Failed to add location")}finally{F(!1)}}}async function Re(A){F(!0),w(null);try{await bm(t.name,A),n(),De({title:"Location removed",detail:`${A} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${A}`,dedupeMode:"drop"})}catch(be){w(be instanceof Error?be.message:"Failed to remove location")}finally{F(!1)}}async function re(A){F(!0),w(null);try{await ym(t.name,A),n(),De({title:"Default location updated",detail:`${A} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(be){w(be instanceof Error?be.message:"Failed to set default location")}finally{F(!1)}}async function xe(A){oe(A),Y(null);try{await jm(t.name,A),De({title:`${A.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(be){Y(be instanceof Error?be.message:"Could not download tracking results.")}finally{oe(null)}}const Ae=m!==t.displayName||p!==t.canonicalDomain||h!==t.country||f!==t.language||JSON.stringify(j)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(g)!==JSON.stringify(t.aliases??[]),et=!ie()&&!Ls(),Le="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",O="mb-1 block text-sm font-medium text-secondary",ke=Q.trim()&&K.trim()&&J.trim()&&X.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),et&&!a&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),c&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[c,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>d(null),children:"×"})]}),et&&a?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:O,children:"Display name"}),e.jsx("input",{className:Le,type:"text",value:m,onChange:A=>u(A.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:O,children:"Canonical domain"}),e.jsx("input",{className:Le,type:"text",value:p,onChange:A=>x(A.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:O,children:"Country"}),e.jsx("input",{className:Le,type:"text",value:h,onChange:A=>y(A.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:O,children:"Language"}),e.jsx("input",{className:Le,type:"text",value:f,onChange:A=>b(A.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:O,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:j.map(A=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[A,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Z(A),"aria-label":`Remove ${A}`,children:"×"})]},A))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Le} flex-1`,type:"text",placeholder:"docs.example.com",value:$,onChange:A=>S(A.target.value),onKeyDown:A=>A.key==="Enter"&&(A.preventDefault(),he())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!$.trim(),onClick:he,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:O,children:"Aliases"}),e.jsx("p",{className:"mb-1.5 text-sm text-secondary",children:"Other brand names that may appear in answers."}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:g.map(A=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[A,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>G(A),"aria-label":`Remove ${A}`,children:"×"})]},A))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Le} flex-1`,type:"text",placeholder:"Facebook",value:C,onChange:A=>T(A.target.value),onKeyDown:A=>A.key==="Enter"&&(A.preventDefault(),me())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!C.trim(),onClick:me,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(P,{type:"button",disabled:l||!Ae||!m.trim()||!p.trim(),onClick:Ze(pe),children:l?"Saving...":"Save changes"}),e.jsx(P,{type:"button",variant:"outline",disabled:l,onClick:ue,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-default bg-surface overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(A=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:A},A))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Aliases"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.aliases??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.aliases.map(A=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:A},A))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.country})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.language})]}),t.tags?.length?e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Tags"}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map(A=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:A},A))})})]}):null,e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[I&&e.jsxs("div",{className:"mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-xs text-negative",children:[I,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>w(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-faint",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(A=>e.jsxs("tr",{className:"border-t border-mono-800/30",children:[e.jsx("td",{className:"py-1.5 pr-3",children:e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium ${A.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[A.label,A.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:A.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:A.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:A.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:A.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[et&&A.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:V,onClick:()=>{re(A.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${A.label} as default location`,children:"Set default"}),et&&e.jsx("button",{type:"button",disabled:V,onClick:()=>{Re(A.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${A.label}`,children:"Remove"})]})})]},A.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),et?z?e.jsxs("div",{className:"mt-2 rounded border border-base bg-bg-elevated/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-secondary",children:"Add location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Label *"}),e.jsx("input",{className:Le,type:"text",value:Q,onChange:A=>se(A.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"City *"}),e.jsx("input",{className:Le,type:"text",value:K,onChange:A=>U(A.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Region *"}),e.jsx("input",{className:Le,type:"text",value:J,onChange:A=>q(A.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Country *"}),e.jsx("input",{className:Le,type:"text",value:X,onChange:A=>L(A.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Timezone (optional)"}),e.jsx("input",{className:Le,type:"text",value:D,onChange:A=>ee(A.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(P,{type:"button",size:"sm",disabled:V||!ke,onClick:Ze(Ee),children:V?"Adding...":"Add location"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:V,onClick:()=>{B(!1),w(null)},children:"Cancel"})]})]}):e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>B(!0),children:"+ Add location"}):null]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted",children:"Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"max-w-xl text-xs leading-5 text-muted",children:"Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ne!==null,onClick:Ze(()=>xe("csv")),children:ne==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ne!==null,onClick:Ze(()=>xe("json")),children:ne==="json"?"Preparing JSON...":"Download JSON"})]})]}),we&&e.jsx("p",{className:"mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:we})]})]})]})}function la(t){return{...t??{}}}function Db(t,s){const n=Object.entries(t).sort(([r],[l])=>r.localeCompare(l)),a=Object.entries(s).sort(([r],[l])=>r.localeCompare(l));return n.length===a.length&&n.every(([r,l],i)=>{const c=a[i];return c?.[0]===r&&c[1]===l})}function Ob({project:t,onSave:s}){const{isAdmin:n}=nn(),a=qe({queryKey:["settings"],queryFn:Kl,staleTime:6e4,enabled:n&&!ie()}),[r,l]=o.useState(t.providers.length===0),[i,c]=o.useState(t.providers),[d,m]=o.useState(()=>la(t.providerModels)),[u,p]=o.useState({providers:t.providers,providerModels:la(t.providerModels)}),[x,h]=o.useState(!1),[y,f]=o.useState(!1),[b,j]=o.useState(null),[k,$]=o.useState(null),S=o.useRef(null),g=a.data?.providerCatalog??[],v=o.useMemo(()=>new Set((a.data?.providers??[]).filter(B=>B.configured).map(B=>B.name)),[a.data]),C=o.useMemo(()=>{const B=new Map(a.data?.providers.map(se=>[se.name,se.model])),Q=new Map(g.map(se=>[se.name,{...se,defaultModel:B.get(se.name)||se.defaultModel}]));for(const se of Object.keys(d))Q.has(se)||Q.set(se,{name:se,displayName:se,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...Q.values()].sort((se,K)=>se.displayName.localeCompare(K.displayName))},[g,d,a.data?.providers]),T=!Db(d,u.providerModels);o.useEffect(()=>{if(x||y)return;const B={providers:t.providers,providerModels:la(t.providerModels)};p(B),l(B.providers.length===0),c(B.providers),m(B.providerModels)},[t]);function I(){f(!0),l(!1),i.length===0&&c([...v])}function w(B,Q,se=!1){f(!0),m(K=>{const U={...K};return Q==="__inherit__"?delete U[B]:Q==="__custom__"?U[B]=se?"":U[B]??"":U[B]=Q,U}),Q==="__custom__"&&queueMicrotask(()=>S.current?.focus())}function V(B,Q){f(!0),c(se=>Q?[...new Set([...se,B])]:se.filter(K=>K!==B))}function F(){f(!1),l(u.providers.length===0),c(u.providers),m(la(u.providerModels)),j(null),$(null)}async function z(){if(!(a.isError||a.isLoading||!r&&i.length===0)){h(!0),j(null),$(null);try{const B=Object.fromEntries(Object.entries(d).filter(([se,K])=>K.trim()!==""&&(r||i.includes(se)))),Q={providers:r?[]:i,providerModels:B};await s(Q),p({providers:[...Q.providers],providerModels:la(Q.providerModels)}),f(!1),$("Engine settings saved. They apply on the next sweep.")}catch(B){j(fa(B))}finally{h(!1)}}}return ie()||!n?null:a.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):a.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):g.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):v.size===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsxs("p",{className:"text-sm text-secondary",children:["Configure an answer engine in ",e.jsx(Ms,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":x,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Execution"}),e.jsx("h2",{children:"Answer engines"})]}),e.jsx("p",{className:"supporting-copy",children:"Changes apply on the next sweep."})]}),e.jsxs("fieldset",{disabled:x,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:r,onChange:()=>{f(!0),l(!0)}})," All configured engines"]}),e.jsx("p",{className:"project-engine-help",children:"Includes engines configured later in global Settings."}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:!r,onChange:I})," Choose engines"]}),!r&&e.jsx("div",{className:"project-engine-list",children:C.map(B=>{const Q=i.includes(B.name),se=v.has(B.name),K=Q&&!se,U=d[B.name],J=B.knownModels.some(X=>X.id===U),q=U===void 0?"__inherit__":J?U:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:Q,disabled:!se&&!Q,onChange:X=>V(B.name,X.target.checked)})," ",e.jsx("span",{children:B.displayName}),K&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),Q&&(B.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${B.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${B.name}`,value:q,onChange:X=>w(B.name,X.target.value,J),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",B.defaultModel||"default"]}),B.knownModels.map(X=>e.jsx("option",{value:X.id,children:X.displayName},X.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),q==="__custom__"&&e.jsx("input",{ref:S,"aria-label":`${B.displayName} custom model ID`,value:U??"",onChange:X=>{f(!0),m(L=>({...L,[B.name]:X.target.value}))},"aria-describedby":`project-model-hint-${B.name}`}),e.jsxs("p",{id:`project-model-hint-${B.name}`,className:"project-engine-help",children:[U?"Project override":"Inherited from instance settings",". ",B.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},B.name)})})]}),!r&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),b&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:b}),k&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:k}),T&&e.jsx("p",{className:"project-engine-warning",children:"Applies on the next sweep. Existing history remains visible. If the recorded model changes, month-to-month comparison may exclude that engine."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{type:"button",onClick:()=>{z()},disabled:x||!r&&i.length===0,children:x?"Saving engines…":"Save engines"}),e.jsx(P,{type:"button",variant:"outline",onClick:F,disabled:x,children:"Cancel"})]})]})}const As={heading:"Site Health scans",help:`Used by every scan that sets no budget, scheduled or manual. Onboarding's first look always checks ${Eh(Sm)}.`,pageBudget:"Page budget",customOption:"Custom number...",customLabel:"Custom page budget",customError:`Enter a whole number from 1 to ${Jl.toLocaleString("en-US")}.`,save:"Save page budget",saving:"Saving page budget…",saved:"Page budget saved."},Yi="full",Gn="custom";function er(t){return t===null?{choice:Yi,customText:""}:ic.some(s=>s.value===t)?{choice:String(t),customText:""}:{choice:Gn,customText:String(t)}}function Fb({choice:t,customText:s}){if(t===Yi)return null;if(t!==Gn)return Number(t);const n=s.trim();if(n==="")return;const a=wm.safeParse(Number(n));return a.success?a.data:void 0}function Kb({project:t,onSave:s}){const{canWrite:n,isAdmin:a}=nn(),r=n&&!ie()&&!Ls()&&(!Nm(Us["site-audit"])||a),l=t.siteAuditMaxPages??null,[i,c]=o.useState(l),[d,m]=o.useState(()=>er(l)),[u,p]=o.useState(!1),[x,h]=o.useState(!1),[y,f]=o.useState(!1),[b,j]=o.useState(null),[k,$]=o.useState(null),S=o.useRef(null),g=o.useId(),v=`${g}-heading`,C=`${g}-page-budget`,T=`${g}-custom-page-budget`,I=`${g}-custom-page-budget-error`;o.useEffect(()=>{y||x||(c(l),m(er(l)))},[l]);const w=Fb(d),F=d.choice===Gn&&w===void 0&&(u||d.customText.trim()!==""),z=w!==void 0&&w!==i;function B(J){h(!0),j(null),$(null),m(q=>({...q,choice:J})),J===Gn&&(p(!1),queueMicrotask(()=>S.current?.focus()))}function Q(J){h(!0),j(null),$(null),p(!0),m(q=>({...q,customText:J}))}function se(){h(!1),m(er(i)),p(!1),j(null),$(null)}async function K(){if(!(y||w===void 0)){f(!0),j(null),$(null);try{await s(w),c(w),m(er(w)),p(!1),h(!1),$(As.saved)}catch(J){j(fa(J))}finally{f(!1)}}}const U="h-9 w-full rounded-md border border-base bg-bg px-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600 disabled:opacity-60";return e.jsxs("section",{className:"project-engine-settings","aria-labelledby":v,"aria-busy":y,children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:v,children:As.heading}),e.jsx(Oe,{text:As.help})]})}),r?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid max-w-sm gap-1",children:[e.jsx("label",{htmlFor:C,className:"text-sm font-medium text-heading",children:As.pageBudget}),e.jsxs("select",{id:C,value:d.choice,disabled:y,onChange:J=>B(J.target.value),className:U,children:[e.jsx("option",{value:Yi,children:$h}),ic.map(J=>e.jsx("option",{value:String(J.value),children:J.label},J.value)),e.jsx("option",{value:Gn,children:As.customOption})]}),d.choice===Gn&&e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:T,className:"mt-2 text-sm font-medium text-heading",children:As.customLabel}),e.jsx("input",{ref:S,id:T,type:"number",inputMode:"numeric",min:1,max:Jl,step:1,value:d.customText,disabled:y,"aria-invalid":F,"aria-describedby":F?I:void 0,onChange:J=>Q(J.target.value),className:U}),F&&e.jsx("p",{id:I,role:"alert",className:"text-sm text-negative",children:As.customError})]})]}),b&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:b}),k&&e.jsx("p",{role:"status",className:"mt-3 text-sm text-positive",children:k}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsx(P,{type:"button",onClick:()=>{K()},disabled:y||!z,children:y?As.saving:As.save}),e.jsx(P,{type:"button",variant:"outline",onClick:se,disabled:y||!x,children:"Cancel"})]})]}):e.jsxs("p",{className:"text-sm text-secondary",children:[As.pageBudget,": ",e.jsx("span",{className:"text-strong",children:qh(i)})]})]})}const tr={edit:"Edit schedule",pause:"Pause",resume:"Resume",save:"Save schedule"},Gb=[{value:"daily",label:"Every day"},{value:"weekly@mon",label:"Every Monday"},{value:"weekly@wed",label:"Every Wednesday"},{value:"weekly@fri",label:"Every Friday"},{value:"twice-daily",label:"Twice a day (6am & 6pm)"},{value:"calendar",label:"Every N days"},{value:"custom",label:"Custom cron expression"}],Rl=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Toronto","America/Vancouver","Europe/London","Europe/Paris","Europe/Berlin","Asia/Tokyo","Asia/Shanghai","Asia/Singapore","Australia/Sydney"];function ei(t,s){const n=s==="UTC"?"UTC":s.split("/").pop()?.replace(/_/g," ")??s,a=new Date(`${t.startDate}T00:00:00Z`),r=Number.isNaN(a.getTime())?t.startDate:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(a),[l,i]=t.time.split(":").map(Number),c=Number.isInteger(l)&&Number.isInteger(i)?new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",timeZone:"UTC"}).format(new Date(Date.UTC(1970,0,1,l,i))):t.time;return`Every ${t.everyDays} days starting ${r} at ${c} · ${n}`}function _b({projectName:t}){const s=ds(),n=!ie()&&!Ls()&&!s,a=hs(),[r,l]=o.useState(!1),[i,c]=o.useState("daily"),[d,m]=o.useState(6),[u,p]=o.useState(""),[x,h]=o.useState(14),[y,f]=o.useState(""),[b,j]=o.useState("00:00"),[k,$]=o.useState("UTC"),[S,g]=o.useState(!1),[v,C]=o.useState(""),[T,I]=o.useState(!1),[w,V]=o.useState(!1),[F,z]=o.useState(null),[B,Q]=o.useState(void 0),se=Cm({client:W,path:{name:t}}),K=qe({...Xl({client:W,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),U=K.isPending||K.isFetching,J=K.isError,q=K.data?.find(Z=>Z.kind==="answer-visibility")??null,X=r&&B!==void 0&&(q?.updatedAt??null)!==B,L=Z=>{a.setQueryData(se,me=>{const G=(me??[]).filter(pe=>pe.kind!=="answer-visibility");return Z?[...G,Z]:G})},D=Z=>{if(Z){if(Z.recurrence)c("calendar"),h(Z.recurrence.everyDays),f(Z.recurrence.startDate),j(Z.recurrence.time);else{const G=Im(Z.preset??null,Z.cronExpr);c(G.freq),m(G.hour),p(G.customCron)}const me=Rl.includes(Z.timezone);$(me?Z.timezone:"Other"),g(!me),C(me?"":Z.timezone)}else c("daily"),m(6),p(""),h(14),f(""),j("00:00"),$("UTC"),g(!1),C("");Q(Z?.updatedAt??null)},ee=()=>{n&&(D(q),z(null),l(!0))},ne=()=>{D(q),z(null)},oe=async()=>{(await K.refetch()).isError?z("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):z(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},we=async(Z,me)=>{if(Z instanceof Vn&&Z.code==="SCHEDULE_VERSION_CONFLICT"){await oe();return}z(Z instanceof Error?Z.message:me)},Y=async()=>{if(n&&!(X||B===void 0)){I(!0),z(null);try{const Z=await K.refetch();if(Z.isError||Z.data===void 0){z("Canonry could not verify the latest schedule. Try again before saving.");return}const me=Z.data.find(Re=>Re.kind==="answer-visibility")??null;if((me?.updatedAt??null)!==B)return;const pe={timezone:S?v.trim()||"UTC":k,enabled:me?.enabled??!0,providers:me?.providers??[],expectedUpdatedAt:B};i==="calendar"?pe.recurrence={everyDays:x,startDate:y,time:b}:i==="custom"?pe.cron=u.trim():pe.preset=Pm(i,d);const Ee=await lo(t,pe);l(!1),Q(void 0),L(Ee),De({title:"Schedule saved",detail:Ee.recurrence?ei(Ee.recurrence,Ee.timezone):kr(Ee.preset??null,Ee.cronExpr,Ee.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(Z){await we(Z,"Failed to save schedule")}finally{I(!1)}}},ue=async()=>{if(!n||!q)return;const Z=q.updatedAt;I(!0),z(null);try{const me=await K.refetch();if(me.isError||me.data===void 0){z("Canonry could not verify the latest schedule. Try again before updating it.");return}const G=me.data.find(Re=>Re.kind==="answer-visibility")??null;if(!G||G.updatedAt!==Z){z("This schedule changed elsewhere. Review the latest version and try again.");return}const pe={timezone:G.timezone,enabled:!G.enabled,providers:G.providers,expectedUpdatedAt:Z};G.recurrence?pe.recurrence=G.recurrence:G.preset?pe.preset=G.preset:pe.cron=G.cronExpr;const Ee=await lo(t,pe);L(Ee),De({title:Ee.enabled?"Schedule resumed":"Schedule paused",detail:Ee.recurrence?ei(Ee.recurrence,Ee.timezone):kr(Ee.preset??null,Ee.cronExpr,Ee.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(me){await we(me,"Failed to update schedule")}finally{I(!1)}},he=async()=>{if(!n||!q)return;const Z=q.updatedAt;V(!0),z(null);try{await Rm(t,Z),L(null),l(!1),Q(void 0),De({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(me){await we(me,"Failed to remove schedule")}finally{V(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),n&&!U&&!J&&!r&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:ee,children:q?tr.edit:"+ Set schedule"})]}),U&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),F&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:F}),!U&&J&&e.jsxs(je,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{K.refetch()},children:"Retry"})]}),!U&&!J&&!r&&q===null&&e.jsx(je,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?Qn:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!U&&!J&&!r&&q!==null&&e.jsx(je,{className:"surface-card compact-card",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[s&&e.jsx("p",{className:"text-sm text-secondary",children:Qn}),e.jsx("p",{className:"text-sm font-medium text-strong",children:q.recurrence?ei(q.recurrence,q.timezone):kr(q.preset??null,q.cronExpr,q.timezone)}),!q.recurrence&&e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:q.cronExpr})]}),q.enabled&&q.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",km(q.nextRunAt,q.timezone)]}),q.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(q.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(Ne,{tone:q.enabled?"positive":"neutral",children:q.enabled?"Active":"Paused"}),n&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:T,onClick:Ze(ue),children:q.enabled?tr.pause:tr.resume}),n&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:w,onClick:Ze(he),children:w?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[X&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",role:"alert",children:[e.jsx("p",{children:"This schedule changed elsewhere. Load the latest version before saving."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:ne,children:"Load latest schedule"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Frequency",value:i,onChange:Z=>c(Z.target.value),children:Gb.map(Z=>e.jsx("option",{value:Z.value,children:Z.label},Z.value))})]}),i!=="calendar"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:d,disabled:i==="twice-daily"||i==="custom",onChange:Z=>m(parseInt(Z.target.value)),children:Array.from({length:24},(Z,me)=>e.jsx("option",{value:me,children:Am(me)},me))})]})]}),i==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:u,onChange:Z=>p(Z.target.value)})]}),i==="calendar"&&e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Repeat every"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Repeat every days",type:"number",min:"1",max:"3650",value:x,onChange:Z=>h(Number(Z.target.value))}),e.jsx("p",{className:"text-xs text-muted",children:"days"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Start date"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Start date",type:"date",value:y,onChange:Z=>f(Z.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Recurrence time",type:"time",value:b,onChange:Z=>j(Z.target.value)})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Timezone",value:S?"Other":k,onChange:Z=>{Z.target.value==="Other"?(g(!0),$("Other")):(g(!1),$(Z.target.value))},children:[Rl.map(Z=>e.jsx("option",{value:Z,children:Z},Z)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),S&&e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:v,onChange:Z=>C(Z.target.value)})]}),F&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:F}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{l(!1),Q(void 0),z(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:T||K.isFetching||J||X||i==="custom"&&!u.trim()||i==="calendar"&&(!Number.isInteger(x)||x<1||x>3650||!y||!b),onClick:Ze(Y),children:T?"Saving...":tr.save})]})]})]})}const Ub=[{value:"citation.lost",label:"Citation lost"},{value:"citation.gained",label:"Citation gained"},{value:"run.completed",label:"Run completed"},{value:"run.failed",label:"Run failed"}];function Bb({projectName:t}){const[s,n]=o.useState("loading"),[a,r]=o.useState(!1),[l,i]=o.useState(""),[c,d]=o.useState(["citation.lost","citation.gained"]),[m,u]=o.useState(!1),[p,x]=o.useState(null),[h,y]=o.useState({}),[f,b]=o.useState(new Set),j=!ie()&&!Ls();o.useEffect(()=>{Tm(t).then(n).catch(()=>n([]))},[t]);const k=v=>{d(C=>C.includes(v)?C.filter(T=>T!==v):[...C,v])},$=async()=>{if(!(!l.trim()||c.length===0)){u(!0),x(null);try{const v=await Mm(t,{channel:"webhook",url:l.trim(),events:c});n(C=>C==="loading"?[v]:[...C,v]),i(""),d(["citation.lost","citation.gained"]),r(!1),De({title:"Webhook added",detail:`Notifications will be sent to ${v.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(v){x(v instanceof Error?v.message:"Failed to add webhook")}finally{u(!1)}}},S=async v=>{if(!f.has(v)){b(C=>new Set(C).add(v));try{await $m(t,v),n(C=>C==="loading"?C:C.filter(T=>T.id!==v)),De({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${v}`,dedupeMode:"drop"})}catch(C){x(C instanceof Error?C.message:"Failed to remove webhook")}finally{b(C=>{const T=new Set(C);return T.delete(v),T})}}},g=async v=>{y(C=>({...C,[v]:{state:"testing"}}));try{const C=await Lm(t,v);y(T=>({...T,[v]:{state:C.ok?"ok":"fail",status:C.status}})),C.ok&&De({title:"Test notification sent",detail:`Webhook returned status ${C.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${v}`,dedupeMode:"replace"})}catch{y(C=>({...C,[v]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),j&&s!=="loading"&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),x(null)},children:a?"Cancel":"+ Add webhook"})]}),j&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:l,onChange:v=>i(v.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Ub.map(v=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:c.includes(v.value),onChange:()=>k(v.value)}),e.jsx("span",{className:"text-sm text-neutral",children:v.label})]},v.value))})]}),p&&e.jsx("p",{className:"text-negative-400 text-sm",children:p}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),x(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:m||!l.trim()||c.length===0,onClick:Ze($),children:m?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(je,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-neutral break-all",title:v.urlHost,children:v.urlDisplay??v.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:v.events.map(C=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-strong bg-surface-inset px-2 py-0.5 text-[10px] font-medium text-secondary uppercase tracking-wide",children:C.replace("."," ")},C))})}),e.jsx("td",{children:e.jsx(Ne,{tone:v.enabled?"positive":"neutral",children:v.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[h[v.id]&&(()=>{const C=h[v.id],T=C.state==="testing"?"Sending…":C.state==="ok"?`Delivered${C.status?` (${C.status})`:""}`:`Failed${C.status?` (${C.status})`:""}`;return e.jsx(Ne,{tone:C.state==="ok"?"positive":C.state==="fail"?"negative":"neutral",children:T})})(),j&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:h[v.id]?.state==="testing",onClick:()=>{g(v.id)},children:"Test"}),j&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:f.has(v.id),onClick:()=>{S(v.id)},children:f.has(v.id)?"Removing…":"Remove"})]})})]},v.id))})]}),p&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:p})]})]})}function Vb({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:l}){return ie()||ds()?null:e.jsx(Em,{open:t,onOpenChange:n,children:e.jsxs(Dm,{onCloseAutoFocus:i=>{r&&(i.preventDefault(),r())},children:[e.jsxs(Om,{children:[e.jsx(Fm,{children:"Run AI sweep for the whole project?"}),e.jsxs(Km,{children:["Runs all tracked queries for ",s,". View filters do not limit the sweep. Provider charges apply."]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsx(P,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(Ye,{disabled:l,onClick:a,children:"Run project-wide sweep"})]})]})})}const Pl=2e3,Il=3e5;function Qb(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function zb(t,s){t.setQueriesData({predicate:n=>n.queryKey[0]==="project-dashboard-full"&&n.queryKey[1]===s.id},n=>!n||typeof n!="object"||!("project"in n)?n:{...n,project:s})}function Hb({projectName:t,refreshNonce:s}){const n=hs(),[a,r]=o.useState(null),[l,i]=o.useState([]),[c,d]=o.useState(null),[m,u]=o.useState([]),[p,x]=o.useState([]),[h,y]=o.useState(null),[f,b]=o.useState(""),[j,k]=o.useState(""),[$,S]=o.useState(""),[g,v]=o.useState(!0),[C,T]=o.useState(!1),[I,w]=o.useState(null),[V,F]=o.useState("performance");o.useEffect(()=>{z()},[t,s]);async function z(){v(!0),w(null);try{const L=await n.fetchQuery({...ac({client:W,path:{name:t}}),staleTime:Yt});if(r(L),L.connected){const[D,ee,ne,oe]=await Promise.all([n.fetchQuery({...kh({client:W,path:{name:t}}),staleTime:Yt}).catch(()=>null),n.fetchQuery({...Ah({client:W,path:{name:t}}),staleTime:Yt}).catch(()=>[]),n.fetchQuery({...Rh({client:W,path:{name:t}}),staleTime:Yt}).catch(()=>[]),L.siteUrl?Promise.resolve([]):n.fetchQuery({...Ph({client:W,path:{name:t}}),staleTime:Yt}).then(we=>we.sites).catch(()=>[])]);d(D),u(ee),x(ne),i(oe)}else d(null),u([]),x([]),i([])}catch(L){w(L instanceof Error?L.message:"Failed to load Bing data")}finally{v(!1)}}async function B(){if(j.trim()){w(null);try{const L=await Ih(t,j.trim());await $t(n,"bing"),k(""),L.availableSites.length>0&&i(L.availableSites),await z()}catch(L){w(L instanceof Error?L.message:"Failed to connect")}}}async function Q(){try{await Th(t),await $t(n,"bing"),r(null),i([]),d(null),u([]),x([]),y(null),S(""),w(null)}catch(L){w(L instanceof Error?L.message:"Failed to disconnect")}}async function se(){if($)try{await Mh(t,$),await $t(n,"bing"),await z()}catch(L){w(L instanceof Error?L.message:"Failed to set site")}}async function K(){if(f.trim())try{const L=await Lh(t,f.trim());await $t(n,"bing"),y(L),u(D=>[L,...D])}catch(L){w(L instanceof Error?L.message:"Inspection failed")}}async function U(L){T(!0),w(null);try{const D=await mo(t,{urls:[L]}),{succeeded:ee,failed:ne,total:oe}=D.summary;De({title:"Bing submission requested",detail:ne===0?`${ee} URL submitted to Bing.`:`${ee}/${oe} submitted successfully, ${ne} failed.`,tone:ne===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${L}`,dedupeMode:"replace"})}catch(D){const ee=D instanceof Error?D.message:"Submission failed";w(ee),De({title:"Bing submission failed",detail:ee,tone:"negative",dedupeKey:`bing:indexing:${t}:${L}`,dedupeMode:"replace"})}finally{T(!1)}}async function J(){T(!0),w(null),De({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const L=await mo(t,{allUnindexed:!0}),{succeeded:D,failed:ee,total:ne}=L.summary;De({title:"Bing submissions requested",detail:ee===0?`${D}/${ne} URL${ne!==1?"s":""} submitted to Bing.`:`${D}/${ne} submitted successfully, ${ee} failed.`,tone:ee===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(L){const D=L instanceof Error?L.message:"Batch submission failed";w(D),De({title:"Bing submissions failed",detail:D,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{T(!1)}}if(g)return e.jsx(je,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return ie()?e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(Ne,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(Ne,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:j,onChange:L=>k(L.target.value),onKeyDown:L=>{L.key==="Enter"&&B()}}),e.jsx(Ye,{size:"sm",disabled:!j.trim(),onClick:Ze(B),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-secondary hover:text-neutral underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),I&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:I})]});if(!a.siteUrl)return e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Ze(Q),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.domain})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Jt(a.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Select site"}),l.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:$,onChange:L=>S(L.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(L=>e.jsxs("option",{value:L.url,children:[L.url,L.verified?" (verified)":""]},L.url))]}),!ie()&&e.jsx(Ye,{size:"sm",disabled:!$,onClick:Ze(se),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-muted",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),I&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:I})]});const q=[{key:"performance",label:"Performance",eyebrow:"Performance",title:"Search performance"},{key:"coverage",label:"Coverage",eyebrow:"Coverage",title:"Index monitoring"},{key:"inspections",label:"Inspections",eyebrow:"Inspection",title:"URL inspection history"}],X=q.find(L=>L.key===V)??q[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Ze(Q),children:"Disconnect"})]})]}),I&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:I}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["This project uses ",e.jsx("code",{children:a.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Jt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(je,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:X.eyebrow}),e.jsx("h3",{children:X.title})]}),e.jsx("p",{className:"text-xs text-muted",children:c?.lastInspectedAt?`Last inspected ${Jt(c.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:q.map(L=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${V===L.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>F(L.key),children:L.label},L.key))}),V==="coverage"&&c&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Fa,{label:"Indexed",value:c.summary.indexed,tone:"positive"}),e.jsx(Fa,{label:"Not in index",value:c.summary.notIndexed+(c.summary.unknown??0),tone:"negative"}),e.jsx(Fa,{label:"Status unknown",value:c.summary.unknown??0,tone:"neutral"}),e.jsx(Fa,{label:"Coverage",value:tt(c.summary.percentage,Yn.percent),tone:"neutral"})]}),c.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",c.notIndexed.length,")"]}),!ie()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:C,onClick:Ze(J),children:C?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!ie()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:c.notIndexed.map(L=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:L.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:L.httpCode??"—"}),!ie()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:C,onClick:()=>{U(L.url)},children:"Submit"})})]},L.id))})]})})]}),(c.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(c.unknown??[]).length,")"]}),!ie()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:C,onClick:Ze(J),children:C?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!ie()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(c.unknown??[]).map(L=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:L.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:L.lastCrawledDate?Jt(L.lastCrawledDate):"—"}),!ie()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:C,onClick:()=>{U(L.url)},children:"Submit"})})]},L.id))})]})})]}),c.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",c.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:c.indexed.map(L=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:L.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:L.lastCrawledDate?Jt(L.lastCrawledDate):"—"})]},L.id))})]})})]})]}),V==="coverage"&&!c&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),V==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!ie()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:f,onChange:L=>b(L.target.value),onKeyDown:L=>{L.key==="Enter"&&K()}}),e.jsx(Ye,{size:"sm",disabled:!f.trim(),onClick:Ze(K),children:"Inspect"})]}),h&&e.jsxs("div",{className:"rounded border border-base bg-bg-elevated/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-strong",children:h.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:h.inIndex?"text-positive-400":"text-negative-400",children:h.inIndex?"Yes":"No"})," · ","HTTP: ",h.httpCode??"—"," · ","Crawled: ",h.lastCrawledDate??"—"]})]}),m.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:m.map(L=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:L.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(Ne,{tone:L.inIndex?"positive":"negative",children:L.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:L.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Jt(L.inspectedAt)})]},L.id))})]})})]}),V==="performance"&&e.jsx("div",{className:"mt-4",children:p.length===0?e.jsx("p",{className:"text-xs text-muted",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Da[jn.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Da[jn.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Da[jn.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Da[jn.Position]})]})}),e.jsx("tbody",{children:p.map((L,D)=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:L.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:L.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:L.impressions}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:tt(L.ctr)}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:L.averagePosition.toFixed(1)})]},D))})]})})})]})]})}function Wb({projectName:t}){const s=hs(),[n,a]=o.useState("google"),[r,l]=o.useState(!0),[i,c]=o.useState("idle"),[d,m]=o.useState(null),u=o.useRef(null),[p,x]=o.useState(null),[h,y]=o.useState(null),[f,b]=o.useState(0);async function j($=!1){$||l(!0),m(null);try{const[S,g]=await Promise.all([s.fetchQuery({...Ai({client:W,path:{name:t}}),staleTime:Yt}).catch(()=>[]),s.fetchQuery({...ac({client:W,path:{name:t}}),staleTime:Yt}).catch(()=>null)]),v=S.find(C=>C.connectionType==="gsc")??null;x(v),y(g)}catch(S){m(S instanceof Error?S.message:"Failed to load search engine connections")}finally{l(!1)}}async function k(){if(i!=="idle")return;u.current?.abort();const $=new AbortController;u.current=$;const S=$.signal;c("syncing"),m(null),De({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const g=[],v=[];try{async function C(){if(!p)return;const w=await Sh(t);if(!w?.id)return;const V=Date.now()+Il;for(;Date.now()<V;){if(S.aborted||(await new Promise(z=>setTimeout(z,Pl)),S.aborted))return;const F=await ti(w.id).catch(()=>null);if(!F)break;if(["completed","failed","cancelled"].includes(F.status)){F.status!=="completed"&&g.push(`Google sync ${F.status}`);return}}v.push("Google sync is still running — search data will appear shortly")}async function T(){if(!h?.connected)return;const w=await Ch(t).catch(()=>null);if(!w?.id){g.push("Bing sweep could not be started");return}const V=Date.now()+Il;for(;Date.now()<V;){if(S.aborted||(await new Promise(z=>setTimeout(z,Pl)),S.aborted))return;const F=await ti(w.id).catch(()=>null);if(!F)break;if(["completed","failed","cancelled","partial"].includes(F.status)){F.status==="failed"?g.push("Bing sweep failed"):F.status==="partial"&&v.push("Bing sweep finished with some pages unverified");return}}v.push("Bing sweep is still running — coverage will update shortly")}const I=await Promise.allSettled([C(),T()]);for(const w of I)w.status==="rejected"&&g.push(w.reason instanceof Error?w.reason.message:"Sync failed");if(await Promise.all([$t(s,"gsc"),$t(s,"bing")]),S.aborted)return;if(c("reloading"),await j(!0),b(w=>w+1),g.length>0){const w=`Partial refresh: ${[...g,...v].join("; ")}`;m(w),De({title:"Search coverage partially refreshed",detail:w,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else v.length>0?De({title:"Search coverage refresh incomplete",detail:v.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):De({title:"Search coverage refreshed",detail:"Google and Bing workspaces are reloaded with the latest stored coverage.",tone:"positive",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}catch(C){if(!S.aborted){const T=C instanceof Error?C.message:"Refresh failed";m(T),De({title:"Search coverage refresh failed",detail:T,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{S.aborted||c("idle")}}return o.useEffect(()=>(j(),()=>{u.current?.abort()}),[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([$,S])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===$,className:`project-subnav-link ${n===$?"project-subnav-link-active":""}`,onClick:()=>a($),children:S},$))}),!ie()&&e.jsxs(Ye,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{k()},children:[e.jsx(ba,{className:`h-3.5 w-3.5 ${i!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":i==="syncing"?"Refreshing search data…":i==="reloading"?"Reloading workspaces…":"Refresh search data"]})]}),d&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:d}),n==="google"&&e.jsx(Dx,{projectName:t,refreshNonce:f}),n==="bing"&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(Hb,{projectName:t,refreshNonce:f})]})]})}function Tl({label:t,summary:s,displayValue:n,tooltip:a}){const{figure:r,sign:l}=Si(s.value),i=s.progress!==void 0?Math.min(Math.max(s.progress,0),100):0;return e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("p",{className:"aeo-hero-row-label",children:[t,(a||s.tooltip)&&e.jsx(Oe,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${ga[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[r,l?e.jsx("span",{className:"text-faint",children:l}):null]})}),e.jsx("div",{className:"aeo-hero-row-bar","aria-hidden":"true",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.tone}`,style:{width:`${i}%`}})})]})}function Yb({id:t,title:s,meta:n,defaultOpen:a=!1,children:r}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:a||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsx("h2",{className:"overview-disclosure-title",children:s}),e.jsxs("span",{className:"overview-disclosure-meta",children:[n&&e.jsx("span",{children:n}),e.jsx(zn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:r})]})}function Jb({insights:t,suggestedQueries:s,onManageQueries:n}){const{openEvidence:a}=Ci(),r=n?s.rows:[];if(t.length===0&&r.length===0)return null;const l=x=>e.jsxs("div",{className:"py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:x.title}),x.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:x.detail}):null]}),e.jsx(Ne,{tone:x.tone,children:x.actionLabel})]}),x.affectedPhrases.length>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:["Evidence · ",x.affectedPhrases.length," affected ",x.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:x.affectedPhrases.map((h,y)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(ri,{state:h.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:h.query}),h.provider?e.jsx(wh,{provider:h.provider}):null,!ie()&&h.evidenceId?e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(h.evidenceId)},children:"View evidence"}):null]},h.evidenceId||`${x.id}-${y}`))})]}):null]},x.id),i=x=>e.jsxs("div",{className:"flex items-start justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:x.query}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:x.reason})]}),n?e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},x.query),c=t.slice(0,1),d=r.slice(0,1),m=t.slice(1),u=r.slice(1),p=m.length+u.length;return e.jsxs("section",{className:"visibility-disclosure-panel","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[c.map(l),d.map(i)]}),p>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[p," more ",p===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[m.map(l),u.map(i)]})]}):null]})}function xv(t){const{projectName:s}=id({from:"/projects/$projectName"}),a=Zl()?.dashboard.projects.find(v=>v.project.name===s||v.project.id===s)?.project.name??null,r=qe({...qm({client:W}),enabled:!a}),l=a??r.data?.find(v=>v.name===s||v.id===s)?.name??null,i=ec(),c=tc(t.tab,sc(i)),[d,m]=o.useState(null),u=l!==null&&d===l,p=o.useCallback(()=>{l&&m(l)},[l]),{commandCenter:x,isLoading:h,overviewLoading:y,overviewError:f,isError:b,latestVisibilityRevision:j,competitorHistoryRevision:k,refetch:$}=nc(l,{overview:c==="overview"&&u}),S=!a&&r.isLoading||h;return!l&&!a&&r.isSuccess&&!h?e.jsx("div",{className:"page-container",children:e.jsxs(je,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(P,{asChild:!0,children:e.jsx(Ms,{to:"/",children:"Return to overview"})})]})}):!x&&(b||r.isError)?e.jsxs("div",{className:"page-container",role:"alert",children:[e.jsx("p",{children:"Could not load this project."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{Promise.all([r.refetch(),$()])},children:"Retry"})]}):!x||S?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(v=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},v))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(v=>e.jsx("div",{className:"skeleton-text-sm w-full"},v))})]})]}):e.jsx(sv,{model:x,refetch:$,latestVisibilityRevision:j,competitorHistoryRevision:k,overviewLoading:y,overviewError:f,overviewRequested:u,onRequestOverview:p,...t})}function Xb({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=o.useRef(null),l=o.useRef(null),[i,c]=o.useState(null);o.useLayoutEffect(()=>{const u=r.current,p=l.current;if(!u||!p)return;const x=()=>{const y=u.getBoundingClientRect().width;if(!y)return;const f=Number.parseFloat(getComputedStyle(u).columnGap)||0,b=new Map([...p.querySelectorAll("[data-project-tab]")].map(v=>[v.dataset.projectTab,v.getBoundingClientRect().width])),j=v=>b.get(v)??0,k=v=>v.reduce((C,T)=>C+j(T),0)+Math.max(0,v.length-1)*f,$=[...t.map(v=>v.key),...s.length?["more"]:[],...n?[n.key]:[]];let S=t.map(v=>v.key),g=!1;if(k($)>y){const v=t.find(I=>I.key===a),C=v?[v.key]:[];g=!!(n&&k([...C,"more",n.key])>y);const T=["more",...n&&!g?[n.key]:[]];for(const I of t)if(I.key!==v?.key){if(k([...C,I.key,...T])>y)break;C.push(I.key)}S=t.filter(I=>C.includes(I.key)).map(I=>I.key)}c(v=>v?.settingsInMore===g&&v.visibleKeys.join()===S.join()?v:{visibleKeys:S,settingsInMore:g})};if(x(),typeof ResizeObserver>"u")return window.addEventListener("resize",x),()=>window.removeEventListener("resize",x);const h=new ResizeObserver(x);return h.observe(u),h.observe(p),()=>h.disconnect()},[t,s,n,a]);const d=i?t.filter(u=>i.visibleKeys.includes(u.key)):t,m=[...t.filter(u=>!d.includes(u)),...s,...i?.settingsInMore&&n?[n]:[]];return e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",ref:r,children:[e.jsx("div",{className:"project-subnav-measure","aria-hidden":"true",children:e.jsxs("div",{className:"project-subnav-measure-row",ref:l,children:[[...t,...n?[n]:[]].map(u=>e.jsx("span",{className:"project-subnav-link","data-project-tab":u.key,children:u.label},u.key)),e.jsxs("span",{className:"project-subnav-link project-subnav-more-trigger","data-project-tab":"more",children:["More",e.jsx(zn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),d.map(u=>e.jsx(Ms,{to:u.href,search:p=>({...p,onboarding:void 0}),className:`project-subnav-link ${u.key===a?"project-subnav-link-active project-subnav-current":""}`,"aria-current":u.key===a?"page":void 0,children:e.jsx("span",{className:"project-subnav-label",children:u.label})},u.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(Zb,{items:m,activeTab:a}),n&&!i?.settingsInMore&&e.jsx(Ms,{to:n.href,search:u=>({...u,onboarding:void 0}),className:`project-subnav-link ${a==="settings"?"project-subnav-link-active":""}`,"aria-current":a==="settings"?"page":void 0,children:n.label})]})]})}function Zb({items:t,activeTab:s}){const[n,a]=o.useState(!1),r=o.useRef(null),l=o.useRef(null),i=o.useRef("first"),c=o.useId(),d=t.map(u=>u.key).join();if(o.useEffect(()=>{a(!1)},[d]),o.useEffect(()=>{if(!n)return;const u=r.current?.querySelectorAll('[role="menuitem"]');(i.current==="last"?u?.[u.length-1]:u?.[0])?.focus()},[n]),o.useEffect(()=>{if(!n)return;const u=x=>{r.current&&!r.current.contains(x.target)&&a(!1)},p=x=>{x.key==="Escape"&&(a(!1),l.current?.focus())};return document.addEventListener("pointerdown",u),document.addEventListener("keydown",p),()=>{document.removeEventListener("pointerdown",u),document.removeEventListener("keydown",p)}},[n]),t.length===0)return null;const m=t.some(u=>u.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",ref:l,className:`project-subnav-link project-subnav-more-trigger ${m?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?c:void 0,onClick:()=>{i.current="first",a(u=>!u)},onKeyDown:u=>{u.key!=="ArrowDown"&&u.key!=="ArrowUp"||(u.preventDefault(),i.current=u.key==="ArrowUp"?"last":"first",a(!0))},children:["More",e.jsx(zn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:c,"aria-label":"More project sections",onKeyDown:u=>{const p=[...u.currentTarget.querySelectorAll('[role="menuitem"]')],x=p.indexOf(document.activeElement),h=u.key==="Home"?0:u.key==="End"?p.length-1:u.key==="ArrowDown"?(x+1)%p.length:u.key==="ArrowUp"?(x-1+p.length)%p.length:null;h!==null&&(u.preventDefault(),p[h]?.focus())},onBlur:u=>{r.current?.contains(u.relatedTarget)||a(!1)},children:t.map(u=>e.jsx(Ms,{to:u.href,search:p=>({...p,onboarding:void 0}),role:"menuitem",tabIndex:-1,className:`project-subnav-menu-item ${u.key===s?"project-subnav-menu-item-active":""}`,"aria-current":u.key===s?"page":void 0,onClick:()=>a(!1),children:u.label},u.key))}):null]})}const ev=20,tv=5;function sv({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r,overviewLoading:l,overviewError:i,overviewRequested:c,onRequestOverview:d}){const m=od(),u=hs(),{account:p,canWrite:x}=nn(),[h,y]=o.useState(null),f=o.useRef(null),b=Zl(),j=s.project.name,k=b?.dashboard.projects.some(M=>M.project.name===j)??!1,$=ld({strict:!1}),S=Gm($),g=mp(S),v=qe({..._m({client:W,path:{name:j}}),enabled:!ie()&&!!j&&(x||t==="portfolio"||t==="overview"||t==="settings"||g),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),C=b?b.dashboard.settings.providerStatuses.filter(M=>M.state==="ready").map(M=>co(M.name)):void 0,T=v.data?.answerVisibilityProviderReady,I=C,w=s.project.providers.map(co),V=I?.some(M=>w.length===0||w.includes(M))===!0,F=w.length===0||w.includes(Um),z=qe({...Bm({client:W}),enabled:!ie()&&x&&T===void 0&&F&&!V,staleTime:6e4,retry:!1}),B=F?z.isSuccess?typeof z.data.browserVersion=="string":z.isError?!1:void 0:!1,Q=T??Vm({projectProviders:w,configuredApiProviders:I,cdpConfigured:B}),se=o.useMemo(()=>sc(ec()),[]),K=tc(t,se),U=o.useMemo(()=>s.competitors.map(M=>M.domain),[s.competitors]),J=o.useMemo(()=>Object.fromEntries(s.competitors.map(M=>[M.domain,M.aliases??[]])),[s.competitors]),q=o.useMemo(()=>Object.fromEntries(s.competitors.map(M=>[M.domain,M.autoAliases??[]])),[s.competitors]),X=o.useMemo(()=>Object.fromEntries(s.competitors.map(M=>[M.domain,[...M.aliases??[],...M.autoAliases??[]]])),[s.competitors]),[L,D]=o.useState(!1),[ee,ne]=o.useState(!1),oe=Qm(),we=o.useCallback((M,fe)=>{m({to:".",search:ye=>zm(ye,M),replace:fe?.replace===!0})},[m]),Y=$.queryWorkspace==="research"||K==="discovery"&&$.queryWorkspace===void 0?"research":"tracked",ue=uc(Y,dc(p?.role,p?.role==="viewer"?Wl():null)),he=qe({...Ii({client:W,path:{name:j}}),enabled:!ie()&&(K==="queries"||K==="discovery")&&ue==="tracked"}),Z=$.manageQueries===!0,me=o.useCallback(()=>{m({to:".",replace:!0,search:M=>({...M,siteHealthRunId:void 0})})},[m]),[G,pe]=o.useState(Z),[Ee,Re]=o.useState(""),[re,xe]=o.useState(!1),[Ae,et]=o.useState(null),[Le,O]=o.useState("30d"),[ke,A]=o.useState(void 0),[be,Ke]=o.useState(""),[Ve,Ge]=o.useState(!1),[ge,vt]=o.useState(null),[Qe,Je]=o.useState(!1),Dt=Hm($),[ct,at]=o.useState(void 0),[pt,Ct]=o.useState(void 0),It=o.useCallback(M=>{at(M.search),M.sort&&Ct(M.sort),m({to:".",search:fe=>({...fe,...Wm(M)}),replace:!1})},[m]),[He,R]=o.useState(!1),$e=s?.project.displayName||s?.project.name||j,Ie=Ym(),Fe=qe({...uo({client:W,path:{name:j}}),enabled:K==="portfolio"&&!!j,staleTime:0,refetchOnMount:"always"}),dt=qe({...Jm({client:W,path:{name:j}}),enabled:!ie()&&!!j&&(x||K==="portfolio"||K==="overview"||K==="settings"),staleTime:0,refetchOnMount:"always"}),ze=dt.data?.active??null,yt=dt.data!==void 0,te=new Set(ze&&Number(ze.plan.schemaVersion)===2?ze.plan.groups?.map(M=>M.stableKey)??[]:[]),Pe={...Dt.scope==="group"&&!!Dt.groupKey&&yt&&!te.has(Dt.groupKey)?{scope:"all",queryClass:Dt.queryClass}:Dt,...ct?{search:ct}:{}},ve=ze===null?null:Number(ze.plan.schemaVersion),Tt=ze?.revision??0,Xt=yt?`${j}:${Tt}`:null,Zt=o.useRef(null);o.useEffect(()=>{const M=Zt.current;Xt!==null&&(Zt.current=Xt),Xm(M,Xt)&&(It({scope:"all",queryClass:"all"}),R(!1))},[Xt,It]);const Ot={client:W,path:{name:j},query:{scope:Pe.scope,...Pe.groupKey?{groupKey:Pe.groupKey}:{},queryClass:Pe.queryClass,...Pe.search?{search:Pe.search}:{},...pt?{sort:pt}:{},limit:50}},ut=Ml({...Zm(Ot),enabled:!1,initialPageParam:Ot,getNextPageParam:(M,fe)=>{if(!M.properties.nextCursor)return;const ye=fe[0]?.measurement.displayedRunId;return{path:Ot.path,query:{...Ot.query,cursor:M.properties.nextCursor,...ye?{runId:ye}:{}}}},placeholderData:wi,staleTime:0,refetchOnMount:"always"}),es=ut.data?.pages[0]?.measurement.displayedRunId,it=qe({...eh({client:W,path:{name:j},query:{revision:Tt,...es?{runId:es}:{}}}),enabled:K==="overview"&&!!j&&ze!==null&&ve===1,staleTime:0,refetchOnMount:"always"}),gs=dt.data!==void 0,ps=Fe.data!==void 0,Bs=dt.isPending&&!gs,bt=dt.isError&&!gs,Vs=Fe.isPending&&!ps,Mt=Fe.isError&&!ps,as=it.data!==void 0,Vt=Ab({activePlanSchemaVersion:v.data?.activeSchemaVersion??ve,hasDraft:v.data?.draft!==null&&v.data?.draft!==void 0}),xt=Vt.surface==="simple-overview",ts=v.data===void 0&&dt.data===void 0&&(dt.isLoading||v.isLoading);o.useEffect(()=>{K==="overview"&&xt&&!ts&&d()},[ts,xt,d,K]);const Qt=hp({tab:K,surface:ts?"unresolved":Vt.surface,embedded:ie(),scoped:g,queryWorkspace:ue,tracking:he.isError?{state:"error"}:he.data?{state:"ready",mode:he.data.mode,scopeUnavailable:mc(he.data,S)}:{state:"pending"}}),fs=Mc(j,S,{enabled:Qt.kind==="report-picker"}),zt=K==="overview"&&xt&&!ts,gt=nc(j,{evidence:zt}),Lt=gt.commandCenter?.visibilityEvidence??s.visibilityEvidence,Nt=o.useMemo(()=>{const M=new Map(Lt.map(ye=>[Bn(ye.query),ye.queryClass??null])),fe=th(sh(s.project));return ye=>{const ft=M.get(Bn(ye));return ft!==void 0?ft:fe?.classify(ye)??null}},[Lt,s.project]),ys=o.useMemo(()=>[...new Set([...Lt.map(M=>M.query),...s.movementComparison.addedQueries,...s.movementComparison.removedQueries])],[Lt,s.movementComparison]),bs=o.useMemo(()=>s.visibilitySweeps.map(M=>M.createdAt),[s.visibilitySweeps]),_=x&&!ie()&&!ds()&&K!=="overview",ae=qe({...uo({client:W,path:{name:j}}),enabled:_,staleTime:Ri,refetchOnWindowFocus:"always"}),de=ve===2&&S.measurementScope==="group"?S.measurementScopeKey:void 0,le=ve===2&&S.measurementScope==="project",Te=o.useMemo(()=>{if(!(ze?.plan.schemaVersion!==2||!de))return ze.plan.groups.find(M=>M.stableKey===de)},[ze,de]),Ue={client:W,path:{name:j},query:{window:Le,queryClass:ve===2&&S.queryClass!=="unknown"?S.queryClass:"non-brand",...de?{groupKey:de}:{},...le?{scope:"all-markets"}:{}}},mt=K==="overview"&&!S.marketKey&&!!j&&(xt||yt)&&!ts&&(xt||(S.measurementScope==="project"||ve===2&&S.measurementScope==="group")&&S.queryClass!=="unknown"&&(ve===2||S.queryClass!=="branded")),[kt,vs]=o.useState(null);o.useEffect(()=>{mt||vs(null)},[mt]),o.useEffect(()=>{vs(null)},[j]);const E=kt===j,Se=mt&&E,st=qe({...nh(Ue),enabled:Se,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});ah(j,JSON.stringify([r,s.competitors.map(M=>`${M.domain}=${[...M.aliases??[],...M.autoAliases??[]].join("|")}`).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,Tt,v.data?.draft?.etag??null]),Se);const qt=st.isError?st.data===void 0?"Could not load competitors over time. Your pinned competitors remain available.":"Could not refresh competitors over time. Showing the last available data.":void 0,Ft=o.useMemo(()=>s.competitors.map(M=>({domain:M.domain,label:M.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:M.citationCount,answeredResults:M.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),Be=o.useMemo(()=>{if(ze?.plan.schemaVersion!==2)return Ft;const M=de?Te?.competitors??[]:ze.plan.groups.flatMap(ye=>ye.competitors),fe=new Map;for(const ye of M){const ft=ye.domain.trim().toLowerCase();!ft||fe.has(ft)||fe.set(ft,{domain:ye.domain,label:ye.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const ye of Ft){const ft=ye.domain.trim().toLowerCase();!ft||fe.has(ft)||fe.set(ft,ye)}return[...fe.values()]},[ze,de,Ft,Te]),wt=ve===2?Be:Ft,qs=Et({...rh({client:W}),meta:{skipGlobalErrorToast:!0}}),Xn=v.data!==void 0?"success":v.isError?"error":"pending",ss=o.useMemo(()=>{const M=ut.data?.pages;return M?!Fh(M):!1},[ut.data]),an=o.useMemo(()=>{const M=ut.data?.pages,fe=M?.[0],ye=M?.at(-1);if(!(!fe||!ye||ss))return{...fe,properties:{...fe.properties,items:M.flatMap(ft=>ft.properties.items),nextCursor:ye.properties.nextCursor}}},[ss,ut.data]),Kt=o.useMemo(()=>{if(ze)return ze.plan.schemaVersion===1?it.data?qb(ze,it.data):void 0:an?Kh({overview:an,activePlan:ze,sort:pt,report:it.data,reportState:an.measurement.displayedRunId===void 0?"ready":it.isFetching&&it.data===void 0?"loading":it.isError&&it.data===void 0?"error":it.data?"ready":"loading"}):void 0},[ze,it.data,it.isError,it.isFetching,an]),Es=ve===2?ss?"error":ut.isPending?"loading":ut.isError&&Kt===void 0?"error":"ready":it.isPending&&!as?"loading":it.isError&&!as?"error":"ready",Ds=(s?.recentRuns??[]).some(M=>M.kind===Us["answer-visibility"]&&(M.status===Ts.running||M.status===Ts.queued)),kn=s.queryCounts.total>0,Pa=o.useMemo(()=>(s?.project.locations??[]).map(M=>M.label),[s?.project.locations]),Zn=o.useMemo(()=>new Set(Lt.map(M=>M.location??"")),[Lt]),ea=Zn.has(""),rn=o.useMemo(()=>[...new Set(Lt.map(M=>M.query))].sort((M,fe)=>M.localeCompare(fe)),[Lt]),on=rn.length>0||s.queryCounts.total>0||(ae.data?.length??0)>0||ze!==null,Rn=x&&!on&&(dt.data===void 0&&dt.isPending||ae.isLoading||zt&>.evidenceLoading),ln=x&&(v.isError&&!v.isFetching||_&&ae.isError&&!ae.isFetching),cn=x&&!ln&&(Rn||Q===void 0||v.isFetching),ta=!cn&&!ln&&on&&Q===!0,dn=x&&!cn&&!ta,sa=!ie()&&K==="overview"&&dn&&!on,js=qe({...ih({client:W,path:{name:j},query:{limit:ev}}),enabled:sa&&!!j,retry:!1}),Ia=js.isSuccess&&js.data.scans.some(M=>M.status==="completed"||M.status==="partial"),Ta=sa&&js.isSuccess&&!Ia,Ma=sa&&Ia,un=qe({...Xl({client:W,path:{name:j}}),enabled:!ie()&&!ds()&&!!j,retry:!1}).data?.find(M=>M.kind===Us["answer-visibility"]),Pn=un?.enabled&&un.nextRunAt?oh(un.nextRunAt,un.timezone):null,na=Pn?`Next AI sweep ${Pn}`:null,La=o.useMemo(()=>{const M=[...Zn].filter(Boolean);return M.length>1?M:Pa},[Zn,Pa]);o.useEffect(()=>{if(!zt||ke===void 0||ke===""||!j){vt(null),Je(!1);return}Je(!0),lh(j,ke,20).then(M=>{vt(M),Je(!1)}).catch(()=>{vt(null),Je(!1)})},[ke,j,zt]);const In=o.useMemo(()=>{if(!ge)return null;const M=new Map;for(const fe of ge){for(const[ye,ft]of Object.entries(fe.providerRuns??{}))M.set(`${fe.query}::${ye}`,ft.map(Ss=>({runId:Ss.runId,citationState:Ss.citationState,createdAt:Ss.createdAt,answerMentioned:Ss.answerMentioned,visibilityState:Ss.visibilityState,visibilityTransition:Ss.visibilityTransition,mentionState:Ss.mentionState,mentionTransition:Ss.mentionTransition})));(!fe.providerRuns||Object.keys(fe.providerRuns).length===0)&&M.set(`${fe.query}::`,fe.runs.map(ye=>({runId:ye.runId,citationState:ye.citationState,createdAt:ye.createdAt,answerMentioned:ye.answerMentioned,visibilityState:ye.visibilityState,visibilityTransition:ye.visibilityTransition,mentionState:ye.mentionState,mentionTransition:ye.mentionTransition})))}return M},[ge]),$a=o.useMemo(()=>{const M=ke!==void 0?Lt.filter(fe=>ke===""?!fe.location:fe.location===ke):Lt;return In?M.map(fe=>{const ye=In.get(`${fe.query}::${fe.provider}`)??In.get(`${fe.query}::`);return ye?{...fe,runHistory:ye}:fe}):M},[Lt,ke,In]);async function br(){if(!(h!==j||!x||ie()||ds()||Ie.isPending||Ds||!ta))try{await Ie.mutateAsync({projectName:j,projectLabel:$e,sourceAction:"project-run"}),y(null),n()}catch{}}function qa(){m({to:"/setup",search:{experience:"legacy",setupProject:j}})}function N(){m({to:"/projects/$projectName/technical-aeo",params:{projectName:j}})}async function H(){ne(!0);try{await Nh(j),De({title:"Project deleted",detail:`${$e} was removed.`,tone:"positive",dedupeKey:`project:delete:${j}`,dedupeMode:"drop"}),m({to:"/"}),n()}catch(M){console.error("Failed to delete project:",M)}finally{ne(!1)}}async function ce(){const M=Ee.split(`
|
|
7
|
-
`).map(fe=>fe.trim()).filter(Boolean);if(M.length!==0){xe(!0);try{await hh(j,M),n(),Re("")}finally{xe(!1)}}}async function Ce(M){et(M);try{await mh(j,[M]),n()}catch(fe){De({title:"Could not remove query",detail:fe instanceof Error?fe.message:`Failed to remove "${M}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{et(null)}}async function rt(M){const fe=M.trim();if(!fe)return!1;try{return await dh(j,[fe]),n(),!0}catch(ye){return De({title:"Could not add competitor",detail:ye instanceof Error?ye.message:`Failed to add ${fe}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function nt(M){const fe=s.competitors.find(ye=>ye.domain===M);if(!fe)return De({title:"Could not remove competitor",detail:`Could not find ${M} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await uh(j,fe.id),n(),!0}catch(ye){return De({title:"Could not remove competitor",detail:ye instanceof Error?ye.message:`Failed to remove ${fe.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function ht(M){const fe=M.trim();if(!fe||!de||ve!==2||!x||ie()||qs.isPending)return!1;try{const ye=await qs.mutateAsync({client:W,path:{name:j},headers:{"Idempotency-Key":Qb()},body:{expectedActiveRevision:Tt,groupKey:de,domain:fe}});return Promise.allSettled([v.refetch()]),De({title:ye.draftCreated?"Competitor added to a market draft":"Market competitor updated",detail:`Publish the Advanced Measurement draft before ${fe} is used in future market runs.`,tone:"positive",dedupeKey:`competitor:market-pin:${de}:${fe}`,dedupeMode:"replace"}),!0}catch(ye){return De({title:"Could not add market competitor",detail:ye instanceof Error?ye.message:`Failed to add ${fe} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function Rt(M,fe){const ye=await yh(M,fe);return await u.invalidateQueries({queryKey:bh({client:W})}),u.setQueryData(vh({client:W,path:{name:M}}),ye),zb(u,ye),fe.providers!==void 0&&await u.invalidateQueries({queryKey:jh({client:W,path:{name:M}}),exact:!0}),ye}const Xe=`/projects/${encodeURIComponent(s.project.name)}`,Me=[{key:"overview",label:"AI Visibility",href:Xe},{key:"search-console",label:"Search Engines",href:`${Xe}/search-console`},{key:"activity",label:"Activity",href:`${Xe}/activity`},{key:"technical-aeo",label:"Site Health",href:`${Xe}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${Xe}/conversions`},{key:"local",label:"Local Presence",href:`${Xe}/local`},{key:"queries",label:"Queries",href:`${Xe}/queries`},{key:"backlinks",label:"Backlinks",href:`${Xe}/backlinks`}],Ns=[{key:"history",label:"Change History",href:`${Xe}/history`}],mn=Me.filter(M=>Ar(M.key,se)),Tn=Ns.filter(M=>Ar(M.key,se)),ws=Ar("settings",se)?{key:"settings",label:"Settings",href:`${Xe}/settings`}:null;function vr(M){const fe=xt?M:e.jsx(Fg,{projectName:j,selection:S,showUnmeasuredFallback:!ze&&!kn&&S.measurementScope==="project"&&S.queryClass==="all"&&!S.provider&&!S.model&&!S.location&&!S.from&&!S.to&&!S.revision&&!S.measurementRunId&&!S.queryKey&&!S.marketKey,onSelectionChange:we,onManageQueries:ie()?void 0:()=>{m({to:"/projects/$projectName/queries",params:{projectName:j},search:ft=>({...ft,queryWorkspace:"tracked",trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:ie()?void 0:({id:ft,label:Ss})=>e.jsx(Ms,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:j,targetKey:ft},search:ph,"aria-label":`Property details for ${Ss}`,className:"inline-flex min-h-11 items-center text-sm text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:"Property details"}),fallback:M});if(ie())return fe;let ye=xh(S,xt?"simple":"advanced",typeof $.sentimentEvaluationDefinitionId=="string"?$.sentimentEvaluationDefinitionId:void 0);return xt&&(ye.location=ke===""?"none":ke,ye=gh(ye,$a,be)),e.jsx(fh,{hasSourceEvidence:!xt||!!(ye.runId||ye.runIds?.length),evidenceReady:!xt||!(gt.isLoading||gt.evidenceLoading||gt.evidenceError),waitForResolvedRun:!xt,projectName:j,runOptions:s.visibilitySweeps.slice(0,tv).map(ft=>({id:ft.id,label:Jt(ft.finishedAt??ft.createdAt)})),selection:ye,children:fe})}function ad(){switch(Qt.kind){case"report-picker":{if(fs.error)return Ql(zl(fs.error))?e.jsx("p",{className:"text-[13px] text-secondary",children:Oa.savedScopeUnavailable}):null;const M=fs.data;if(!M)return e.jsx("div",{className:"skeleton-text h-11 w-56",role:"status","aria-label":"Loading measurement scope"});if(M.selection.availability.state!=="available"||M.scopeOptions.length<=1)return null;const fe=ai(M.scopeOptions,S)??M.selection.scope;return e.jsx(ho,{labelVisibility:"sr-only",options:M.scopeOptions,selected:fe,marketKey:S.marketKey,onSelect:(ye,ft)=>we({measurementScope:ye.kind,measurementScopeKey:ye.kind==="project"?void 0:ye.id,measurementMarketKey:ft})})}case"tracking-picker":{const M=he.data?.scopeOptions??[],fe=ai(M,S);return fe?e.jsx(ho,{labelVisibility:"sr-only",options:M,selected:fe,onSelect:ye=>we({measurementScope:ye.kind,measurementScopeKey:ye.kind==="project"?void 0:ye.id})}):null}case"scope-unavailable":return e.jsx("p",{className:"text-[13px] text-secondary",children:Oa.savedScopeUnavailable});case"project-wide":return e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[13px] text-secondary",children:Oa.projectWide}),e.jsx(Oe,{text:Oa.projectWideHelp})]});case"none":return null}}const Ji=K==="overview"&&!xt&&(S.from||S.to)?`${S.from?.slice(0,10)??"First measurement"} to ${S.to?.slice(0,10)??"Latest measurement"}`:null,Xi=ad(),Zi=mt?e.jsx(Pp,{window:Le,landscape:st.data,pinnedFallback:wt,competitorAliases:J,competitorAutoAliases:q,canWrite:x,isEmbed:ie(),onWindowChange:O,onPin:de&&x&&!ie()?ht:!le&&x&&!ie()?rt:void 0,onUnpin:de||le||!x||ie()?void 0:nt,onAddCompetitor:de&&x&&!ie()?ht:!le&&x&&!ie()?rt:void 0,error:qt,onRetry:Se?()=>{st.refetch()}:void 0,isLoading:Se&&st.isPending&&st.data===void 0,scopeLabel:de?`${Te?.label??de} group`:le?"All markets":"Project-wide"}):null,jr=ie()?null:e.jsx(e.Fragment,{children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>pe(!G),children:G?"Done":"Manage queries"})}),eo=!ie()&&G?e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[rn.length>0?e.jsx("ul",{className:"mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto rounded border border-default",children:rn.map(M=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsx("span",{className:"min-w-0 truncate text-sm text-strong",title:M,children:M}),e.jsx("button",{type:"button",className:"shrink-0 rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500 disabled:opacity-50","aria-label":`Remove query ${M}`,title:`Stop tracking "${M}"`,disabled:Ae!==null,onClick:()=>{Ce(M)},children:Ae===M?"Removing…":"Remove"})]},M))}):e.jsx("p",{className:"mb-3 text-xs text-muted",children:"No queries tracked yet. Add some below."}),e.jsx("textarea",{className:"w-full resize-none rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:3,placeholder:"Enter queries to add, one per line",value:Ee,onChange:M=>Re(M.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[Ee.split(`
|
|
8
|
-
`).filter(M=>M.trim()).length," to add"]}),e.jsx(Ye,{type:"button",size:"sm",disabled:!Ee.trim()||re,onClick:Ze(ce),children:re?"Adding...":"Add queries"})]})]}):null;return e.jsxs("div",{className:"page-container",children:[ie()?e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain," · ",s.contextLabel]})]}),e.jsx("div",{className:ds()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:Ji!==null?e.jsx("p",{className:"text-sm text-muted",children:Ji}):null})]}):e.jsxs("div",{className:"project-context-row",children:[e.jsx("h1",{className:"project-context-title md:sr-only",children:s.project.displayName||s.project.name}),Xi!==null?e.jsx("div",{className:"project-context-scope",children:Xi}):null,s.project.canonicalDomain?e.jsx("span",{className:"project-context-domain",children:s.project.canonicalDomain}):null,e.jsx("div",{className:"project-context-actions","data-project-actions":!0,children:ds()?e.jsx(ch,{projectName:j,running:Ds,portfolio:!xt}):e.jsxs(e.Fragment,{children:[na?e.jsx("p",{className:"text-sm text-secondary",children:na}):null,Ta?e.jsx(Ye,{type:"button",onClick:N,children:"Map site"}):Ma?e.jsx(Ye,{type:"button",onClick:N,children:"View Page Health"}):null,e.jsx(Ye,{type:"button",variant:"outline",disabled:Ie.isPending||Ds||cn,onClick:ln?()=>{Promise.all([v.refetch(),..._?[ae.refetch()]:[]])}:dn?qa:M=>{f.current=M.currentTarget,y(j)},children:Ie.isPending?"Starting…":Ds?"AI sweep running…":cn?"Checking AI readiness…":ln?"Retry AI readiness":dn?"Set up AI Visibility":"Run AI sweep"})]})})]}),!ie()&&!ds()&&e.jsx(Vb,{open:h===j,projectLabel:$e,onOpenChange:M=>y(M?j:null),onConfirm:Ze(br),onClosed:()=>f.current?.focus(),disabled:Ie.isPending||Ds||!ta}),e.jsx(Xb,{items:mn,overflowItems:Tn,settingsItem:ws,activeTab:K}),K==="portfolio"&&!ie()?e.jsx(lb,{projectName:j,canEdit:x,queries:Fe.data??[],isQueryLoading:Vs,isQueryError:Mt,onRetryQueries:()=>{Fe.refetch()},publishedPlan:ze,onCreateQueries:async M=>(await oe.mutateAsync({projectName:j,queries:[...M]}),(await Fe.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{m({to:"/projects/$projectName",params:{projectName:j},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([v.refetch(),dt.refetch()]).finally(()=>{m({to:"/projects/$projectName",params:{projectName:j}})})}},j):K==="overview"?ts||xt&&!k&&(!c||l)?e.jsxs("div",{role:"status","aria-live":"polite",children:[e.jsx("span",{className:"sr-only",children:"Loading project overview"}),e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-hidden":"true"})]}):xt&&i?e.jsxs("div",{role:"alert",className:"page-section-divider",children:[e.jsx("p",{children:"Could not load AI visibility."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[bt?e.jsxs("div",{role:"alert",className:"mb-5 flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("span",{children:"Could not check the advanced measurement setup. Existing project-wide results remain available."}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{dt.refetch()},children:"Retry setup check"})]}):null,vr(e.jsx(Rb,{mode:Vt,canEdit:x&&!ie()&&!Bs&&!bt,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(sf,{projectName:s.project.name,competitorDomains:U,competitorAliases:X,analyticsRevision:a,queryTexts:ys,classifyQuery:Nt,sweepTimes:bs})}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"av-card-head",children:[e.jsx("h2",{className:"av-card-title",children:"Where competitors are winning"}),kn?e.jsx("p",{className:"av-card-meta",children:"Latest sweep"}):null]}),kn?e.jsxs("div",{className:"competitive-summary",children:[e.jsx(yp,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:U},s.project.name),e.jsxs("div",{className:"competitive-gaps",children:[e.jsx("p",{className:"competitive-gaps-scope",children:"All queries"}),e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Tl,{label:"Mention gaps",summary:s.mentionGaps,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.mentionGaps.value}),e.jsxs("span",{className:"text-secondary",children:[" / ",s.queryCounts.total]}),e.jsx("span",{className:"sr-only",children:" queries, all queries"})]}),tooltip:"Across all queries, branded and non-brand: a competitor was mentioned in an answer and your brand was not mentioned by any engine. The mention-share query type does not filter these counts."}),e.jsx(Tl,{label:"Citation gaps",summary:s.gapQueries,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.gapQueries.value}),e.jsxs("span",{className:"text-secondary",children:[" / ",s.queryCounts.total]}),e.jsx("span",{className:"sr-only",children:" queries, all queries"})]}),tooltip:"Across all queries, branded and non-brand: a competitor was cited as a source and your domain was not cited by any engine. The mention-share query type does not filter these counts."})]})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Competitive mention and citation gaps appear after the first AI Visibility sweep."})]}),e.jsx("div",{className:"page-section-divider",children:e.jsx(xg,{projectName:s.project.name,classify:Nt,hasCompetitors:U.length>0,providerScores:s.providerScores})}),e.jsxs(Yb,{id:"evidence-section",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${ke===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":ke===void 0,onClick:()=>{A(void 0)},children:"All locations"}),s.project.locations.map(M=>e.jsx("button",{className:`filter-chip ${ke===M.label?"filter-chip-active":""}`,type:"button","aria-pressed":ke===M.label,onClick:()=>{A(M.label),Ge(!1)},children:M.label},M.label)),ea&&e.jsx("button",{className:`filter-chip ${ke===""?"filter-chip-active":""}`,type:"button","aria-pressed":ke==="",onClick:()=>{A(""),Ge(!1)},children:"No location"}),La.length>1&&ke===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${Ve?"filter-chip-active":""}`,type:"button","aria-pressed":Ve,onClick:()=>Ge(M=>!M),title:"Side-by-side location comparison",children:"Compare"})]}),gt.evidenceLoading||gt.evidenceError?e.jsxs(e.Fragment,{children:[jr&&e.jsx(wc,{actions:jr}),eo,gt.evidenceLoading?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading query evidence…"}):e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load query evidence."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{gt.refetch()},children:"Retry"})]})]}):e.jsx(lx,{evidence:$a,compareLocations:Ve,providerSelection:be,onProviderSelectionChange:Ke,addedQueries:s.movementComparison.addedQueries,actions:jr,actionPanel:eo})]}),!ie()&&e.jsx("div",{className:"page-section-divider",children:e.jsx(fg,{runs:s.recentRuns,collapsed:!0})})]}),report:Kt,reportState:Es,onOpenSetup:ie()?void 0:()=>{m({to:"/projects/$projectName/portfolio",params:{projectName:j}})},onRetryReport:()=>{ve===2?Promise.all([ut.refetch(),it.refetch()]):it.refetch()},onViewChange:M=>{It({scope:M.scope,...M.groupKey?{groupKey:M.groupKey}:{},queryClass:M.queryClass,...M.search?.trim()?{search:M.search.trim()}:{}})},onLoadMore:M=>{M===an?.properties.nextCursor&&ut.fetchNextPage()},onPropertyExpand:()=>{He&&it.isError&&it.refetch(),R(!0)},onRetryEvidence:()=>{it.refetch()},isViewLoading:ut.isPlaceholderData,isLoadingMore:ut.isFetchingNextPage,isLoadMoreError:ut.isFetchNextPageError,viewSearch:Pe.search??""},`${j}:${Tt}`)),!xt&&S.measurementScope==="project"?e.jsxs("details",{className:"visibility-disclosure",onToggle:M=>{M.currentTarget.open&&d()},children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Project signals"})}),!c||l?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading project signals…"}):i?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load project signals."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsx(Jb,{insights:s.insights,suggestedQueries:s.suggestedQueries,onManageQueries:ie()?void 0:()=>{m({to:"/projects/$projectName/queries",params:{projectName:j},search:M=>({...M,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]},j):null,Zi!==null?e.jsxs("details",{className:`visibility-disclosure${xt?" page-section-divider":""}`,open:E,onToggle:M=>vs(M.currentTarget.open?j:null),children:[e.jsx("summary",{className:"visibility-disclosure-summary",children:e.jsx("span",{className:"visibility-disclosure-label",children:"Competitor history"})}),e.jsx("div",{className:"visibility-disclosure-panel",children:Zi})]}):null]}):K==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(Eb,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(M,fe)=>{await Rt(M,fe)},onRefresh:()=>{n()}}),e.jsx(Ob,{project:s.project,onSave:async M=>{await Rt(s.project.name,M)}}),e.jsx(Kb,{project:s.project,onSave:async M=>{await Rt(s.project.name,{siteAuditMaxPages:M})}},s.project.id),x&&!ie()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Advanced measurement"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Measure individual properties, locations, or site sections with separate query sets."}),Xn==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):Xn==="error"?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:"Could not load advanced measurement setup."}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{v.refetch()},children:"Retry"})]}):e.jsx(P,{type:"button",variant:"outline",onClick:()=>{m({to:"/projects/$projectName/portfolio",params:{projectName:j}})},children:nd(Vt.setupAction)})]}):null,e.jsx(_b,{projectName:s.project.name}),e.jsx(Bb,{projectName:s.project.name}),x&&!ie()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-negative-400",children:"Delete project"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Permanently deletes this project and all its queries, competitors, runs, and snapshots."}),L?e.jsxs(je,{className:"surface-card p-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(P,{type:"button",variant:"destructive",disabled:ee,onClick:Ze(H),children:ee?"Deleting...":"Yes, delete project"}),e.jsx(P,{type:"button",variant:"outline",disabled:ee,onClick:()=>D(!1),children:"Cancel"})]})]}):e.jsxs(Ye,{type:"button",variant:"outline",onClick:()=>D(!0),children:[e.jsx(cc,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):K==="queries"||K==="discovery"?e.jsx(pf,{projectName:j,queryWorkspace:Y,onQueryWorkspaceChange:M=>we({queryWorkspace:M,trackingQueryId:void 0}),researchMode:$.researchMode==="test"?"test":"find",onResearchModeChange:M=>we({researchMode:M}),selection:S,onSelectionChange:we,trackingQueryId:typeof $.trackingQueryId=="string"?$.trackingQueryId:void 0,onTrackingQueryIdChange:M=>we({trackingQueryId:M})}):K==="technical-aeo"?e.jsx(Dh,{projectName:s.project.name,projectId:s.project.id,initialRunId:$.siteHealthRunId,onReleaseInitialRun:me}):K==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(Sy,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(dy,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):K==="history"?e.jsx(Kf,{projectName:s.project.name}):K==="activity"?e.jsx(wx,{projectName:s.project.name}):K==="backlinks"?e.jsx(lg,{projectName:s.project.name}):K==="local"?e.jsx(Fx,{projectName:s.project.name,projectId:s.project.id}):K==="search-console"?e.jsx(Wb,{projectName:s.project.name}):null]})}export{xv as ProjectPage,Xb as ProjectSubnav,Vb as ProjectSweepConfirmation,zb as patchProjectDashboardCache};
|