@ainyc/canonry 5.2.1 → 5.3.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/README.md +2 -2
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +1 -0
- package/assets/assets/{AuditHistoryPanel-CkBLHz2H.js → AuditHistoryPanel-D5cOFMKE.js} +1 -1
- package/assets/assets/{BacklinksPage-D2YWJUf9.js → BacklinksPage-BiOj8ztV.js} +1 -1
- package/assets/assets/{HistoryPage-C9j3RzMN.js → HistoryPage-DDBCwooU.js} +1 -1
- package/assets/assets/MeasurementPropertyPage-CMoU2yA_.js +1 -0
- package/assets/assets/ProjectPage-CrFybBls.js +8 -0
- package/assets/assets/{RunRow-DTJuJ8mb.js → RunRow-BLBAwIot.js} +1 -1
- package/assets/assets/{RunsPage-CdKorpOj.js → RunsPage-BVgBbE1M.js} +1 -1
- package/assets/assets/{SettingsPage-BOjZh2vW.js → SettingsPage-DYtN-1_-.js} +1 -1
- package/assets/assets/{SiteHealthSection-D7sPztpW.js → SiteHealthSection-ElUwcAS4.js} +3 -3
- package/assets/assets/{TrafficPage-BCodKdgN.js → TrafficPage-D6QT_2hU.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-D_zueOK5.js → TrafficSourceDetailPage-BnLzF82w.js} +1 -1
- package/assets/assets/{extract-error-message-BZYGBapN.js → extract-error-message-DIzjGZxl.js} +1 -1
- package/assets/assets/{index-aZ69fB-u.js → index-CoQVOsWw.js} +3 -3
- package/assets/assets/{react-sigma_core.esm.min-m72qsd73.js → react-sigma_core.esm.min-DTbIcdn4.js} +1 -1
- package/assets/assets/v2-overview-adapter-B_N4ilQV.js +1 -0
- package/assets/assets/{vendor-lucide-D_WBzb76.js → vendor-lucide-nVpYViBH.js} +1 -1
- package/assets/index.html +2 -2
- package/dist/{chunk-AGUCTX7L.js → chunk-HOOU4NS2.js} +194 -56
- package/dist/{chunk-5VONCLVQ.js → chunk-MNUFMEAX.js} +1 -1
- package/dist/{chunk-YQNKULAD.js → chunk-QAGZWYPI.js} +815 -366
- package/dist/cli.js +6 -6
- package/dist/{demo-server-BIPT53EY.js → demo-server-Y7YWLPU7.js} +2 -2
- package/dist/index.js +3 -3
- package/dist/{intelligence-service-SJO5E7WN.js → intelligence-service-PR6T6JKY.js} +1 -1
- package/package.json +8 -8
- package/assets/assets/MeasurementPropertyPage-Ci3CUr7Q.js +0 -1
- package/assets/assets/ProjectPage-Bdq_KTXX.js +0 -8
- package/assets/assets/v2-overview-adapter-BgsdlByS.js +0 -1
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{j as e,r as l,u as Te,L as As,h as xs,o as Pt,B as ai,C as el,D as gc,k as fc,l as yc}from"./vendor-tanstack-ZXXkndVj.js";import{T as ce,t as bc,a as vc,M as tl,I as Ve,s as sl,B as R,b as jc,u as nl,C as Nc,P as En,h as wc,c as Sc,d as gn,g as al,e as rl,f as pe,i as H,j as oe,k as Ms,l as Ct,m as He,n as Cc,o as kc,p as Ac,q as il,r as Pc,v as Rc,w as wn,S as fn,x as Ic,y as Tc,z as Bs,A as Ht,D as $c,E as Ci,F as ol,G as Ft,H as ri,J as Mc,K as Lc,L as qc,N as Ec,O as ki,Q as $e,R as Dc,U as Oc,V as tr,W as Fc,X as Kc,Y as Gc,Z as _c,_ as Uc,$ as Bc,a0 as Vc,a1 as Qc,a2 as zc,a3 as Wc,a4 as Hc,a5 as Yc,a6 as Jc,a7 as Xc,a8 as Zc,a9 as ll,aa as Xs,ab as ed,ac as cl,ad as Ka,ae as td,af as Je,ag as sd,ah as nd,ai as ad,aj as Ga,ak as rd,al as id,am as od,an as bn,ao as ld,ap as cd,aq as dd,ar as dl,as as Kr,at as ud,au as ii,av as md,aw as aa,ax as Zs,ay as Kt,az as hd,aA as xd,aB as pd,aC as sr,aD as Tt,aE as gd,aF as fd,aG as yd,aH as bd,aI as vd,aJ as sa,aK as Ai,aL as va,aM as nr,aN as jd,aO as Nd,aP as Pi,aQ as ar,aR as yn,aS as wd,aT as ul,aU as ml,aV as Sd,aW as Cd,aX as Ri,aY as kd,aZ as Ad,a_ as Pd,a$ as Rd,b0 as Id,b1 as Td,b2 as $d,b3 as Md,b4 as Ld,b5 as qd,b6 as Ed,b7 as Dd,b8 as Od,b9 as Fd,ba as Kd,bb as Gd,bc as _d,bd as Ud,be as Bd,bf as Vd,bg as Qd,bh as zd,bi as Wd,bj as Hd,bk as Yd,bl as Jd,bm as Xd,bn as Zd,bo as Ns,bp as eu,bq as gt,br as tu,bs as su,bt as nu,bu as au,bv as ru,bw as iu,bx as ou,by as lu,bz as cu,bA as du,bB as uu,bC as mu,bD as hu,bE as xu,bF as pu,bG as gu,bH as fu,bI as yu,bJ as bu,bK as vu,bL as ju,bM as Nu,bN as wu,bO as Ii,bP as Ti,bQ as $i,bR as Su,bS as Cu,bT as ku,bU as Au,bV as Pu,bW as Ru,bX as Iu,bY as Tu,bZ as $u,b_ as Mu,b$ as Lu,c0 as qu,c1 as Eu,c2 as Du,c3 as Ou,c4 as Fu,c5 as Ku,c6 as Gu,c7 as _u,c8 as Uu,c9 as hl,ca as rr,cb as Bu,cc as Mi,cd as Vu,ce as Qu,cf as zu,cg as Wu,ch as Hu,ci as Yu,cj as Ju,ck as xl,cl as Xu,cm as pl,cn as gl,co as fl,cp as yl,cq as Zu,cr as em,cs as tm,ct as sm,cu as nm,cv as am,cw as Li,cx as rm,cy as im,cz as om,cA as lm,cB as cm,cC as qi,cD as dm,cE as um,cF as mm,cG as hm,cH as xm,cI as pm,cJ as _a,cK as gm,cL as ir,cM as fm,cN as ym,cO as bm,cP as vm,cQ as jm,cR as Nm,cS as wm,cT as Sm,cU as Cm,cV as km,cW as bl,cX as Am,cY as Pm,cZ as Rm,c_ as Im,c$ as Tm,d0 as $m,d1 as ja,d2 as Mm,d3 as Lm,d4 as qm,d5 as Ei,d6 as Em}from"./index-aZ69fB-u.js";import{C as vn,f as Ua,r as ra,U as Dm,s as Om,L as Fm,t as Km,k as Gm,P as Ba,D as vl,u as _m,v as jl,w as Um,e as Bm,E as Vm,q as Qm,x as zm,y as Nl}from"./vendor-lucide-D_WBzb76.js";import{R as Wm}from"./RunRow-DTJuJ8mb.js";import{u as jn,D as Hs,a as Ls,b as wl,M as Da,c as Ps,S as Hm}from"./SiteHealthSection-D7sPztpW.js";import{C as ia,f as Nn,a as ms,b as Lt,c as Gt,d as ns,e as it,g as hs,h as qs,M as Sl,i as Cl,o as Es,j as Ys,p as Ym}from"./ChartPrimitives-Bxa_vFmq.js";import{u as Jm,a as Xm,b as Zm,t as eh,e as th,c as jt}from"./extract-error-message-BZYGBapN.js";import{R as en,C as tn,a as oa,X as sn,Y as nn,T as an,b as Gr,L as Va,A as Qs,d as $s,e as sh}from"./vendor-recharts-D-cUuLZo.js";import{A as kl,a as nh,b as ah,c as rh}from"./v2-overview-adapter-BgsdlByS.js";import{A as ih}from"./AuditHistoryPanel-CkBLHz2H.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B-Oq2NYq.js";import"./vendor-yaml-GWJz5H2G.js";function Js(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function oh(t,s,n=800){const a=[];if(!/^\d{4}-\d{2}-\d{2}$/.test(t)||!/^\d{4}-\d{2}-\d{2}$/.test(s))return a;for(let r=t;r<=s&&(a.push(r),!(a.length>=n));r=lh(r,1));return a}function lh(t,s){if(!Number.isFinite(s))return t;const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n?.[1]||!n[2]||!n[3])return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+Math.trunc(s)));if(Number.isNaN(a.getTime()))return t;const r=a.getUTCFullYear(),o=String(a.getUTCMonth()+1).padStart(2,"0"),i=String(a.getUTCDate()).padStart(2,"0");return`${r}-${o}-${i}`}function ch(t,s){if(!Number.isFinite(t)||!Number.isFinite(s)||s<=0)return null;const n=(t-s)/s;return Number.isFinite(n)?n:null}function dh(t,s){const n=ch(t,s);return n===null?null:Math.round(n*100)}function or(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Js(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Js(t.prior)} ${s})`:`Flat ${n} (${Js(t.prior)} ${s})`}const Al=30;function Di(t){return Math.round(t*10)/10}function uh(t){return t.prior>=Al&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Di(t.deltaAbs)} vs ${Di(t.prior)}`}function mh(t,s,n){return t.prior>=Al&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Js(Math.round(t.deltaAbs))} ${s} ${n}`}function hh(t,s="UTC"){const n=new Date(t);if(!Number.isFinite(n.getTime()))return null;const a={weekday:"short",year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"};try{return n.toLocaleString("en-US",{...a,timeZone:s})}catch{return n.toLocaleString("en-US",{...a,timeZone:"UTC"})}}const xh=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Pl(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Rl(t){return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function Il(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Pl).map(Rl).filter(Boolean)):new Set}function Tl(t,s){const n=Pl(t).map(Rl).filter(Boolean).filter(a=>!xh.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function ph(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function gh(t,s){const n=Il(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,r=[];for(const o of s){if(o.category!=="content"){r.push(o);continue}const i=Tl(ph(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function fh(t){const s=Il(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=Tl(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const yh=1e6;function bh(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/yh)}const oi={queryClass:"all"},vh=["all","non-brand","branded"];function $l(t){return typeof t=="string"&&vh.includes(t)}function Ml(t){const s=$l(t.class)?t.class:oi.queryClass,n=t.scope;if(typeof n!="string"||n==="all"||n.length===0)return{scope:"all",queryClass:s};const a=n.startsWith("group:")?n.slice(6):"";return a?{scope:"group",groupKey:a,queryClass:s}:{scope:"all",queryClass:s}}function jh(t,s){return s===null||t===null?!1:t!==s}function Nh(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===oi.queryClass?void 0:t.queryClass}}function wh(t,s){if(!(typeof t!="string"||t.length>16384||!s))try{const n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return;const a=n,r=i=>typeof i=="string"&&i.trim().length>0,o=i=>i===null||r(i);return a.queryKey!==s||!r(a.provider)||a.queryClass!=="branded"&&a.queryClass!=="non-brand"&&a.queryClass!=="unknown"||!o(a.model)||!o(a.location)||!o(a.runId)||a.revision!==null&&(typeof a.revision!="number"||!Number.isSafeInteger(a.revision)||a.revision<=0)?void 0:{queryKey:s,queryClass:a.queryClass,provider:a.provider,model:a.model,location:a.location,runId:a.runId,revision:a.revision}}catch{return}}function Sh(t){const s=h=>typeof t[h]=="string"&&t[h]!==""?t[h]:void 0,n=Ml({scope:s("scope"),class:s("class")}),a=s("measurementScope")??(n.scope==="group"?"group":"project"),r=s("measurementScopeKey")??(s("measurementScope")?void 0:n.groupKey),o=s("queryClass")??s("class"),i={measurementScope:r&&(a==="group"||a==="market"||a==="property")?a:"project",queryClass:o==="unknown"||$l(o)?o:oi.queryClass};i.measurementScope!=="project"&&(i.measurementScopeKey=r);for(const[h,m]of[["measurementMarketKey","marketKey"],["measurementProvider","provider"],["measurementModel","model"],["measurementLocation","location"],["measurementFrom","from"],["measurementTo","to"],["measurementRunId","measurementRunId"],["measurementQueryKey","queryKey"]]){const u=s(h);u!==void 0&&(i[m]=u)}const d=Number(t.measurementRevision);Number.isSafeInteger(d)&&d>0&&(i.revision=d);const c=wh(t.measurementAnswer,i.queryKey);return c&&(i.answer=c),i}function Ch(t,s){const n={...t,...s};return["measurementScope","measurementScopeKey","measurementMarketKey","queryClass","measurementProvider","measurementModel","measurementLocation","measurementFrom","measurementTo","measurementRevision","measurementRunId"].some(a=>a in s)?(n.measurementQueryKey=s.measurementQueryKey,n.measurementAnswer=s.measurementAnswer):"measurementQueryKey"in s&&!("measurementAnswer"in s)&&(n.measurementAnswer=void 0),"measurementScope"in s&&(n.scope=void 0,"measurementMarketKey"in s||(n.measurementMarketKey=void 0),n.measurementQueryKey=void 0,s.measurementScope==="project"&&(n.measurementScopeKey=void 0)),"queryClass"in s&&(n.class=void 0),n}function _r({state:t,label:s}){return e.jsx(ce,{tone:vc(t),children:s??bc(t)})}const cn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Oi={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},kh={"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."},Ah="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Ph(t,s){if(s.unavailable)return{headline:"No data",numeric:!1,detail:"could not load, refresh to retry",showRows:!1};if(s.noRun)return{headline:"No data",numeric:!1,detail:"no sweep has run yet",showRows:!1};if(t.snapshotsTotal===0)return 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};if(t.snapshotsWithAnswerText===0)return{headline:"No answers",numeric:!1,detail:"no answer text in this run",showRows:!1};if(!s.hasCompetitors)return{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1};const n=t.projectMentionSnapshots+t.competitorMentionSnapshots;return n===0||t.score===null?{headline:"No mentions",numeric:!1,detail:`no brand named in ${t.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:`${t.score}`,numeric:!0,detail:`${t.projectMentionSnapshots} of ${n} brand mentions`,showRows:!0}}function Rh({breakdown:t,projectLabel:s,competitorDomains:n}){const a=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(a===0)return null;const r=new Map(t.perCompetitor.map(i=>[i.domain,i.mentionSnapshots])),o=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...n.map(i=>({label:i,mentions:r.get(i)??0,isYou:!1}))].sort((i,d)=>d.mentions-i.mentions||(i.label<d.label?-1:1));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(Ve,{text:Ah})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:o.map(i=>{const d=i.mentions/a*100;return e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${i.isYou?"text-heading font-medium":"text-secondary"}`,children:i.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${i.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${d>0?Math.max(d,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:i.mentions}),e.jsxs("td",{className:"mention-share-share",children:[d.toFixed(1),"%"]})]},i.label)})})]})}function Ih({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=l.useState("non-brand"),o=l.useId(),i=t.scope==="pooled",d=!i&&t.branded.snapshotsTotal>0,c=d?a:"non-brand",h=i?"pooled":c,m=c==="branded"?t.branded:t.breakdown,u=c==="branded"?t.breakdown:t.branded,y=Ph(m,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:u.snapshotsTotal>0}),p=h==="non-brand"?tl[t.tone]:"text-secondary";function x(g){const f=cn.findIndex(N=>N.value===c);let S=null;g.key==="ArrowRight"||g.key==="ArrowDown"?S=(f+1)%cn.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?S=(f-1+cn.length)%cn.length:g.key==="Home"?S=0:g.key==="End"&&(S=cn.length-1),S!==null&&(g.preventDefault(),r(cn[S].value),g.currentTarget.querySelectorAll('[role="radio"]')[S]?.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:o,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Ve,{text:kh[h]})]}),d?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:x,children:cn.map(g=>{const f=g.value===c;return e.jsx("button",{type:"button",role:"radio","aria-checked":f,tabIndex:f?0:-1,onClick:()=>r(g.value),className:`segmented-option min-h-11 ${f?"segmented-option-active":""}`,children:g.label},g.value)})}):e.jsx("span",{className:"mention-share-class",children:Oi[h]})]}),y.numeric?e.jsxs("p",{className:`mention-share-value ${p}`,children:[y.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:y.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:Oi[h]}),` · ${y.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),y.showRows&&e.jsx(Rh,{breakdown:m,projectLabel:s,competitorDomains:n})]})}const dn=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Fi=5;function Th(t){switch(t){case"non-brand":return"Counts queries that do not name your brand.";case"branded":return"Counts queries that name your brand.";default:return"Counts every tracked query, so share of voice is not shown."}}function $h(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function lr(t){return t==="unavailable"?"Unavailable":"Not measured"}function Ll(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 Mh({value:t,onChange:s}){function n(a){const r=dn.findIndex(d=>d.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%dn.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+dn.length)%dn.length:a.key==="Home"?o=0:a.key==="End"&&(o=dn.length-1),o===null)return;a.preventDefault();const i=dn[o];s(i.value),a.currentTarget.querySelectorAll('[role="radio"]')[o].focus()}return e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"block text-sm font-medium text-heading",children:"History"}),e.jsx("div",{role:"radiogroup","aria-label":"Competitor history window",className:"segmented",onKeyDown:n,children:dn.map(a=>{const r=a.value===t;return e.jsx("button",{type:"button",role:"radio","aria-checked":r,tabIndex:r?0:-1,onClick:()=>s(a.value),className:`segmented-option min-h-11 ${r?"segmented-option-active":""}`,children:a.label},a.value)})})]})}function Ur({row:t,isProject:s=!1,metricState:n="measured",shareContext:a,canManage:r,onPin:o,onUnpin:i}){const d=!s&&r&&!t.pinned&&!!o,c=!s&&r&&t.pinned&&!!i,h=n==="measured",m=h&&t.sampleUrls.length>0,[u,y]=l.useState(!1),[p,x]=l.useState(null);async function g(f,S){if(!(!S||u)){y(!0),x(null);try{await S(t.domain)===!1&&x(`Could not ${f} competitor. Try again.`)}catch{x(`Could not ${f} competitor. Try again.`)}finally{y(!1)}}}return e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"font-medium text-heading",children:[t.label,s?e.jsx("span",{className:"ml-1 text-secondary",children:"(you)"}):null]}),e.jsx("td",{className:"text-secondary",children:s?"Your brand":Ll(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:h?jc(t.shareOfVoice,a):lr(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.mentionCount:lr(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.citationCount:lr(n)}),e.jsx("td",{className:"text-right",children:d||c||m?e.jsxs("div",{className:"flex min-w-max items-start justify-end gap-2",children:[m?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.sampleUrls.map(f=>e.jsx("li",{className:"break-all",children:f},f))})]}):null,c&&i?e.jsxs(R,{type:"button",size:"sm",variant:"outline",disabled:u,onClick:()=>{g("unpin",i)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,d&&o?e.jsxs(R,{type:"button",size:"sm",variant:"outline",disabled:u,onClick:()=>{g("pin",o)},children:["Pin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,p?e.jsx("span",{role:"alert",className:"sr-only",children:p}):null]}):e.jsx("span",{className:"text-faint",children:"—"})})]})}function Br({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function Lh({rows:t,shareContext:s,canManage:n,onPin:a}){const[r,o]=l.useState(!1),i=r?t:t.slice(0,Fi);return e.jsxs("tbody",{children:[e.jsx(Br,{children:"Observed in this window"}),i.map(d=>e.jsx(Ur,{row:{...d,pinned:!1},shareContext:s,canManage:n,onPin:a},d.domain)),t.length>Fi?e.jsx("tr",{children:e.jsx("td",{colSpan:6,children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-sm text-secondary",children:["Showing ",i.length," of ",t.length," observed competitors."]}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11 text-sm","aria-expanded":r,"aria-label":r?"Show fewer observed competitors":`Show all ${t.length} observed competitors`,onClick:()=>o(d=>!d),children:r?"Show fewer":`Show all ${t.length}`})]})})}):null]})}function qh({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,d]=l.useState(null);async function c(){const h=n.trim();if(!(!h||r)){o(!0),d(null);try{if(await t(h)===!1){d("Could not add competitor. Try again.");return}a("")}catch{d("Could not add competitor. Try again.")}finally{o(!1)}}}return e.jsxs("details",{className:"inline-disclosure competitor-landscape-manage",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:h=>{h.preventDefault(),c()},"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:h=>a(h.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(R,{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 Eh({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:d,onAddCompetitor:c,error:h,onRetry:m,isLoading:u=!1,scopeLabel:y}){const p=a&&!r,x=s?.pinned??n,g=s?.observed??[],f=s?.otherSources??[],S=s?.evidence,N=$h(s),E=s?.marketState?.draft?.pendingCompetitorDomains.length??0;return e.jsxs("section",{"aria-labelledby":"competitor-landscape-title","aria-busy":u,className:"competitor-landscape",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{id:"competitor-landscape-title",children:"Competitor landscape"}),y?e.jsx("p",{className:"supporting-copy mt-1",children:y}):null,s?e.jsx("p",{className:"supporting-copy mt-1",children:Th(s.filters?.queryClass)}):null,s?.reason?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:sl(s.reason)}):null]}),e.jsx(Mh,{value:t,onChange:o})]}),h?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:h}),m?e.jsx(R,{type:"button",size:"sm",variant:"outline",onClick:m,children:"Retry competitor history"}):null]}):null,u&&!s&&x.length===0?e.jsx("div",{role:"status","aria-live":"polite",className:"h-48 animate-pulse rounded-md bg-surface-subtle",children:e.jsx("span",{className:"sr-only",children:"Loading competitor history"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table","aria-label":"Competitor landscape",children:[e.jsx("caption",{className:"sr-only",children:"Pinned competitors followed by competitors observed in the selected history window."}),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:"Share of voice"}),e.jsx("th",{scope:"col",children:"Mentions"}),e.jsx("th",{scope:"col",children:"Citations"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsxs("tbody",{children:[s?e.jsxs(e.Fragment,{children:[e.jsx(Br,{children:"You"}),e.jsx(Ur,{row:s.project,shareContext:s,isProject:!0,metricState:N,canManage:!1})]}):null,e.jsx(Br,{children:"Pinned"}),x.length>0?x.map(A=>e.jsx(Ur,{row:{...A,pinned:!0},shareContext:s,metricState:N,canManage:p,onUnpin:d},A.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s&&g.length>0?e.jsx(Lh,{shareContext:s,rows:g,canManage:p,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),S?e.jsxs("details",{className:"group text-sm text-secondary",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer list-none flex-wrap items-center justify-between gap-x-4 gap-y-1 rounded-md hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500 [&::-webkit-details-marker]:hidden",children:[e.jsxs("span",{className:"flex flex-wrap items-center gap-x-4 gap-y-1",children:[e.jsxs("span",{children:[S.answeredResults," ",S.answeredResults===1?"answer":"answers"]}),S.missingAnswerTextResults>0?e.jsx("span",{className:"text-caution",children:"Answer data incomplete"}):null,S.incompleteSourceResults>0?e.jsx("span",{className:"text-caution",children:"Citation data incomplete"}):null]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:["About these results",e.jsx(vn,{size:14,"aria-hidden":"true",className:"transition-transform group-open:rotate-180 motion-reduce:transition-none"})]})]}),e.jsxs("div",{className:"max-w-prose space-y-2 pb-2 pt-1",children:[g.length===0?e.jsx("p",{children:"No additional competitors were identified in this period."}):null,e.jsxs("p",{children:[S.sourceResults," ",S.sourceResults===1?"result includes":"results include"," source URLs."]}),S.missingAnswerTextResults>0?e.jsxs("p",{children:[S.missingAnswerTextResults," ",S.missingAnswerTextResults===1?"result has":"results have"," no answer text and ",S.missingAnswerTextResults===1?"is":"are"," excluded from mention share."]}):null,S.incompleteSourceResults>0?e.jsxs("p",{children:[S.incompleteSourceResults," ",S.incompleteSourceResults===1?"result has an incomplete source list":"results have incomplete source lists",". Recorded citations still count; missing citations are not treated as confirmed misses."]}):null,S.excludedProbeResults+S.excludedNonCompletedResults>0?e.jsxs("p",{children:[S.excludedProbeResults+S.excludedNonCompletedResults," test or unfinished ",S.excludedProbeResults+S.excludedNonCompletedResults===1?"result is":"results are"," excluded."]}):null,s.truncated?e.jsx("p",{children:"Lists include up to 100 observed competitors and 100 other sources. All pinned competitors are included."}):null]})]}):null,E>0?e.jsx("p",{className:"text-sm text-secondary",children:s?.scope.kind==="all-markets"?`${E} competitor${E===1?" is":"s are"} pending publication across markets.`:`${E} competitor${E===1?" is":"s are"} pending publication for this market.`}):null,(s?.observedNames?.length??0)>0?e.jsxs("details",{className:"inline-disclosure text-sm text-secondary",children:[e.jsx("summary",{children:"Names observed in answers"}),e.jsx("p",{children:"Names are observations. Only classified competitor domains enter share of voice."}),e.jsx("ul",{children:s?.observedNames?.map(A=>e.jsxs("li",{children:[A.name," · ",A.answerCount," answers"]},A.name))})]}):null,f.length>0?e.jsxs("details",{className:"inline-disclosure",children:[e.jsxs("summary",{children:["Other observed sources (",f.length,")"]}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:f.map(A=>e.jsxs("li",{children:[e.jsxs("span",{children:[A.label," · ",Ll(A.surfaceClass)," · ",A.citationCount," citations"]}),A.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:A.sampleUrls.map(v=>e.jsx("li",{className:"break-all",children:v},v))}):null]},A.domain))})]}):null]}),p&&c?e.jsx(qh,{onAddCompetitor:c}):null]})}function Ki({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},r={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},o=n.length-1,i=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),d=new Date(n[o].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=n.map((h,m)=>{const u=new Date(h.createdAt).toLocaleDateString();return`${m===o?"Latest run, ":""}${u}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${c}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,m)=>{const u=!!(h.model&&m>0&&n[m-1]?.model&&n[m-1].model!==h.model),y=m===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${u?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${y?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,u?"model changed":null,y?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[d," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function Vr(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const o=s.get(r.createdAt);o?o.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:o}])=>({runId:o,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const Dh=320;function Oh(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function Fh(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function Gi(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 _i(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 Ui(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const r=t[t.length-1].citationState,o=t[t.length-2].citationState;if(o!=="cited"&&r==="cited")return`Newly ${n}`;if(o==="cited"&&r!=="cited")return"Lost since last run";let i=0;for(let d=t.length-1;d>=0&&t[d].citationState===r;d--)i++;return r==="cited"?i<=1?`${a} in latest run`:`${a} for ${i} runs`:i<=1?`Not ${n} in latest run`:`Not ${n} across ${i} runs`}function Kh(t,s){return t.map(n=>ql(n,s))}function ql(t,s){return s==="citations"?t:{...t,citationState:Gi(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Gi(n,s)}))}}function Bi(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,o=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",d=o==="cited"||o==="emerging";return r==="lost"||o!==null&&d&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||o!==null&&!d&&i?{key:s,label:`New ${n}`,tone:"positive"}:o===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 Gh(t){const s=Vr(Kh(t,"mentions")),n=Vr(t);return[Bi(s,"mentions"),Bi(n,"citations")]}function _h({signal:t}){const s=t.tone==="positive"?"border-positive-500/25 bg-positive-500/10 text-positive":t.tone==="negative"?"border-negative-500/25 bg-negative-500/10 text-negative":t.tone==="pending"?"border-caution-500/20 bg-caution-500/10 text-caution":"border-mono-700/60 bg-bg-elevated/70 text-secondary";return e.jsx("span",{className:`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium leading-none ${s}`,children:t.label})}function Vi({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Gh(t).map(s=>e.jsx(_h,{signal:s},s.key))})}function Uh({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=nl(),[r,o]=l.useState(new Set),[i,d]=l.useState("mentions"),[c,h]=l.useState(n),[m,u]=l.useState("all"),y=l.useMemo(()=>{const v=new Map;for(const w of t){const j=w.query,L=w.queryClass??null,q=s?w.location??null:null,D=JSON.stringify([j,L,q]),X=v.get(D)??{key:D,phrase:j,queryClass:L,location:q,items:[],rawItems:[]};X.items.push(ql(w,i)),X.rawItems.push(w),v.set(D,X)}return[...v.values()]},[t,i,s]),p=l.useMemo(()=>y.filter(v=>m==="all"||(m==="unclassified"?v.queryClass===null:v.queryClass===m)),[y,m]),x=jn({rows:p,getSearchText:Fh}),g=x.rows.map(v=>v.key),f=g.length>0&&g.every(v=>r.has(v)),S=v=>{o(w=>{const j=new Set(w);return j.has(v)?j.delete(v):j.add(v),j})},N=i==="mentions"?"mentioned":"cited",E=i==="mentions"?"Mention History":"Citation History",A=i==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":i==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>d("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":i==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>d("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:i==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{o(v=>{const w=new Set(v);for(const j of g)f?w.delete(j):w.add(j);return w})},children:f?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),y.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(Hs,{value:x.query,onChange:x.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"w-full max-w-md"}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-secondary",children:["Query class",e.jsxs("select",{value:m,onChange:v=>{u(v.target.value),x.setPage(1)},className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",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.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:E}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:x.rows.map(({key:v,phrase:w,queryClass:j,location:L,items:q,rawItems:D})=>{const X=r.has(v),G=q.map(z=>z.citationState),K=G.includes("cited")?"cited":G.includes("emerging")?"emerging":G.includes("lost")?"lost":G.every(z=>z==="pending")?"pending":"not-cited",Q=Vr(q),C=q.filter(z=>z.citationState===Nc.cited||z.citationState==="emerging").length,te=Ui(Q,i);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>S(v),onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),S(v))},tabIndex:0,role:"button","aria-expanded":X,children:[e.jsx("td",{children:e.jsx(Ua,{size:14,className:`transition-transform duration-150 text-muted ${X?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:w}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:L??"No location"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.jsx(ce,{tone:"neutral",className:"whitespace-nowrap",children:Oh(j)}),q.map(z=>e.jsx(En,{provider:z.provider},z.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{state:K,label:_i(K,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${C} of ${q.length} engines ${A}`,children:[C,"/",q.length]})]})}),e.jsx("td",{children:e.jsx(Ki,{history:Q})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:te}),e.jsx(Vi,{items:D})]}),e.jsx("td",{})]}),X&&q.map((z,Y)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(En,{provider:z.provider})}),e.jsx("td",{children:e.jsx(_r,{state:z.citationState,label:_i(z.citationState,i)})}),e.jsx("td",{children:e.jsx(Ki,{history:z.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:Ui(z.runHistory,i)}),e.jsx(Vi,{items:[D[Y]??z]})]}),e.jsx("td",{children:e.jsx(R,{variant:"ghost",size:"sm",type:"button",onClick:V=>{V.stopPropagation(),a(z.id)},children:"View"})})]}),c==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Qh,{item:z,onViewFull:()=>a(z.id)})})]})]},z.id))]},v)})})]})}),x.totalRows===0&&(x.hasQuery||m!=="all")?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ls,{page:x.page,pageSize:x.pageSize,visibleRows:x.rows.length,totalRows:x.totalRows,onPageChange:x.setPage,itemLabel:x.hasQuery||m!=="all"?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",N==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Bh(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=Sc(r);return o.length>=4?[o]:[]}),...t.recommendedCompetitors??[]].filter(r=>r.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function Qi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function Vh(t,s){if(t.length<=s)return{body:t,truncated:!1};const n=t.lastIndexOf(" ",s);return{body:`${t.slice(0,n>s-40?n:s).trimEnd()}…`,truncated:!0}}function Qh({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:r}=Vh(t.answerSnippet,Dh),o=Bh(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-neutral",children:wc(a,o)}),(t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(i=>e.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[11px] ${Qi(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,Qi(t,i)?" · competitor source":""]},`c-${i}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors in answer:"}),t.mentionedCompetitorDomains.slice(0,4).map(i=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:i},`co-${i}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:i=>{i.stopPropagation(),s()},children:"View full answer →"})]})}function Na({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 Ja({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:o=!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:o,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>n(i),children:r?r(i):i},i))})}const cr=it[0],dr=it[1],zi=it[2],Wi=it[3],zh=["both","server","ga4"],Hi={fontSize:11,paddingTop:6},Yi=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Ji=t=>typeof t=="number"?Js(Math.round(t)):String(t),os=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function ur(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,o)=>o<t.startIndex||o>t.endIndex?null:t.start+(o-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(Ve,{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 Wh(t,s){return n=>{const{cx:a,cy:r,index:o,key:i}=n,d=o??-1;return!(t[d]!=null&&t[d-1]==null&&t[d+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 Hh({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,d]=l.useState("both"),c=Jm(t,{sinceMinutes:s,granularity:"day",limit:1}),h=Xm(t),u=Te({...al({client:H,path:{name:t}}),enabled:!!t,staleTime:gn}).data?.connected===!0,y=Te({...rl({client:H,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&u,staleTime:gn}),p=l.useMemo(()=>c.data?.series?.points??[],[c.data]),x=l.useMemo(()=>{const L=y.data;return new Map((L?.days??[]).map(q=>[q.date,q.sessions]))},[y.data]),g=l.useMemo(()=>{const L=D=>D.measured!==!1;if(p.length===0||L(p[0]))return null;const q=p.findIndex(L)-1;return q<0?{from:p[0].bucket,to:p[p.length-1].bucket}:{from:p[0].bucket,to:p[q].bucket}},[p]),f=c.data?.series?.coverageStart??null,S=c.data?.series?.trends,N=l.useMemo(()=>{const L=ur(S?.crawlerContentHits,p.length),q=ur(S?.aiUserFetchHits,p.length),D=ur(S?.aiReferralLandedHits,p.length);return p.map((X,G)=>({...X,crawlerContentHits:X.measured!==!1?os(X.crawlerContentHits):null,aiUserFetchHits:X.measured!==!1?os(X.aiUserFetchHits):null,aiReferralLandedHits:X.measured!==!1?os(X.aiReferralLandedHits):null,ga4Visits:x.get(X.bucket)??null,crawlTrend:L[G],fetchTrend:q[G],visitTrend:D[G]}))},[p,x,S]),E=c.data?.totals,A=E&&{crawlers:os(E.crawlerContentHits),fetches:os(E.aiUserFetchHits),visits:os(E.aiReferralLandedHits)},v=l.useMemo(()=>p.reduce((L,q)=>({crawlers:L.crawlers+os(q.crawlerContentHits),fetches:L.fetches+os(q.aiUserFetchHits),visits:L.visits+os(q.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[p]),w=A??v,j=w.crawlers>0||w.fetches>0||w.visits>0;if(c.isLoading)return e.jsx(pe,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(c.isError)return e.jsxs(pe,{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(!j){const L=h.data?.sources,q=L!==void 0&&L.length===0,D=!q&&f===null;return e.jsxs(pe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:q?"No server-side traffic source connected yet.":D?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:q?"Connect a traffic source to see how AI engines read this site over time.":D?"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(pe,{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:Js(w.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:Js(w.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:Js(w.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."})]}),p.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:os(p[p.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:os(p[p.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:os(p[p.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:x.get(p[p.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(Ve,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:L=>a(L.target.checked),className:"accent-current"}),"Page fetches"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:L=>o(L.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(en,{width:"100%",height:206,children:e.jsxs(tn,{data:N,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(oa,{stroke:ia,vertical:!1}),e.jsx(sn,{dataKey:"bucket",tick:Lt,stroke:ms,tickFormatter:Nn,minTickGap:28}),e.jsx(nn,{tick:Lt,stroke:ms,width:48,allowDecimals:!1}),e.jsx(an,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:Gt,formatter:Ji}),g&&e.jsx(Gr,{x1:g.from,x2:g.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(Va,{wrapperStyle:Hi,iconType:"plainline",iconSize:14,formatter:L=>Yi.has(L)?"":L}),e.jsx(Qs,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:cr,fill:cr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Qs,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:dr,fill:dr,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx($s,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:cr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx($s,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:dr,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(Ve,{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(Ja,{windows:zh,value:i,onChange:d,label:"Visit measurement source",formatOption:L=>L==="ga4"?"GA4":L==="both"?"Both":"Server"})]}),e.jsx(en,{width:"100%",height:176,children:e.jsxs(tn,{data:N,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(oa,{stroke:ia,vertical:!1}),e.jsx(sn,{dataKey:"bucket",tick:Lt,stroke:ms,tickFormatter:Nn,minTickGap:28}),e.jsx(nn,{tick:Lt,stroke:ms,width:48,allowDecimals:!1}),e.jsx(an,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:Gt,formatter:Ji}),g&&e.jsx(Gr,{x1:g.from,x2:g.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(Va,{wrapperStyle:Hi,iconType:"plainline",iconSize:14,formatter:L=>Yi.has(L)?"":L}),i!=="ga4"&&e.jsx($s,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:zi,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx($s,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Wi,strokeWidth:1.8,strokeDasharray:"5 3",dot:Wh(N.map(L=>L.ga4Visits),Wi)}),r&&i!=="ga4"&&e.jsx($s,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:zi,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const Yh=6,Dn="__other__",Ln="_socialTotal";function Jh(t,s=Yh){const n=new Map;for(const m of t)n.set(m.source,(n.get(m.source)??0)+m.sessions);const a=[...n.entries()].sort((m,u)=>u[1]!==m[1]?u[1]-m[1]:m[0].localeCompare(u[0])),r=a.slice(0,s),o=new Set(r.map(([m])=>m)),i=Math.max(0,a.length-s),d=new Map;for(const m of t){let u=d.get(m.date);u||(u={date:m.date,[Ln]:0},d.set(m.date,u));const y=o.has(m.source)?m.source:Dn;u[y]=(u[y]??0)+m.sessions,u[Ln]=(u[Ln]??0)+m.sessions}const c=[...d.values()].sort((m,u)=>String(m.date).localeCompare(String(u.date))),h=r.map(([m])=>m);return i>0&&h.push(Dn),{data:c,sources:h,otherCount:i}}function qn(t){return t.replace(/\+/g," ")}function El(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Xi="_totalSessions",Zi="_organicSessions";function Xh(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Xi]:i.sessions,[Zi]:i.organicSessions});for(const i of t.days){let d=n.get(i.date);d||(d={[Xi]:0,[Zi]:0},n.set(i.date,d));for(const c of i.bySource)d[c.source]=(d[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([i],[d])=>i.localeCompare(d)).map(([i,d])=>({date:i,...d})),r=a.map(i=>i.date),o=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:o}}const Zh=["7d","30d","90d"],ex={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Vs=it,Qr=hs.textDim,Dl=hs.textFaint,Qn=25;function tx(t){return wl(t.landingPage)}const sx=25,nx=10,hr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function wa(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Ol(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 ax({projectName:t}){const{data:s,isLoading:n,isError:a}=Zm(t);if(n)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!oe()&&e.jsx(As,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(pe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!oe()&&e.jsxs(e.Fragment,{children:[e.jsx(As,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(pe,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(o=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:o.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ce,{tone:eh(o.status),children:o.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:o.lastSyncedAt?Ol(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:oe()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(As,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function rx({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(ax,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Ja,{windows:Zh,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(ix,{projectName:t,window:s}),e.jsx(Hh,{projectName:t,sinceMinutes:ex[s]})]})}function ix({projectName:t,window:s}){const n=xs(),a=s??"30d",[r,o]=l.useState(null),[i,d]=l.useState(null),[c,h]=l.useState(!0),[m,u]=l.useState(!1),[y,p]=l.useState(!1),[x,g]=l.useState(null),[f,S]=l.useState(null),[N,E]=l.useState("sessions"),[A,v]=l.useState("desc"),[w,j]=l.useState("sessions"),[L,q]=l.useState("desc"),[D,X]=l.useState("sessions"),[G,K]=l.useState("desc"),[Q,C]=l.useState("sessions"),[te,z]=l.useState("desc"),[Y,V]=l.useState(hr),[U,F]=l.useState([]),[T,ae]=l.useState([]),[I,Z]=l.useState(!1);async function se(ne){h(!0),g(null);try{const Ee=await n.fetchQuery({...al({client:H,path:{name:t}}),staleTime:gn});if(ne.current)return;if(o(Ee),!Ee.connected){d(null),V(hr),F([]),ae([]),h(!1);return}const Pe=a==="all"?void 0:a,Ae=await n.fetchQuery({...Cc({client:H,path:{name:t},query:Pe?{window:Pe}:void 0}),staleTime:gn}).then(lt=>lt),Yt=Ae.windowStart||Ae.windowEnd?{...Ae.windowStart?{startDate:Ae.windowStart}:{},...Ae.windowEnd?{endDate:Ae.windowEnd}:{}}:void 0,[Jt,_t,bt]=await Promise.all([n.fetchQuery({...rl({client:H,path:{name:t},query:Pe?{window:Pe}:void 0}),staleTime:gn}).catch(()=>hr),n.fetchQuery({...kc({client:H,path:{name:t},query:Pe?{window:Pe}:void 0}),staleTime:gn}).catch(()=>[]),n.fetchQuery({...Ac({client:H,path:{name:t},query:Yt}),staleTime:gn}).catch(()=>[])]);if(ne.current)return;d(Ae),V(Jt),F(_t),ae(bt),h(!1)}catch(Ee){if(ne.current)return;g(Ee instanceof Error?Ee.message:"Failed to load GA4 data"),h(!1)}}l.useEffect(()=>{const ne={current:!1};return se(ne),()=>{ne.current=!0}},[t,a,n]);async function de(){u(!0),g(null),S(null);try{const ne=await il(t);S(`Synced ${ne.rowCount.toLocaleString()} page rows, ${ne.aiReferralCount.toLocaleString()} AI and ${ne.socialReferralCount.toLocaleString()} social referral rows (${ne.days} days)`),await Ct(n,"ga"),await se({current:!1})}catch(ne){g(ne instanceof Error?ne.message:"Sync failed")}finally{u(!1)}}async function J(){p(!0),g(null),S(null);try{await Pc(t),await Ct(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),d(null),S("GA4 disconnected")}catch(ne){g(ne instanceof Error?ne.message:"Disconnect failed")}finally{p(!1)}}function ie(ne){B.setPage(1),N===ne?v(Ee=>Ee==="desc"?"asc":"desc"):(E(ne),v("desc"))}function ye(ne){w===ne?q(Ee=>Ee==="desc"?"asc":"desc"):(j(ne),q("desc"))}function ee(ne){D===ne?K(Ee=>Ee==="desc"?"asc":"desc"):(X(ne),K("desc"))}const me=l.useMemo(()=>i?.topPages?[...i.topPages].sort((ne,Ee)=>{const Pe=ne[N],Ae=Ee[N];return typeof Pe=="string"&&typeof Ae=="string"?A==="asc"?Pe.localeCompare(Ae):Ae.localeCompare(Pe):A==="asc"?Pe-Ae:Ae-Pe}):[],[i?.topPages,N,A]),B=jn({rows:me,getSearchText:ne=>wl(ne.landingPage),pageSize:nx}),xe=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((ne,Ee)=>{const Pe=ne[w],Ae=Ee[w];return typeof Pe=="string"&&typeof Ae=="string"?L==="asc"?Pe.localeCompare(Ae):Ae.localeCompare(Pe):L==="asc"?Pe-Ae:Ae-Pe}):[],[i?.aiReferrals,w,L]),Se=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((ne,Ee)=>{const Pe=ne[Q],Ae=Ee[Q];return typeof Pe=="string"&&typeof Ae=="string"?te==="asc"?Pe.localeCompare(Ae):Ae.localeCompare(Pe):te==="asc"?Pe-Ae:Ae-Pe}):[],[i?.aiReferralLandingPages,Q,te]),Ce=jn({rows:Se,getSearchText:tx,pageSize:sx}),tt=Ce.totalRows>0?`${Ce.totalRows.toLocaleString()} ${Ce.hasQuery?Ce.totalRows===1?"match":"matches":Ce.totalRows===1?"row":"rows"}`:Ce.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Qe(ne){Ce.setPage(1),Q===ne?z(Ee=>Ee==="desc"?"asc":"desc"):(C(ne),z("desc"))}const Ge=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((ne,Ee)=>{const Pe=ne[D],Ae=Ee[D];return typeof Pe=="string"&&typeof Ae=="string"?G==="asc"?Pe.localeCompare(Ae):Ae.localeCompare(Pe):G==="asc"?Pe-Ae:Ae-Pe}):[],[i?.socialReferrals,D,G]),{socialChartData:st,socialChartSources:qe,socialOtherCount:O}=l.useMemo(()=>{const ne=Jh(T);return{socialChartData:ne.data,socialChartSources:ne.sources,socialOtherCount:ne.otherCount}},[T]),{chartData:Le,chartSources:P,dateRange:ge}=l.useMemo(()=>{const ne=Xh(Y,U);return{chartData:ne.data,chartSources:ne.sources,dateRange:ne.dateRange}},[Y,U]);if(c&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return oe()||Ms()?e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(ox,{projectName:t,onConnected:()=>{(async()=>(await Ct(n,"ga"),await se({current:!1})))()}});const Oe=i?.organicSharePctDisplay??"0%",We=i?.channelBreakdown?.organic.sharePctDisplay??Oe,_e=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,he=i?.aiSessionsDeduped??0,xt=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,Ue=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Fe=i?.paidAiSessionsBySession??0,kt=i?.paidAiSharePctBySessionDisplay??"0%",Xe=i?new Set(i.aiReferrals.map(ne=>ne.source.toLowerCase())).size:0,ke=xe[0]??null,ot=i?.totalDirectSessions??0,ft=i?.directSharePctDisplay??"0%",qt=i?.channelBreakdown?.direct.sessions??ot,De=i?.channelBreakdown?.direct.sharePctDisplay??ft,k=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Ie=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",we=i?.socialSessions??0,ze=i?.socialSharePctDisplay??"0%",yt=i?.channelBreakdown?.social.sessions??we,nt=i?.channelBreakdown?.social.sharePctDisplay??ze,Rt=i?new Set(i.socialReferrals.map(ne=>ne.source.toLowerCase())).size:0,Ye=Ge[0]??null;return e.jsxs(e.Fragment,{children:[x&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:x}),f&&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:f}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!oe()&&!Ms()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",disabled:m,onClick:He(de),children:[e.jsx(ra,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(R,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:y,onClick:He(J),children:[e.jsx(Dm,{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(Ve,{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(xr,{value:wa(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(xr,{value:wa(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Oe} of total`,tone:"positive"}),e.jsx(xr,{value:i.totalUsers===null?"—":wa(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!oe()&&!Ms()&&e.jsxs(R,{variant:"outline",size:"sm",disabled:m,onClick:He(de),children:[e.jsx(ra,{className:`w-3.5 h-3.5 mr-1.5 ${m?"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(Ve,{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."})]})]}),ge&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(ge.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(ge.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),Le.length>0&&e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:P.length>0?"AI vs. total sessions":"All sessions (baseline)"}),P.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),P.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:Le,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(sn,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:ms},tickFormatter:Nn}),e.jsx(nn,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...ns,labelFormatter:Gt,formatter:(ne,Ee)=>{const Pe=typeof ne=="number"?ne.toLocaleString():String(ne??0),Ae=String(Ee??"");return Ae==="_totalSessions"?[Pe,"Total Sessions"]:Ae==="_organicSessions"?[Pe,"Organic Sessions"]:[Pe,Ae]}}),e.jsx(Va,{wrapperStyle:{fontSize:11,color:hs.text},formatter:ne=>ne==="_totalSessions"?"Total Sessions":ne==="_organicSessions"?"Organic Sessions":ne}),e.jsx(Qs,{type:"monotone",dataKey:"_totalSessions",stroke:hs.textFaint,fill:hs.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),P.map((ne,Ee)=>e.jsx(Qs,{type:"monotone",dataKey:ne,stackId:"ai",stroke:Vs[Ee%Vs.length],fill:Vs[Ee%Vs.length],fillOpacity:.4,strokeWidth:1.5},ne))]})})})]}),e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(gs,{label:"Organic",value:We,hint:`${_e.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions from Google organic search (sessionDefaultChannelGrouping = 'Organic Search'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(gs,{label:"Social",value:nt,hint:`${yt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(gs,{label:"Direct",value:De,hint:`${qt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(gs,{label:"Visitors from AI (at least)",value:Ue,hint:Fe>0?`${xt.toLocaleString()} sessions · ${Fe.toLocaleString()} paid`:`${xt.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(gs,{label:"Other channels",value:Ie,hint:`${k.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."})]}),ke&&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:ke.source})," via ",ke.medium,", accounting for ",ke.sessions.toLocaleString()," sessions.",Fe>0&&e.jsxs("span",{children:[" Paid AI: ",Fe.toLocaleString()," sessions (",kt,")."]})]})]}),e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${Xe} 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(ls,{label:"Source",sortKey:"source",current:w,dir:L,onSort:ye,align:"left"}),e.jsx(ls,{label:"Medium",sortKey:"medium",current:w,dir:L,onSort:ye,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(ls,{label:"Sessions",sortKey:"sessions",current:w,dir:L,onSort:ye,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:xe.map(ne=>e.jsx(cx,{referral:ne,totalSessions:he},`${ne.source}:${ne.medium}:${ne.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:tt})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{value:Ce.query,onChange:Ce.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Ce.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(ls,{label:"Landing Page",sortKey:"landingPage",current:Q,dir:te,onSort:Qe,align:"left"}),e.jsx(ls,{label:"Source",sortKey:"source",current:Q,dir:te,onSort:Qe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(ls,{label:"Sessions",sortKey:"sessions",current:Q,dir:te,onSort:Qe,align:"right"})]})}),e.jsx("tbody",{children:Ce.rows.map(ne=>e.jsx(dx,{row:ne},`${ne.landingPage}:${ne.source}:${ne.medium}:${ne.sourceDimension}`))})]})}),e.jsx(Ls,{page:Ce.page,pageSize:Ce.pageSize,visibleRows:Ce.rows.length,totalRows:Ce.totalRows,onPageChange:Ce.setPage,itemLabel:Ce.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:()=>Ce.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(Ve,{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(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(gs,{label:"Social Sessions",value:wa(we),hint:`${we.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(gs,{label:"Share of Traffic",value:ze,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(gs,{label:"Platforms",value:String(Rt),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."})]}),Ye&&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:`${Ye.source} via ${Ye.medium}`,children:El(qn(Ye.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Ye.medium,children:["via ",qn(Ye.medium)," · ",Ye.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(gs,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(gs,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(gs,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),st.length>0&&e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"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 ",qe.length-1," sources · ",O," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:st,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(sn,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:ms},tickFormatter:Nn}),e.jsx(nn,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...ns,labelFormatter:Gt,formatter:(ne,Ee)=>{const Pe=typeof ne=="number"?ne.toLocaleString():String(ne??0),Ae=String(Ee??"");if(Ae===Ln)return[Pe,"Total Social"];if(Ae===Dn){const Yt=`Other (${O} source${O===1?"":"s"})`;return[Pe,Yt]}return[Pe,qn(Ae)]}}),e.jsx(Qs,{type:"monotone",dataKey:Ln,stroke:Dl,fill:hs.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),qe.map((ne,Ee)=>{const Ae=ne===Dn?Qr:Vs[Ee%Vs.length];return e.jsx(Qs,{type:"monotone",dataKey:ne,stackId:"social",stroke:Ae,fill:Ae,fillOpacity:.4,strokeWidth:1.5},ne)})]})})}),e.jsx(mx,{sources:qe,otherCount:O})]}),e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Ge.length>Qn&&!I?`Top ${Qn} of ${Ge.length}`:`${Ge.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(ls,{label:"Source",sortKey:"source",current:D,dir:G,onSort:ee,align:"left"}),e.jsx(ls,{label:"Medium",sortKey:"medium",current:D,dir:G,onSort:ee,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(ls,{label:"Sessions",sortKey:"sessions",current:D,dir:G,onSort:ee,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(I?Ge:Ge.slice(0,Qn)).map(ne=>e.jsx(ux,{referral:ne,totalSessions:we},`${ne.source}:${ne.medium}:${ne.channelGroup}`))})]})}),Ge.length>Qn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>Z(ne=>!ne),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:I?`Show top ${Qn}`:`Show all ${Ge.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(Ve,{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(Hs,{value:B.query,onChange:B.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(ls,{label:"Landing Page",sortKey:"landingPage",current:N,dir:A,onSort:ie,align:"left"}),e.jsx(ls,{label:"Sessions",sortKey:"sessions",current:N,dir:A,onSort:ie,align:"right"}),e.jsx(ls,{label:"Organic",sortKey:"organicSessions",current:N,dir:A,onSort:ie,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:B.rows.map(ne=>e.jsx(lx,{page:ne},ne.landingPage))})]})}),B.totalRows===0&&B.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Ls,{page:B.page,pageSize:B.pageSize,visibleRows:B.rows.length,totalRows:B.totalRows,onPageChange:B.setPage,itemLabel:B.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 ${Ol(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function ox({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,d]=l.useState(null),[c,h]=l.useState(!1),[m,u]=l.useState(null),y=l.useRef(null),p=l.useCallback(g=>{const f=g.target.files?.[0];if(!f)return;u(null),o(f.name);const S=new FileReader;S.onload=()=>{const N=S.result;try{const E=JSON.parse(N);if(!E.client_email||!E.private_key){u("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),d(null);return}d(N)}catch{u("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),d(null)}},S.onerror=()=>{u("Failed to read file."),d(null)},S.readAsText(f)},[]);async function x(){if(u(null),!n.trim()){u("Property ID is required.");return}if(!i){u("Please upload a service account key file.");return}h(!0);try{await Rc(t,{propertyId:n.trim(),keyJson:i});try{await il(t)}catch{}s()}catch(g){u(g instanceof Error?g.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(pe,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),m&&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:m}),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:g=>a(g.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:y,type:"file",accept:".json,application/json",onChange:p,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>y.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(Om,{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(R,{variant:"default",size:"sm",disabled:c||!n.trim()||!i,onClick:He(x),children:c?"Connecting & syncing…":"Connect GA4"})]})}function ls({label:t,sortKey:s,current:n,dir:a,onSort:r,align:o}){const i=n===s;return e.jsx("th",{className:`py-1 ${o==="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 Fl={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function xr({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 ${Fl[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function gs({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Ve,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Fl[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function lx({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[s,"%"]})]})}const Kl={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Gl={session:"Detected via GA4 sessionSource (referrer or utm_source for this session)",first_user:"Detected via GA4 firstUserSource (referrer from the user's first-ever visit)",manual_utm:"Detected via GA4 sessionManualSource (explicit utm_source parameter for the session)"};function cx({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Kl[t.sourceDimension]??t.sourceDimension,r=Gl[t.sourceDimension]??"",o=t.trafficClass==="paid"?"Paid":"Organic",i=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:i,children:o})}),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:r,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function dx({row:t}){const s=Kl[t.sourceDimension]??t.sourceDimension,n=Gl[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(Da,{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 ux({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=qn(t.source),o=qn(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:r}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:o}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function mx({sources:t,otherCount:s}){const n=[{key:Ln,color:Dl,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Dn)n.push({key:Dn,color:Qr,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=qn(r);n.push({key:r,color:Vs[a%Vs.length]??Qr,label:El(o,32),tooltip:o})}}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 hx(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 xx="Search Console is not connected yet. Your Canonry team can set this up.",px=["7d","30d","90d","all"],Sa=500,eo=[{key:"clicks",label:"Clicks",color:it[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:it[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:qs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:it[2],inverted:!0,format:t=>t.toFixed(1)}],_s=25,gx="canonry:google-oauth-complete",fx=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function yx(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 c=t.prior[s],h=t.trailing[s];return c!==null&&h!==null&&c<=0&&h>0?`new in the last ${a}d`:c===null||c<=0?`no prior ${a}d to compare`:h===null?`no value in the last ${a}d`:"comparison unavailable"}if(r===0)return`→ no change vs prior ${a}d`;const o=Math.abs(r*100),i=o<.1?"<0.1%":`${fx.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function bx(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,o=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,d=`${r.startDate} to ${r.endDate}`,c=`Tile percentages compare these ${s} ${o} (${d}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?c:`${c} 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 to(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function so(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 no(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function vx({projectName:t,refreshNonce:s}){const n=xs(),{isAdmin:a}=wn(),r=Ms(),[o,i]=l.useState(!1),[d,c]=l.useState([]),[h,m]=l.useState([]),[u,y]=l.useState([]),[p,x]=l.useState(null),[g,f]=l.useState([]),[S,N]=l.useState([]),[E,A]=l.useState(null),[v,w]=l.useState(""),[j,L]=l.useState(""),[q,D]=l.useState("30"),[X,G]=l.useState(!1),[K,Q]=l.useState("30d"),[C,te]=l.useState(["clicks","impressions"]),[z,Y]=l.useState(!0),[V,U]=l.useState(null),[F,T]=l.useState(0),[ae,I]=l.useState({startDate:"",endDate:"",query:"",page:""}),[Z,se]=l.useState(0),[de,J]=l.useState(!1),[ie,ye]=l.useState(0),[ee,me]=l.useState(!1),[B,xe]=l.useState(""),[Se,Ce]=l.useState(!0),[tt,Qe]=l.useState(!1),[Ge,st]=l.useState(!1),[qe,O]=l.useState(!1),[Le,P]=l.useState(!1),[ge,Oe]=l.useState(!1),[We,_e]=l.useState(!1),[he,xt]=l.useState(null),[Ue,Fe]=l.useState(!1),[kt,Xe]=l.useState(!1),[ke,ot]=l.useState(null),[ft,qt]=l.useState(null),[De,k]=l.useState([]),[Ie,we]=l.useState(new Set),[ze,yt]=l.useState({}),[nt,Rt]=l.useState(new Set),[Ye,ne]=l.useState(""),[Ee,Pe]=l.useState(null),[Ae,Yt]=l.useState(""),[Jt,_t]=l.useState(!1),[bt,lt]=l.useState(!1),[Ut,as]=l.useState(!1),[Bt,Vt]=l.useState(!1),[mt,rs]=l.useState("indexed"),[Ze,Et]=l.useState(null),Qt=!!(ae.query.trim()||ae.page.trim()||Ze),fs=Ze!==null,ps=l.useMemo(()=>{if(!Ze)return u;const{key:b,dir:W}=Ze;return[...u].sort((ue,ve)=>{const et=b===fn.CTR?Number.isFinite(ue.ctr)?ue.ctr:0:ue[b],at=b===fn.CTR?Number.isFinite(ve.ctr)?ve.ctr:0:ve[b];return W==="asc"?et-at:at-et})},[u,Ze]),zt=jn({rows:ps,pageSize:Ps}),ys=ee?zt.rows:ps,Xt=jn({rows:(ke??[]).filter(b=>b.path.toLowerCase().includes(Ye.trim().toLowerCase())),pageSize:Ps}),[Nt,Zt]=l.useState([]),[vt,es]=l.useState(null),[bs,_]=l.useState(1),re=l.useMemo(()=>{if(Nt.length<2)return null;const b=Nt[Nt.length-1],W=Nt[Nt.length-2];return{indexed:b.indexed-W.indexed,notIndexed:b.notIndexed-W.notIndexed}},[Nt]);l.useEffect(()=>{_(1)},[he,mt,vt]);const je=l.useMemo(()=>vt?(he?.reasonGroups??[]).find(b=>b.reason===vt):void 0,[he,vt]),le=l.useMemo(()=>he?mt==="indexed"?he.indexed:mt==="deindexed"?he.deindexed:mt==="notIndexed"?vt?je?.urls??[]:(he.reasonGroups??[]).length===0?he.notIndexed:[]:[]:[],[he,mt,vt,je]),Ne=Math.max(1,Math.ceil(le.length/_s)),Ke=Math.min(Math.max(1,bs),Ne),ht=(Ke-1)*_s,ct=l.useMemo(()=>he?.indexed.slice(ht,ht+_s)??[],[he,ht]),vs=l.useMemo(()=>he?.notIndexed.slice(ht,ht+_s)??[],[he,ht]),M=l.useMemo(()=>he?.deindexed.slice(ht,ht+_s)??[],[he,ht]),be=l.useMemo(()=>(je?.urls??[]).slice(ht,ht+_s),[je,ht]),[rt,wt]=l.useState(!1),[is,Be]=l.useState(null),[pt,Ds]=l.useState(null),[rn,Wt]=l.useState(null);function Fn(b,W){const ue=th(b),ve=hx(ue);ve?(Ds(ve),Be(null)):(Ds(null),Be(ue.message||W))}const It=d.find(b=>b.connectionType==="gsc"),Os=(It?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),on=De.length>0?De:(ke??[]).map(b=>b.path),Kn=on.filter(b=>ke?.some(W=>W.path===b&&W.isSitemapsIndex)).length,Za=Kn===1?"Resubmit sitemap index":Kn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Sn=u.length>0||g.length>0||S.length>0,Gn=Ic(),_n=Tc();async function ma(b,W=!1){if(r){m([]);return}if(!b){m([]),w("");return}st(!0);try{const{sites:ue}=await n.fetchQuery({...Vc({client:H,path:{name:t}}),staleTime:W?0:Ft});m(ue),w(b.propertyId??ue[0]?.siteUrl??""),Ds(null)}catch(ue){m([]),Fn(ue,"Failed to load Search Console properties")}finally{st(!1)}}async function ln(b){P(!0);const W=b??Z;try{const ue=Qt?Sa:Ps,ve=Qt?0:W,et={limit:String(ue)};ae.startDate&&(et.startDate=ae.startDate),ae.endDate&&(et.endDate=ae.endDate),ae.query&&(et.query=ae.query),ae.page&&(et.page=ae.page),ve>0&&(et.offset=String(ve)),K&&K!=="all"&&!ae.startDate&&(et.window=K);const at=await n.fetchQuery({...Lc({client:H,path:{name:t},query:et}),staleTime:Ft}),dt=at.rows;Qt?(J(!1),y(dt),ye(dt.length),me(!0)):(J(ve+dt.length<at.totalMatching),y(dt),ye(0),me(!1))}catch(ue){y([]),J(!1),ye(0),Be(ue instanceof Error?ue.message:"Failed to load GSC performance data")}finally{P(!1)}}async function Un(){try{const b={};ae.startDate&&(b.startDate=ae.startDate),ae.endDate&&(b.endDate=ae.endDate),K&&K!=="all"&&!ae.startDate&&(b.window=K);const W=await n.fetchQuery({...Mc({client:H,path:{name:t},query:b}),staleTime:Ft});x(W)}catch{x(null)}}async function Cn(b=!1){Oe(!0);try{const W=B.trim()||void 0,ue={limit:"20"};W&&(ue.url=W);const[ve,et]=await Promise.all([n.fetchQuery({...Uc({client:H,path:{name:t},query:ue}),staleTime:b?0:Ft}),n.fetchQuery({...Bc({client:H,path:{name:t}}),staleTime:b?0:Ft})]);f(ve),N(et)}catch(W){f([]),N([]),Be(W instanceof Error?W.message:"Failed to load GSC inspection history")}finally{Oe(!1)}}async function Bn(b=!1){Fe(!0);try{const[W,ue]=await Promise.all([n.fetchQuery({...Dc({client:H,path:{name:t}}),staleTime:b?0:Ft}),n.fetchQuery({...Oc({client:H,path:{name:t}}),staleTime:b?0:Ft}).catch(()=>[])]);xt(W),Zt(ue)}catch(W){xt(null),Zt([]),Be(W instanceof Error?W.message:"Failed to load coverage data")}finally{Fe(!1)}}async function ha(b){wt(!0),Be(null);try{const W=await ki(t,{urls:b}),{succeeded:ue,failed:ve,total:et}=W.summary;$e({title:"Indexing requested",detail:ve===0?`${ue} URL${ue!==1?"s":""} submitted for indexing.`:`${ue}/${et} submitted successfully, ${ve} failed.`,tone:ve===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(W){Be(W instanceof Error?W.message:"Failed to request indexing")}finally{wt(!1)}}async function xa(){wt(!0),Be(null);try{const b=await ki(t,{urls:[],allUnindexed:!0}),{succeeded:W,failed:ue,total:ve}=b.summary;$e({title:"Indexing requested",detail:ue===0?`${W} unindexed URL${W!==1?"s":""} submitted for indexing.`:`${W}/${ve} submitted successfully, ${ue} failed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(b){Be(b instanceof Error?b.message:"Failed to request indexing")}finally{wt(!1)}}async function kn(){Xe(!0),Be(null);try{const b=await tr(t);n.setQueryData(Fc({client:H,path:{name:t}}),b),ot(b.sitemaps),qt(b.summary),k(b.preferredSubmissionUrls),we(new Set),yt({}),b.sitemaps.length===0&&Wt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(b){Be(b instanceof Error?b.message:"Failed to list sitemaps")}finally{Xe(!1)}}async function ts(b){const W=Ie.has(b);if(we(ue=>{const ve=new Set(ue);return W?ve.delete(b):ve.add(b),ve}),!(W||ze[b])){Rt(ue=>new Set(ue).add(b));try{const ue=await tr(t,b);yt(ve=>({...ve,[b]:ue.sitemaps}))}catch(ue){Be(ue instanceof Error?ue.message:"Failed to load sitemap files")}finally{Rt(ue=>{const ve=new Set(ue);return ve.delete(b),ve})}}}async function Fs(b){if(!Os||b.length===0)return;const W=[...new Set(b)];lt(!0),Be(null),Pe({completed:0,total:W.length});let ue=0,ve=0,et=0,at=null;try{for(let At=0;At<W.length;At+=50){const ut=W.slice(At,At+50);try{const Re=await Kc(t,ut);ue+=Re.summary.accepted,ve+=Re.summary.failed,et+=ut.length,Pe({completed:et,total:W.length})}catch(Re){et+=ut.length;const Ks=ut.length,Vn=W.length-et,ba=Re instanceof Error?Re.message:"The batch request failed",Gs=`${ue} accepted, ${ve} failed, ${Ks} unconfirmed, ${Vn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;at=`Sitemap submission stopped after a batch request failed. ${Gs} ${ba}`,Be(at),$e({title:"Sitemap resubmission partially completed",detail:Gs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const dt=W.length;$e({title:ve===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ve===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ue}/${dt} sitemap submissions; ${ve} failed. Indexing is not guaranteed.`,tone:ve===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Yt("")}catch(dt){Be(dt instanceof Error?dt.message:"Failed to submit sitemap to Google")}finally{lt(!1),Pe(null),await kn(),at&&Be(at)}}async function er(){lt(!0);const b=ke??[];try{const W=b.filter(ve=>ve.isSitemapsIndex),ue=[];for(let ve=0;ve<W.length;ve+=4)(await Promise.all(W.slice(ve,ve+4).map(async at=>{const dt=ze[at.path];if(dt)return dt;const At=await tr(t,at.path);return yt(ut=>({...ut,[at.path]:At.sitemaps})),At.sitemaps}))).forEach((at,dt)=>{ue.push(...at.length>0?at.map(At=>At.path):[W[ve+dt].path])});await Fs([...b.filter(ve=>!ve.isSitemapsIndex).map(ve=>ve.path),...ue])}catch(W){Be(W instanceof Error?W.message:"Failed to load sitemap files"),lt(!1)}}async function pa(b){_t(!0),Be(null);try{await Gc(t,"gsc",b),await Ct(n,"google"),c(W=>W.map(ue=>ue.connectionType==="gsc"?{...ue,sitemapUrl:b}:ue)),$e({title:"Default sitemap updated",detail:b,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(W){Be(W instanceof Error?W.message:"Failed to set the default sitemap")}finally{_t(!1)}}async function ga(b){try{await _n.mutateAsync({projectName:t,projectLabel:t,opts:b?{sitemapUrl:b}:void 0})}catch{}}async function fa(){Ce(!0),Be(null);try{const[b,W]=await Promise.all([r||!a?Promise.resolve(null):ol().catch(()=>null),n.fetchQuery({...ri({client:H,path:{name:t}}),staleTime:Ft}).catch(()=>[])]);i(!!b?.google?.configured),c(W);const ue=W.find(ve=>ve.connectionType==="gsc");await Promise.all([r?Promise.resolve():ma(ue),ln(),Un(),Cn(),Bn(),!r&&ue?.propertyId?kn():Promise.resolve()])}finally{Ce(!1)}}l.useEffect(()=>{fa()},[t,s,a]),l.useEffect(()=>{se(0),U(null),I(b=>b.startDate||b.endDate?{...b,startDate:"",endDate:""}:b),T(b=>b+1),Un()},[K]);const ya=l.useRef(!1);l.useEffect(()=>{if(!ya.current){ya.current=!0;return}se(0),zt.setPage(1),ln(0)},[F]);function $(b){const W=V===b?null:b;U(W),I(ue=>({...ue,startDate:W??"",endDate:W??""})),T(ue=>ue+1)}const fe=l.useRef(!1);l.useEffect(()=>{if(!fe.current){fe.current=!0;return}se(0),ln(0)},[fs]);async function Me(){if(!o){Be("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Qe(!0),Be(null),Wt(null);try{let b=function(Re){if(Re.source!==ve||Re.origin!==et||!Re.data||typeof Re.data!="object")return;const Ks=Re.data;Ks.type!==gx||Ks.connectionType!=="gsc"||ut(!0)};const{authUrl:W,redirectUri:ue}=await Ec(t,"gsc");if(!W.startsWith("https://accounts.google.com/")){Be("Unexpected OAuth redirect URL. Please try again.");return}const ve=window.open(W,"_blank","width=600,height=700");if(!ve){window.location.assign(W);return}const et=ue?new URL(ue).origin:window.location.origin;let at=!1,dt=null;const At=()=>{dt!==null&&window.clearInterval(dt),window.removeEventListener("message",b)},ut=async Re=>{if(!at){at=!0,At(),Wt(Re?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Ct(n,"google"),await fa()}finally{Wt(null)}}};window.addEventListener("message",b),Wt("Finish the Google consent flow in the popup. This page will refresh automatically."),dt=window.setInterval(()=>{ve.closed&&ut(!1)},1e3)}catch(b){Be(b instanceof Error?b.message:"Failed to start OAuth flow")}finally{Qe(!1)}}async function ss(){Be(null),Wt(null);try{await qc(t,"gsc"),await Ct(n,"google"),c(b=>b.filter(W=>W.connectionType!=="gsc")),m([]),w("")}catch(b){Be(b instanceof Error?b.message:"Failed to disconnect")}}async function js(){if(v){O(!0),Be(null);try{await Qc(t,"gsc",v),await Ct(n,"google"),c(b=>b.map(W=>W.connectionType==="gsc"?{...W,propertyId:v}:W)),$e({title:"GSC property updated",detail:`${t} is now linked to ${v}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(b){Be(b instanceof Error?b.message:"Failed to save GSC property")}finally{O(!1)}}}async function xc(){Be(null),Wt(null);try{await Gn.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(q,10)||void 0,full:X||void 0}}),await Ct(n,"gsc")}catch{}}async function Si(){if(j.trim()){_e(!0),Be(null),Wt(null);try{const b=await _c(t,j.trim());await Ct(n,"gsc"),A(b),L(""),await Cn()}catch(b){Be(b instanceof Error?b.message:"Failed to inspect URL")}finally{_e(!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"})]})}),pt&&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:pt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:pt.message}),(Bs(pt.enableUrl)||Bs(pt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Bs(pt.enableUrl)&&e.jsx("a",{href:Bs(pt.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 ↗"}),Bs(pt.indexingApiUrl)&&e.jsx("a",{href:Bs(pt.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:()=>Ds(null),children:"×"})]})}),is&&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:[is,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Be(null),children:"×"})]}),rn&&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:[rn,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Wt(null),children:"×"})]}),Se?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[It?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-neutral",children:"Authorized"})]}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsx("code",{className:"text-secondary",children:It.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",he?.lastInspectedAt?Ht(he.lastInspectedAt):"never"]}),!r&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:He(ss),children:"Disconnect"})]}):a?e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ce,{tone:o?"caution":"negative",children:o?"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:o?"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:[o?e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:tt,onClick:He(Me),children:tt?"Opening…":"Connect Google Search Console"}):e.jsx(R,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(As,{to:"/settings",children:"Open Settings"})}),!o&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}):e.jsx(pe,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:xx})}),(It||Sn)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Ve,{text:`${bx(p?.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 ${Sa.toLocaleString()} matching rows while the table shows ${Ps} per page.`})]}),p?.window?.startDate&&p.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[p.window.startDate," to ",p.window.endDate,(p.window.daysSinceLatestData??0)>0&&` · latest data ${p.window.daysSinceLatestData} day${p.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ja,{windows:px,value:K,onChange:b=>{Q(b),se(0),zt.setPage(1)},label:"Search Console time period",formatOption:b=>b==="all"?"All":b}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:Le,onClick:()=>{se(0),zt.setPage(1),ln(0),Un()},children:Le?"Loading…":"Apply filters"})]})]}),p&&p.daily.length>0&&(()=>{const{totals:b,daily:W,trends:ue,periodComparison:ve}=p,at=eo.filter(Re=>C.includes(Re.key)).map(Re=>({dataKey:Re.key,label:Re.label,color:Re.color,axisId:Re.key,inverted:Re.inverted,formatValue:Re.format,trend:z?ue?.[Re.key]??null:null})),dt=Re=>b[Re]??null,At=new Map(W.map(Re=>[Re.date,Re])),ut=W.length===0?[]:oh(W[0].date,W[W.length-1].date).map(Re=>At.get(Re)??{date:Re});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:eo.map(Re=>{const Ks=C.includes(Re.key),Vn=dt(Re.key),ba=Vn===null;return e.jsxs("button",{type:"button","aria-pressed":Ks,disabled:ba,className:`rounded-md border px-3 py-2 text-left transition-colors ${Ks?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${ba?"cursor-not-allowed opacity-50":""}`,onClick:()=>{te(Gs=>Gs.includes(Re.key)?Gs.length===1?Gs:Gs.filter(pc=>pc!==Re.key):[...Gs,Re.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:Ks?Re.color:"transparent",border:`1px solid ${Re.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:Re.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Vn===null?"—":Re.format(Vn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:yx(ve,Re.key,Re.inverted)})]},Re.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:z,onChange:Re=>Y(Re.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(Sl,{data:ut,xKey:"date",series:at,xTickFormatter:Nn,labelFormatter:Gt,onSelectX:$,selectedX:V})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:W.map(Re=>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":V===Re.date,onClick:()=>$(Re.date),children:[Gt(Re.date),": ",Re.clicks," clicks, ",Re.impressions," impressions"]},Re.date))}),V&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Gt(V)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>$(V),children:["Show all ",b.days," days"]})]}),b.position!==null&&(b.positionDays??b.days)<b.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",b.positionDays," of ",b.days," days. The rest have no property-level position recorded."]}),(b.position===null||b.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:ae.startDate,onChange:b=>I(W=>({...W,startDate:b.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:ae.endDate,onChange:b=>I(W=>({...W,endDate:b.target.value}))}),e.jsx(Hs,{value:ae.query,onChange:b=>I(W=>({...W,query:b})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Hs,{value:ae.page,onChange:b=>I(W=>({...W,page:b})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),u.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(fn).map(b=>e.jsx("th",{className:"text-right","aria-sort":Ze?.key===b?Ze.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{zt.setPage(1),Et(W=>W?.key===b?W.dir==="desc"?{key:b,dir:"asc"}:null:{key:b,dir:"desc"})},children:[$c[b],Ze?.key===b?Ze.dir==="desc"?" ↓":" ↑":""]})},b))]})}),e.jsx("tbody",{children:ys.map((b,W)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:b.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:b.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Da,{value:b.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:b.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(b.ctr)?b.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.position.toFixed(1)})]},`${b.date}:${b.query}:${b.page}:${W}`))})]})}),e.jsx(Ls,{page:ee?zt.page:Math.floor(Z/Ps)+1,pageSize:Ps,visibleRows:ys.length,totalRows:ee?ie:void 0,hasNextPage:ee?void 0:de,disabled:Le,itemLabel:ee?"matches":"rows",onPageChange:b=>{if(ee){zt.setPage(b);return}const W=(b-1)*Ps;se(W),ln(W)}}),ee&&ie>=Sa?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Sa.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Ve,{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:[he&&he.notIndexed.length>0&&e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:rt,onClick:()=>{xa()},children:rt?"Requesting…":`Request indexing (${he.notIndexed.length})`}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:Ue,onClick:()=>{Bn(!0)},children:Ue?"Loading…":"Reload saved coverage"})]})]}),he&&he.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const b=he.summary.indexed+he.summary.notIndexed,W=b>0?he.summary.indexed/b:0,ue=b>0?he.summary.notIndexed/b:0,ve=54,et=2*Math.PI*ve,at=et*(1-W),dt=et*ue,At=et*W;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:ve,fill:"none",stroke:hs.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ve,fill:"none",stroke:qs.positiveDeep,strokeWidth:"14",strokeDasharray:et,strokeDashoffset:at,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),he.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ve,fill:"none",stroke:hs.textFaint,strokeWidth:"14",strokeDasharray:`${dt} ${et-dt}`,strokeDashoffset:-At,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-3xl font-bold tabular-nums text-primary",children:[(W*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:he.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:he.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(he.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(he.reasonGroups??[]).length," ",(he.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),he.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:he.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(b=>{const W=b==="indexed"?he.indexed.length:b==="notIndexed"?he.notIndexed.length:he.deindexed.length,ue=b==="indexed"?"Indexed":b==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":mt===b,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${mt===b?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{rs(b),es(null)},children:[ue," (",W,")"]},b)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[mt==="indexed"&&he.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:ct.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-secondary",children:b.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.crawlTime?b.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:b.isMobileFriendly===!0?"Yes":b.isMobileFriendly===!1?"No":"—"})]},b.id))})]}),mt==="notIndexed"&&!vt&&(he.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:(he.reasonGroups??[]).map(b=>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:()=>es(b.reason),onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),es(b.reason))},tabIndex:0,role:"button","aria-label":`View ${b.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:b.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.count})]},b.reason))})]}),mt==="notIndexed"&&!vt&&(he.reasonGroups??[]).length===0&&he.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(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-secondary",children:b.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.coverageState??"Unknown"})]},b.id))})]}),mt==="notIndexed"&&vt&&(()=>{const b=(he.reasonGroups??[]).find(W=>W.reason===vt);return b?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:()=>es(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:b.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[b.count," affected page",b.count!==1?"s":""]})]}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:rt,onClick:()=>{ha(b.urls.map(W=>W.url))},children:rt?"Requesting…":`Request indexing (${b.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:be.map(W=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:W.url}),e.jsx("td",{className:"text-secondary",children:W.crawlTime?W.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:rt,onClick:()=>{ha([W.url])},title:"Request indexing",children:"Index"})})]},W.id))})]})]}):null})(),mt==="deindexed"&&he.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:M.map((b,W)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-secondary",children:b.previousState}),e.jsx("td",{className:"text-secondary",children:b.currentState}),e.jsx("td",{className:"text-secondary",children:b.transitionDate.split("T")[0]})]},`${b.url}-${W}`))})]}),(mt==="indexed"&&he.indexed.length===0||mt==="notIndexed"&&!vt&&he.notIndexed.length===0||mt==="deindexed"&&he.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ls,{page:Ke,pageSize:_s,visibleRows:Math.min(_s,le.length-ht),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":Bt,onClick:()=>Vt(b=>!b),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Bt?"Hide snapshots":Nt.length>0?`View ${Nt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",he.summary.indexed.toLocaleString()," indexed, ",he.summary.notIndexed.toLocaleString()," not indexed.",re&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",re.indexed>=0?"+":"",re.indexed.toLocaleString()," indexed, ",re.notIndexed>=0?"+":"",re.notIndexed.toLocaleString()," not indexed."]})]}),Bt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:Nt.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:Nt.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:b.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:b.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.notIndexed.toLocaleString()})]},b.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:Ue?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),!r&&e.jsxs(e.Fragment,{children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Ve,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:kt||!It?.propertyId,onClick:()=>{kn()},children:kt?"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:Ae,onChange:b=>Yt(b.target.value),onKeyDown:b=>b.key==="Enter"&&void Fs([Ae.trim()])}),e.jsx(R,{type:"button",size:"sm",disabled:!Os||bt||!Ae.trim(),onClick:()=>{Fs([Ae.trim()])},children:bt?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:!Os||bt||on.length===0,onClick:()=>{Fs(on)},children:bt?"Resubmitting…":Za}),e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:!Os||bt||!ke?.length,onClick:()=>{er()},children:"Resubmit all files"}),ft&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",ft.indexes," index",ft.indexes===1?"":"es",", ",ft.files," file",ft.files===1?"":"s"]}),Ee&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Ee.completed,"/",Ee.total]})]}),!Os&&It&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:He(Me),children:"Reconnect"})]}),ke&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:ke.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{value:Ye,onChange:b=>{ne(b),Xt.setPage(1)},label:"Filter sitemaps",placeholder:"Filter sitemaps…"}),e.jsxs("table",{className:"data-table mt-3 w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Sitemap"}),e.jsx("th",{className:"text-left",children:"Type"}),e.jsx("th",{className:"text-left",children:"Google status"}),e.jsx("th",{className:"text-left",children:"Last submitted"}),e.jsx("th",{className:"text-left",children:"Last read"}),e.jsx("th",{className:"text-right",children:"Discovered URLs"}),e.jsx("th",{className:"text-left",children:"Issues"}),e.jsx("th",{className:"text-left",children:"Actions"})]})}),e.jsx("tbody",{children:Xt.rows.flatMap(b=>{const W=to(b),ue=so(b),ve=no(b),et=ze[b.path]??[],at=Ie.has(b.path),dt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Da,{value:b.path})}),e.jsx("td",{className:"text-secondary",children:b.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":at,"aria-label":`${at?"Collapse":"Expand"} files in ${b.path}`,onClick:()=>{ts(b.path)},children:nt.has(b.path)?"Loading…":`${at?"▾":"▸"} Index${ze[b.path]?` (${et.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ve}),e.jsx("td",{className:"text-secondary",children:b.lastSubmitted?b.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:b.lastDownloaded?b.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:W.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ue||"—"}),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:!Os||bt,onClick:()=>{Fs([b.path])},children:b.lastSubmitted?"Resubmit to Google":"Submit to Google"}),It?.sitemapUrl===b.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Jt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{pa(b.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:_n.isPending,onClick:()=>{ga(b.path)},children:"Inspect URLs"})]})})]},b.path),At=b.isSitemapsIndex&&at?et.map(ut=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Da,{value:ut.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:no(ut)}),e.jsx("td",{className:"text-secondary",children:ut.lastSubmitted?ut.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ut.lastDownloaded?ut.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:to(ut).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:so(ut)||"—"}),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:!Os||bt,onClick:()=>{Fs([ut.path])},children:"Resubmit"}),It?.sitemapUrl===ut.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Jt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{pa(ut.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:_n.isPending,onClick:()=>{ga(ut.path)},children:"Inspect URLs"})]})})]},`${b.path}:${ut.path}`)):[];return[dt,...At]})})]}),e.jsx(Ls,{page:Xt.page,pageSize:Ps,visibleRows:Xt.rows.length,totalRows:Xt.totalRows,onPageChange:Xt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:j,onChange:b=>L(b.target.value),onKeyDown:b=>b.key==="Enter"&&void Si()}),e.jsx(R,{type:"button",size:"sm",disabled:We||!It?.propertyId||!j.trim(),onClick:He(Si),children:We?"Inspecting…":"Inspect URL"})]}),E&&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:E.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:E.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:Ci(E.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Ht(E.crawlTime)})]})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:ge,onClick:()=>{Cn(!0)},children:ge?"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:B,onChange:b=>xe(b.target.value)}),e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:ge,onClick:()=>{Cn(!0)},children:"Apply filter"})]}),g.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:g.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-neutral",children:b.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ci(b.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Ht(b.inspectedAt)})]},b.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),S.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:S.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-secondary",children:b.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:b.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ht(b.transitionDate)})]},`${b.url}:${b.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),It&&!r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>as(b=>!b),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 ${Ut?"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"})]})}),Ut&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Ve,{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:v,disabled:Ge||h.length===0,onChange:b=>w(b.target.value),children:h.length===0?e.jsx("option",{value:"",children:Ge?"Loading properties…":"No properties available"}):h.map(b=>e.jsxs("option",{value:b.siteUrl,children:[b.siteUrl," · ",b.permissionLevel]},b.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:Ge,onClick:()=>{ma(It,!0)},children:Ge?"Refreshing…":"Refresh properties"}),e.jsx(R,{type:"button",size:"sm",disabled:!v||qe,onClick:He(js),children:qe?"Saving…":"Save property"})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:q,onChange:b=>D(b.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:X,onChange:b=>G(b.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(R,{type:"button",size:"sm",disabled:Gn.isPending||!It.propertyId,onClick:He(xc),children:Gn.isPending?"Queueing…":"Queue sync"}),!It.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const jx=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Nx({projectName:t,projectId:s}){const n=xs(),[a,r]=l.useState(null),[o,i]=l.useState(null),[d,c]=l.useState(!1),h=Te(ri({client:H,path:{name:t}})),m=h.data?.find(J=>J.connectionType==="gbp"),u=!!m,y=a?{locationName:a}:void 0,p=Te({...zc({client:H,path:{name:t}}),enabled:u}),x=Te({...Wc({client:H,path:{name:t},query:y}),enabled:u}),g=Te({...Hc({client:H,path:{name:t},query:y}),enabled:u}),f=Te({...Yc({client:H,path:{name:t},query:y}),enabled:u}),S=Te({...Jc({client:H,path:{name:t},query:y}),enabled:u}),N=Te({...Xc({client:H,path:{name:t},query:y}),enabled:u}),E=Te({queryKey:["gbp-section-insights",t],queryFn:()=>Zc(t),enabled:u});function A(){Ct(n,"gbp")}const v=Pt({...ed(),onSuccess:J=>{ll({id:J.runId,projectId:s,kind:Xs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),$e({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),w=l.useSyncExternalStore(cl,Ka,Ka),j=Object.values(w.runs).some(J=>J.kind===Xs["gbp-sync"]&&J.projectId===s),L=v.isPending||j,q=Pt({...td(),onSuccess:()=>A()});if(l.useEffect(()=>{if(!a||!p.data)return;const J=p.data.locations.filter(ie=>ie.selected);(J.length<=1||!J.some(ie=>ie.locationName===a))&&r(null)},[a,p.data]),l.useEffect(()=>{if(!o||!p.data)return;(a?[a]:p.data.locations.filter(ie=>ie.selected).map(ie=>ie.locationName)).includes(o)||i(null)},[o,p.data,a]),h.isLoading)return null;if(!m){const J=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(pe,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:J.map((ie,ye)=>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:ye+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ie.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:ie.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ie.note})]})]},ie.title))})]})})}const D=x.data,X=p.data?.locations??[],G=X.filter(J=>J.selected),K=g.data?.keywords??[],Q=f.data?.lodging??[],C=S.data?.placeActions??[],te=N.data?.places??[],z=X.length>0?X[0].accountName:m.domain,Y=a?X.find(J=>J.locationName===a)?.displayName??null:null,V=a?X.filter(J=>J.locationName===a):G,U=new Set(V.map(J=>J.locationName)),F=Q.filter(J=>U.has(J.locationName)),T=C.filter(J=>U.has(J.locationName)),ae=te.filter(J=>U.has(J.locationName)),I=new Set(G.map(J=>J.locationName)),Z=a?K:K.filter(J=>I.has(J.locationName)),se=!a&&G.length>1,de=(E.data??[]).filter(J=>!J.dismissed&&jx.has(J.type)&&(!Y||J.query===Y||J.query===a||J.title.startsWith(Y)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Ve,{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(ce,{tone:"positive",children:"Connected"}),!oe()&&e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:L,onClick:()=>v.mutate({client:H,path:{name:t},body:{}}),children:L?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[z?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:z})," · "]}):null,p.data?`${p.data.totalSelected} of ${p.data.totalDiscovered} locations tracked`:"Loading locations…"]}),G.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:J=>r(J.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),G.map(J=>e.jsx("option",{value:J.locationName,children:J.displayName},J.id))]})]}),G.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[de.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),de.map(J=>e.jsx("div",{className:["insight-card",qx(J.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:[J.title,J.recommendation?.reason&&e.jsx(Ve,{text:J.recommendation.reason})]})},J.id))]}),D&&e.jsx(Fx,{performance:D.performance,freshness:D.freshness,timeseries:D.timeseries}),D?.profileCompleteness&&e.jsx(wx,{summary:D.profileCompleteness}),V.length>0&&e.jsx(Sx,{locations:V,lodging:F,places:ae,placeActions:T,expandedLocation:o,onToggleExpanded:J=>{i(ie=>ie===J?null:J)}}),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"}),g.data&&g.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[g.data.thresholdedPct,"% privacy-thresholded"]})]}),Z.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"}),se&&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:Z.slice(0,25).map(J=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:J.keyword}),se&&e.jsx("td",{className:"text-muted",children:X.find(ie=>ie.locationName===J.locationName)?.displayName??J.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:J.valueCount!==null?J.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",J.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[J.periodStart,"–",J.periodEnd]})]},`${J.locationName}:${J.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>c(J=>!J),"aria-expanded":d,children:[e.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"})," Manage locations (",X.length,")"]}),d&&e.jsx("div",{className:"mt-3",children:X.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!oe()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:X.map(J=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:J.displayName}),e.jsx("td",{className:"text-muted",children:J.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ce,{tone:J.selected?"positive":"neutral",children:J.selected?"Tracked":"Not tracked"})}),!oe()&&e.jsx("td",{className:"text-right",children:e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:q.isPending,onClick:()=>q.mutate({client:H,path:{name:t,locationName:J.locationName},body:{selected:!J.selected}}),children:J.selected?"Untrack":"Track"})})]},J.id))})]})})]})]})})}function wx({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:zn(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:zn(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:zn(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:zn(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:zn(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(Ve,{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 ${Lx(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Sx({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:o}){const i=new Map(s.map(h=>[h.locationName,h])),d=new Map(n.map(h=>[h.locationName,h])),c=new Map;for(const h of a){const m=c.get(h.locationName)??[];m.push(h),c.set(h.locationName,m)}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(Ve,{text:oe()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const m=i.get(h.locationName)??null,u=d.get(h.locationName)??null,y=c.get(h.locationName)??[],p=r===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ce,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ce,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:_l(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(kx,{location:h})}),e.jsx("td",{children:e.jsx(Ax,{lodging:m})}),e.jsx("td",{children:e.jsx(Rx,{place:u,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(Tx,{actions:y})}),e.jsx("td",{className:"text-right",children:e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>o(h.locationName),children:p?"Hide":"Details"})})]}),p&&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(Mx,{location:h,lodging:m,place:u,placeActions:y})})})]},h.id)})})]})})]})}function Cx(t){return[{label:"Description",tone:pn(t.description)?"positive":"neutral",value:pn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:pn(t.primaryPhone)?"positive":"neutral",value:pn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:pn(t.websiteUri)?"positive":"neutral",value:pn(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function kx({location:t}){const s=Cx(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ce,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Ax({lodging:t}){return e.jsx(li,{...Px(t)})}function Px(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 Rx({place:t,mapsUri:s}){return e.jsx(li,{...Ix(t,s)})}function Ix(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 Tx({actions:t}){return e.jsx(li,{...$x(t)})}function $x(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(ce,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Mx({location:t,lodging:s,place:n,placeActions:a}){const r=s?Dx(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(pr,{title:"Owner profile · Business Information",children:[e.jsx(Dt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Dt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Dt,{label:"Description",value:pn(t.description)?t.description:"Not returned"}),e.jsx(Dt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Dt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Dt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Dt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Dt,{label:"Open status",value:_l(t.openStatus)}),e.jsx(Dt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(pr,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Dt,{label:"Last checked",value:ao(s.syncedAt)}),e.jsx(Dt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Dt,{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(pr,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Dt,{label:"Places tier",value:n.tier}),e.jsx(Dt,{label:"Last checked",value:ao(n.syncedAt)}),e.jsx(Dt,{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(o=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Qa(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Qa(o.providerType),o.uri?` · ${Ex(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function pr({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 Dt({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 zn(t,s,n){return t===s?"positive":t===0?n:"caution"}function Lx(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function qx(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function pn(t){return typeof t=="string"&&t.trim().length>0}function _l(t){return t?Qa(t):"Not returned"}function Qa(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Ex(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function ao(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Dx(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Ox(n)).map(([s])=>Qa(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Ox(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Fx({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=sd.filter(x=>(a[x]??0)>0),o=nd.filter(x=>(a[x]??0)>0),i=Object.keys(a).filter(x=>(a[x]??0)>0&&ad(x)==="other").sort((x,g)=>(a[g]??0)-(a[x]??0)),d=Object.keys(a).filter(x=>(a[x]??0)===0).sort(),c=n.map(x=>{const g={date:x.date};for(const[f,S]of Object.entries(x.metrics))g[f]=S;return g}),h=n.find(x=>x.pending)?.date,m=n.length>0?n[n.length-1].date:void 0,u=c.length>0,y=s.dataThroughDate?`Data through ${Gt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,p=[...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"}),y&&e.jsx("span",{className:"text-[11px] text-muted",children:y})]}),!u||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(ro,{data:c,metrics:r,kind:"line",firstPending:h,lastDate:m}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:p.map(x=>e.jsxs("span",{className:"text-sm text-secondary",children:[Ga(x)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[x]??0).toLocaleString()})]},x))})]})]}),u&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(ro,{data:c,metrics:o,kind:"area",firstPending:h,lastDate:m})]}),d.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",d.map(x=>Ga(x)).join(", ")]})]})}function ro({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(oa,{stroke:ia,vertical:!1}),e.jsx(sn,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:ms},tickFormatter:Nn,minTickGap:24}),e.jsx(nn,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(an,{...ns,labelFormatter:Gt,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),Ga(String(i??""))]}),e.jsx(Va,{wrapperStyle:{fontSize:11,color:hs.text},formatter:o=>Ga(o)}),a&&r&&e.jsx(Gr,{x1:a,x2:r,fill:hs.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:hs.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx($s,{type:"monotone",dataKey:o,stroke:it[i%it.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Qs,{type:"monotone",dataKey:o,stackId:"reach",stroke:it[i%it.length],fill:it[i%it.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function Kx(t){return Cl(Es(String(t)))}function Gx(t){return Ys(Es(String(t)))}function gr({children:t,label:s="More info",placement:n="top",className:a}){const r=l.useId(),[o,i]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":o?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(_m,{className:"h-3.5 w-3.5","aria-hidden":!0})}),o&&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 Ca=Ps;function An(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function fr(t){return t.toLocaleString()}function _x(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Ux(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 Bx(t){const s=t.filter(n=>n.kind===Xs["backlink-extract"]&&!dl(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Vx(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),o=a%60;return o===0?`${r}m`:`${r}m ${o}s`}function Qx({projectName:t}){const s=Ms(),[n,a]=l.useState(null),[r,o]=l.useState(null),[i,d]=l.useState([]),[c,h]=l.useState(null),[m,u]=l.useState(null),[y,p]=l.useState(null),[x,g]=l.useState(Date.now()),[f,S]=l.useState(0),[N,E]=l.useState(!0),[A,v]=l.useState(!1),[w,j]=l.useState(null),L=l.useCallback(async()=>{E(!0),j(null);try{const[Y,V,U,F,T]=await Promise.all([rd().catch(()=>null),id(t,{excludeCrawlers:!0}).catch(()=>null),od(t,{limit:Ca,offset:f,excludeCrawlers:!0}).catch(I=>{if(I instanceof bn&&I.code==="NOT_FOUND")return null;throw I}),ld(t).catch(()=>[]),cd(t).catch(()=>[])]);h(Y),a(V),o(U),d(F);const ae=Bx(T);u(ae)}catch(Y){j(Y instanceof Error?Y.message:"Failed to load backlinks")}finally{E(!1)}},[t,f]);l.useEffect(()=>{L()},[L]),l.useEffect(()=>{if(!m)return;const Y=m.id;let V=!1;const U=async()=>{try{const T=await Kr(Y);if(V)return;dl(T.status)?(u(null),p(T),await L()):u(ae=>ae?.id===T.id?{...ae,...T}:ae)}catch{}},F=window.setInterval(()=>{U()},3e3);return()=>{V=!0,window.clearInterval(F)}},[m,L]),l.useEffect(()=>{if(!m)return;const Y=window.setInterval(()=>g(Date.now()),1e3);return()=>window.clearInterval(Y)},[m]),l.useEffect(()=>{if(!y||y.status==="failed")return;const Y=window.setTimeout(()=>p(null),1e4);return()=>window.clearTimeout(Y)},[y]);async function q(){v(!0),j(null);try{const Y=await ud(t);u(Y)}catch(Y){Y instanceof bn&&Y.code==="MISSING_DEPENDENCY"?j("DuckDB is not installed. Visit the Backlinks admin page to install it."):j(Y instanceof Error?Y.message:"Failed to trigger extract")}finally{v(!1)}}const D=l.useMemo(()=>i.slice().sort((Y,V)=>Y.queriedAt.localeCompare(V.queriedAt)).map(Y=>({date:Y.queriedAt,linkingDomains:Y.totalLinkingDomains})),[i]),X=r?.rows??[],G=r?.total??0,K=n?.excludedLinkingDomains??0,Q=Math.floor(f/Ca)+1;return l.useEffect(()=>{f>0&&f>=G&&S(0)},[f,G]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),w&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:w})}),m&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Fm,{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(ce,{tone:"neutral",children:m.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Vx(m.startedAt??null,m.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",x]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),y&&!m&&e.jsx(pe,{className:`surface-card p-4 mb-4 ${y.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[y.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(Km,{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 ${y.status==="failed"?"text-negative":"text-positive"}`,children:y.status==="failed"?"Extract failed":"Extract complete"}),y.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:dd(y.error)}):y.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),C()]});function C(){return N?e.jsx(pe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):te()}function te(){const Y=n!==null&&n.totalLinkingDomains>0,V=y?.status==="failed",U=n!==null&&n.totalLinkingDomains===0&&!V,F=c?.status==="ready",T=c?.status==="failed",ae=c&&(c.status==="downloading"||c.status==="querying"||c.status==="queued");return Y?z(e.jsxs(e.Fragment,{children:[!oe()&&!s&&e.jsxs(e.Fragment,{children:[e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:A||m!==null,onClick:He(q),children:[e.jsx(vl,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),m?"Extract running…":A?"Queuing…":"Re-run extract"]}),e.jsx(gr,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!oe()&&!s&&e.jsx(R,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:An("/backlinks"),children:"Open admin"})})]})):e.jsx(pe,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Gm,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!c&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!oe()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:An("/backlinks"),children:"Set up backlinks"})})})]}),ae&&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 (",c.status,c.phaseDetail?` — ${c.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!oe()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(R,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:An("/backlinks"),children:"View sync status"})})})]}),T&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:c.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!oe()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:An("/backlinks"),children:"Go to Backlinks admin"})})})]}),F&&!ae&&!U&&!V&&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:c.release})," is ready. Run an extract for this project."]}),!oe()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(R,{type:"button",size:"sm",disabled:A||m!==null,onClick:He(q),children:[e.jsx(Ba,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),m?"Extract running…":A?"Queuing…":"Run extract"]}),e.jsx(gr,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),V&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!oe()&&!s&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:An("/backlinks"),children:"Go to Backlinks admin"})})})]}),U&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",n.targetDomain,". Try a newer release or re-run this extract."]}),!oe()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:An("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:A||m!==null,onClick:He(q),children:[e.jsx(Ba,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),m?"Extract running…":A?"Queuing…":"Re-run extract"]}),e.jsxs(gr,{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 z(Y){if(!n)return null;const V="Linking hosts",U="linking hosts",F="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:fr(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 ",U]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:fr(n.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",U," 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:_x(n.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",U," 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"})," · ",F," ",e.jsx("code",{className:"text-secondary",children:n.release})," · queried ",Ux(n.queriedAt),K>0&&e.jsxs(e.Fragment,{children:[" · ",K," excluded domain",K===1?"":"s"]})]}),D.length>=2&&e.jsxs(pe,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:D,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:it[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:it[0],stopOpacity:0})]})}),e.jsx(sn,{dataKey:"date",tick:Lt,stroke:ms,tickFormatter:Kx}),e.jsx(nn,{tick:Lt,stroke:ms,allowDecimals:!1}),e.jsx(an,{contentStyle:ns.contentStyle,labelStyle:ns.labelStyle,itemStyle:ns.itemStyle,labelFormatter:Gx}),e.jsx(Qs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:it[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(pe,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:V})]})}),e.jsxs("tbody",{children:[X.map(T=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:T.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:fr(T.numHosts)})]},T.linkingDomain)),X.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:K>0&&G===0?`Every referring domain in this ${F} was a crawler/proxy host (${K} hidden).`:`No referring domains in this ${F}.`})})]})]})}),e.jsx(Ls,{page:Q,pageSize:Ca,visibleRows:X.length,totalRows:G,onPageChange:T=>S((T-1)*Ca)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:Y})]})}}function zx({projectName:t}){const s=Te({...md({client:H,path:{name:t}}),staleTime:ii}),n=s.data??null,a=s.error;if(s.isLoading&&!n)return null;if(a)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-negative-400",children:aa(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:Kt()?"text-sm text-secondary":"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":Kt()?Zs:"Run a sweep to see which engines cite this project."})]});const{providersCiting:r,providersMentioning:o,providersConfigured:i}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",r," of ",i," engines",e.jsx(Ve,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",o," of ",i," engine answers",e.jsx(Ve,{text:"An engine is ‘mentioning’ when our brand or domain appears inside the prose of the answer text — independent of whether it’s in the citation list. Models often name-drop from training without citing a fresh page."})]})]}),n.summary.latestRunAt&&e.jsxs("p",{className:"supporting-copy",children:["Latest run ",new Date(n.summary.latestRunAt).toLocaleString()]})]}),e.jsx(Wx,{data:n}),e.jsx(Hx,{data:n}),n.competitorGaps.length>0&&e.jsx(Zx,{data:n})]})}function Wx({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:o}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(ka,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(ka,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(ka,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(ka,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function ka({label:t,value:s,helper:n,tone:a}){const r=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${r}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function Hx({data:t}){const s=l.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const r of a.providers)n.add(r.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(Yx,{}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),s.map(n=>e.jsx("th",{className:"text-center",children:e.jsx(En,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const r=n.providers.find(o=>o.provider===a);return e.jsx("td",{className:"text-center",children:r==null?e.jsx(jl,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Jx,{provider:r})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function Yx(){return e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-3 text-[11px] text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Tn,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Tn,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Tn,{active:!1,tone:"cited"}),e.jsx(Tn,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Jx({provider:t}){const s=Xx(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Tn,{active:t.cited,tone:"cited"}),e.jsx(Tn,{active:t.mentioned,tone:"mentioned"})]})}function Xx(t){return t.cited&&t.mentioned?"Cited in sources and mentioned in answer":t.cited?"Cited in sources, not mentioned in answer":t.mentioned?"Mentioned in answer, not in sources":"Not cited and not mentioned"}function Tn({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-strong bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-positive-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-info-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function Zx({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-strong mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(Ve,{text:"Queries where the project is not cited but a configured competitor is. Each row maps to one (query, engine) pair — the same query may surface for multiple engines."}),e.jsxs("span",{className:"text-[10px] font-normal uppercase tracking-wide text-muted",children:[t.competitorGaps.length," ",t.competitorGaps.length===1?"gap":"gaps"]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Engine"}),e.jsx("th",{children:"Competitors cited"})]})}),e.jsx("tbody",{children:t.competitorGaps.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.query}),e.jsx("td",{children:e.jsx(En,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const io="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",yr="flex min-h-11 w-full items-center justify-between gap-3 rounded px-2 text-left text-sm text-primary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",Wn=t=>t.kind==="project"?"Whole site":t.label,Hn={allMarkets:"All markets",browse:t=>`Browse ${t}`,select:t=>`Select ${t}`,browseAll:"Browse all properties"},ep=t=>t?.kind==="group"&&t.marketKeys?.length===1?t.marketKeys[0]:void 0,oo=t=>`${t} ${t===1?"property":"properties"}`;function Ul({options:t,selected:s,onSelect:n,marketKey:a,label:r="Measurement scope",allowGroupSelect:o=!0}){const i=[...t].sort((I,Z)=>I.label.localeCompare(Z.label,void 0,{numeric:!0})||I.id.localeCompare(Z.id)),[d,c]=l.useState(""),[h,m]=l.useState([]),[u,y]=l.useState(!1),p=l.useRef(null),x=l.useRef(null),g=l.useId(),f=i.filter(I=>I.kind==="group"),S=new Map(f.map(I=>[I.id,I])),N=S.get(h.at(-1)??""),E=S.get(h.at(-2)??""),A=d.trim().toLocaleLowerCase(),v=f.filter(I=>!I.parentGroupIds?.some(Z=>S.has(Z))),w=i.filter(I=>I.kind==="property"),j=I=>(I.parentGroupIds??[]).map(Z=>S.get(Z)?.label).filter(Boolean).join(" · "),L=I=>`${Wn(I)} ${j(I)}`.toLocaleLowerCase().includes(A),q=I=>{const Z=[...I.parentGroupIds??[]],se=new Set;for(;Z.length;){const de=Z.pop();if(de===N?.id)return!0;se.has(de)||(se.add(de),Z.push(...S.get(de)?.parentGroupIds??[]))}return!1},D=(u?[]:N?f.filter(I=>A?q(I):I.parentGroupIds?.includes(N.id)):A?f:v).filter(L),X=i.find(I=>I.kind==="market"&&I.id===(a??(s.kind==="market"?s.id:void 0))),G=N&&X&&(N.marketKeys?.includes(X.id)||X.parentGroupIds?.includes(N.id))?X.id:void 0,K=o?G??ep(N):void 0,Q=(N?w.filter(I=>I.parentGroupIds?.includes(N.id)&&(!K||I.marketKeys?.includes(K))):A||u||f.length===0?w:[]).filter(L),C=i.filter(I=>I.kind!=="market"||u||!o&&!N&&!A&&f.length>0||o&&N?.marketKeys?.length===1&&!A?!1:(N?A?q(I):I.parentGroupIds?.includes(N.id):A||!I.parentGroupIds?.some(se=>S.has(se)))&&L(I)),te=N||u?[]:i.filter(I=>I.kind==="project"&&L(I));l.useEffect(()=>{const I=Z=>{p.current?.open&&Z.target instanceof Node&&!p.current.contains(Z.target)&&(p.current.open=!1)};return document.addEventListener("pointerdown",I),()=>document.removeEventListener("pointerdown",I)},[]);const z=I=>{p.current&&(p.current.open=!1,p.current.querySelector("summary")?.focus());const Z=o?I.kind==="property"?K:I.kind==="group"&&I.id===N?.id?G:void 0:void 0;Z?n(I,Z):n(I)},Y=I=>{const Z=[];let se=S.get(I.parentGroupIds?.[0]??"");for(;se&&!Z.includes(se.id)&&se.id!==I.id;)Z.unshift(se.id),se=S.get(se.parentGroupIds?.[0]??"");return[...Z,I.id]},V=()=>{const I=s.kind==="group"?S.get(s.id):void 0,Z=S.get(X?.parentGroupIds?.[0]??""),se=(s.parentGroupIds??[]).flatMap(ie=>{const ye=S.get(ie);return ye?[Y(ye)]:[]}),de=se.find(ie=>ie.at(-1)===N?.id)??se.sort((ie,ye)=>ye.length-ie.length)[0]??[],J=Z?Y(Z):s.marketKeys?.length?[]:de;m(I?Y(I):J),y(s.kind==="property"&&J.length===0&&f.length>0),c("")},U=I=>{m(Y(I)),y(!1),c(""),x.current?.focus()},F=(I,Z=Wn(I))=>e.jsxs("div",{className:"flex items-stretch",children:[e.jsxs("button",{type:"button",className:yr,"aria-label":I.kind==="group"&&!o?Hn.browse(Wn(I)):Hn.select(Wn(I)),"aria-current":s.kind===I.kind&&s.id===I.id?"true":void 0,onClick:()=>I.kind==="group"&&!o?U(I):z(I),children:[e.jsxs("span",{className:"min-w-0 break-words",children:[Z,A&&j(I)?e.jsx("span",{className:"block text-[13px] text-secondary",children:j(I)}):null]}),e.jsx("span",{className:"shrink-0 text-right text-[13px] text-secondary",children:I.kind==="market"?o?"Query context":"Market":I.kind==="property"?"Property":oo(I.targetCount)})]}),o&&I.kind==="group"&&I.id!==N?.id&&i.some(se=>se.parentGroupIds?.includes(I.id))?e.jsx("button",{type:"button","aria-label":Hn.browse(I.label),title:`Browse ${I.label}`,className:"flex min-h-11 min-w-11 items-center justify-center rounded text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>U(I),children:e.jsx(Ua,{size:18,"aria-hidden":"true"})}):null]},`${I.kind}:${I.id}`),T=(I,Z)=>Z.length>0?e.jsxs("section",{"aria-label":I,className:"mt-2",children:[e.jsx("h3",{className:"px-2 py-2 text-[13px] font-medium text-secondary",children:I}),Z.map(se=>F(se))]}):null,ae=(I,Z,se)=>Z.length>0?e.jsxs("details",{open:se,className:"mt-2 border-y border-default",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer px-2 py-3 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[I," (",Z.length,")"]}),Z.map(de=>F(de))]},`${N?.id??"root"}:${I}`):null;return e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{id:`${g}-label`,className:"mb-1 block text-sm font-medium text-heading",children:r}),e.jsxs("details",{ref:p,className:"relative",onToggle:I=>{I.target===I.currentTarget&&I.currentTarget.open&&x.current?.focus()},onKeyDown:I=>{I.key==="Escape"&&(I.preventDefault(),I.currentTarget.open=!1,I.currentTarget.querySelector("summary")?.focus())},children:[e.jsxs("summary",{id:`${g}-value`,"aria-labelledby":`${g}-label ${g}-value`,className:`${io} visibility-scope-trigger`,onClick:()=>{p.current?.open||V()},children:[`${Wn(s)}${s.kind==="group"?` · ${oo(s.targetCount)}`:s.kind==="property"?` · ${i.find(I=>I.kind==="market"&&I.id===a)?.label??(s.marketKeys?.length?Hn.allMarkets:"Property")}`:s.kind==="market"?" · Market":""}`,e.jsx(vn,{size:16,"aria-hidden":"true",className:"shrink-0 text-secondary"})]}),e.jsxs("div",{className:"visibility-scope-menu",children:[N||u?e.jsxs("div",{className:"mb-2 border-b border-default pb-2",children:[e.jsx("button",{type:"button",className:yr,"aria-label":`Back to ${E?.label??"all groups"}`,onClick:()=>{m(h.slice(0,-1)),y(!1),c(""),x.current?.focus()},children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Um,{size:16,"aria-hidden":"true"}),E?.label??"All groups"]})}),e.jsx("p",{className:"px-2 py-1 text-sm font-medium text-heading","aria-live":"polite",children:N?.label??"All properties"})]}):null,e.jsx("input",{ref:x,type:"search","aria-label":"Search scopes",className:io,placeholder:N?"Search within this group":u?"Search properties":"Search groups or properties",value:d,onChange:I=>c(I.target.value)}),e.jsxs("div",{className:"mt-2 max-h-80 overflow-y-auto",children:[o&&N&&!A?F(N,"All properties in this group"):null,te.map(I=>F(I)),N&&!A?ae("Subgroups",D,!0):T(N?"Subgroups":"Groups",D),A?T("Properties",Q):ae(N&&D.length>0?"All properties":"Properties",Q,!N||D.length===0),T("Markets",C),!N&&!u&&!A&&f.length>0&&w.length>0?e.jsxs("button",{type:"button",className:`${yr} mt-2 border-t border-default`,"aria-label":Hn.browseAll,onClick:()=>{y(!0),x.current?.focus()},children:[e.jsx("span",{children:"All properties"}),e.jsx(Ua,{size:18,"aria-hidden":"true"})]}):null,A&&D.length+Q.length+C.length+te.length===0?e.jsx("p",{className:"py-3 text-sm text-secondary",children:"No matching scopes."}):null]})]})]})]})}const da="__cited__",ua="__mentioned__",us="__mentionShare__";function Bl(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Es(n),end:Es(a),sweepCount:s.sweepCount??1}}function za(t){const s=Bl(t);if(!s)return"Sweep date unavailable";const n=Ys(s.start),a=Ys(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function tp(t){const s=Bl(t);return s?Cl(s.start):""}function On(t){return t.trim().toLowerCase()}function zr(t){return Math.round(t*1e3)/10}function Wr(t){return t.byProvider??{}}function sp(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const c=s==="cited"?da:ua,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(u=>({date:u.startDate,[c]:zr(u[h])})),series:[c],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(c=>Object.keys(Wr(c))))].sort();return{rows:t.buckets.map(c=>{const h={date:c.startDate},m=Wr(c);for(const u of i){const y=m[u];h[u]=y?zr(y[o]):null}return h}),series:i,hasData:a,singleBucket:r}}function Vl(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function np(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function ap(t){return t.servedModelAttribution??{}}function rp(t){return t.modelServiceMismatch??{}}function ip(t){return t.modelPointerChanges??{}}function op(t){return t.length>0?t.join(", "):null}function lo(t,s){const n=On(s);return Object.entries(t).find(([a])=>On(a)===n)?.[1]}function Rs(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return`Mixed: ${t.models.join(", ")}${t.includesUnknown?" + unknown":""}`}}function lp(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!lo(Wr(a),s))continue;const r=Vl(a);return r?lo(r,s)??null:null}return null}function cp(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const o=s.get(r.bucketStartDate)??[];o.push({provider:n,event:r}),s.set(r.bucketStartDate,o)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,o)=>r.provider.localeCompare(o.provider)||r.event.observedAt.localeCompare(o.event.observedAt))}))}function dp(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const o=r.events.filter(i=>!i.fromPreWindowAnchor);for(const i of r.events)i.fromPreWindowAnchor&&n.push({provider:a,event:i});o.length>0&&(s[a]={...r,events:o})}return{buckets:cp(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function up(t){let s=0,n=0;for(const a of Object.values(t))s+=a.events.length,n+=a.eventTotal??a.events.length;return{shown:s,total:n}}function mp(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 hp(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[us]:r?.rate==null?null:zr(r.rate)}}),n=s.map(a=>a[us]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[us],hasData:n.length>0,singleBucket:n.length===1}}function xp(t,s,n){return s==="mentionShare"?hp(t):sp(t,s,n)}function co(t,s){for(let n=t.length-1;n>=0;n--){const a=t[n][s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function uo(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function mo(t){return t>0?`+${t}`:`${t}`}function pp(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${mo(n.delta)} on ${uo(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${mo(s.delta)} on ${uo(s.date)})`}const gp=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],ho="Measured answers",fp="Close answers",Is={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},$n="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",Hr=new Intl.NumberFormat("en",{style:"percent",maximumFractionDigits:1});function yp(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function Cs({value:t,unit:s}){return t.rate===null?e.jsx("span",{className:"text-sm text-secondary",children:t.reason==="identity-ambiguous"?Tt.ambiguous:t.reason==="not-applicable"?"Not applicable":"Not measured"}):e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:Hr.format(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator,s?` ${s}`:""]})]})}const bp={otherQueries:"Other queries"};function vp(t,s){const n=new Map;for(const r of t){const o=n.get(r.queryKey);o?o.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 o=[...new Set(r.rows.flatMap(i=>i.marketKeys??[]))].sort();r.marketLabel=o.map(i=>s.get(i)??i).join(" · ")||bp.otherQueries}return a.sort((r,o)=>r.marketLabel.localeCompare(o.marketLabel)||r.query.localeCompare(o.query))}function xo({value:t,singleAnswer:s}){if(s&&t.denominator===1&&(t.rate===0||t.rate===1)){const n=t.rate===1;return e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm ${n?"text-positive":"text-secondary"}`,children:[n?e.jsx(Bm,{size:16,"aria-hidden":"true"}):e.jsx(jl,{size:16,"aria-hidden":"true"}),n?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Cs,{value:t}),t.reason==="evidence-incomplete"?e.jsx(Ve,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function po({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 jp({group:t,advanced:s,targetLabels:n,marketHeading:a,onViewAnswers:r}){const o=t.rows[0],i=m=>JSON.stringify([...m.targetKeys].sort()),d=t.rows.every(m=>i(m)===i(o)),c=t.rows.every(m=>m.location===o.location),h=m=>m===null?"No location targeting":`Search location: ${m}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[a?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:a})})}):null,e.jsx("tr",{className:"measurement-result-heading",children:e.jsxs("th",{scope:"rowgroup",colSpan:4,children:[e.jsx("h3",{className:"break-words text-base font-medium text-heading",children:t.query}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 text-sm font-normal text-secondary",children:[s&&d?e.jsx(po,{targetKeys:o.targetKeys,labels:n}):null,c?e.jsx("span",{children:h(o.location)}):null]})]})}),t.rows.map(m=>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:ks(m.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:m.model??"Model not recorded"}),s&&!d?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(po,{targetKeys:m.targetKeys,labels:n})}):null,c?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:h(m.location)})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(xo,{value:m.mentionCoverage,singleAnswer:m.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(xo,{value:m.citationCoverage,singleAnswer:m.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(R,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${m.query} · ${m.provider}`,onClick:u=>r(m,u.currentTarget),children:[m.answerCount===1?"View answer":"View answers",e.jsx(Ua,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([m.provider,m.model,m.location])))]})}function Np({population:t}){const s=l.useId();let n=0;const a=t.trend.map((c,h)=>(h>0&&c.continuity.state!=="comparable"&&(n+=1),{createdAt:Date.parse(c.createdAt),[`mentioned-${n}`]:c.mentionCoverage.rate,[`cited-${n}`]:c.citationCoverage.rate})),r=Array.from({length:n+1},(c,h)=>h),o=new Set(t.trend.slice(1).map(c=>c.continuity.state)),i=[...a.length===1?["First measurement. A trend appears after another comparable run."]:[],...o.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...o.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...o.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(c=>c.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[]];if(a.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const d=t.trend.some(c=>c.mentionCoverage.rate!==null||c.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[d?e.jsxs(e.Fragment,{children:[e.jsxs("ul",{"aria-label":"Trend legend",className:"flex gap-5 py-3 text-sm text-secondary",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:it[1]}}),"Mentioned"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:qs.positive}}),"Cited"]})]}),i.length>0&&e.jsx("p",{id:s,className:"pb-3 text-sm text-secondary",children:i.join(" ")}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-describedby":i.length>0?s:void 0,"aria-label":`${Is[t.queryClass]} mention and citation trend`,children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:a,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(oa,{stroke:ia,vertical:!1}),e.jsx(sn,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Lt,tickLine:!1,axisLine:{stroke:ms},tickFormatter:c=>new Date(Number(c)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(nn,{domain:[0,1],tick:Lt,tickLine:!1,axisLine:!1,width:48,tickFormatter:c=>Hr.format(Number(c))}),e.jsx(an,{...ns,formatter:c=>typeof c=="number"?Hr.format(c):"Not measured",labelFormatter:c=>new Date(Number(c)).toLocaleDateString()}),r.map(c=>e.jsxs(l.Fragment,{children:[e.jsx($s,{type:"linear",dataKey:`mentioned-${c}`,name:"Mentioned",stroke:it[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}}),e.jsx($s,{type:"linear",dataKey:`cited-${c}`,name:"Cited",stroke:qs.positive,strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}})]},c))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:d?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${Is[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(c=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(c.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(Cs,{value:c.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:c.citationCoverage})}),e.jsx("td",{children:c.continuity.state.replaceAll("-"," ")})]},c.runId))})]})})]})}function Yr(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function ci(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,o=t.populations.find(h=>h.queryClass===r);if(o)return o;const i=Yr(a,s)??Yr(t,s),d=t.populations.find(h=>h.queryClass===i?.queryClass);if(d)return d;const c=["non-brand","branded","unknown"].map(h=>t.populations.find(m=>m.queryClass===h));return c.find(h=>h&&(h.summary.queryCount>0||h.trend.some(m=>m.queryCount>0)))??c.find(h=>h!==void 0)??t.populations[0]}function wp({report:t,onSelectionChange:s,queryClass:n=ci(t).queryClass}){const{selection:a,scopeOptions:r,filterOptions:o}=t,i=(d,c,h,m)=>e.jsxs("label",{className:"min-w-0",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:d}),e.jsx("select",{"aria-label":d,className:$n,value:h,onChange:u=>s({[c]:u.target.value||void 0,measurementQueryKey:void 0}),children:m.map(u=>e.jsx("option",{value:u.value,children:u.label},u.value))})]});return e.jsx("div",{className:"visibility-filter-container",children:e.jsxs("div",{className:"visibility-report-filters","data-has-scope":r.length>1,role:"group","aria-label":"Visibility filters",children:[r.length>1?e.jsx(Ul,{options:r,selected:a.scope,marketKey:a.market?.id,onSelect:(d,c)=>{s({measurementScope:d.kind,measurementScopeKey:d.kind==="project"?void 0:d.id,measurementMarketKey:c})}}):null,i("Query type","queryClass",n,[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"},{value:"unknown",label:"Unclassified"}]),i("Answer engine","measurementProvider",a.provider??"",[{value:"",label:"All engines"},...o.providers.map(d=>({value:d,label:d}))]),i("Search location","measurementLocation",a.location.kind==="exact"?a.location.value:a.location.kind==="none"?"none":"",[{value:"",label:"All locations"},...o.locations.filter(d=>d.kind!=="all").map(d=>({value:d.kind==="exact"?d.value:"none",label:d.kind==="exact"?d.value:"No location"}))])]})})}function Sp({report:t,isRefreshing:s=!1,onSelectionChange:n,onManageQueries:a,onPage:r,onSearch:o,search:i="",queryKey:d,answerSelection:c,evidenceReport:h,isEvidenceLoading:m=!1,evidenceError:u,onRetryEvidence:y,onEvidencePage:p}){const x=l.useRef(null),g=l.useRef(void 0),f=l.useRef(null),S=ci(t,d,c,h),N=h??t,E=N.populations.filter(C=>[...C.queries.items,...C.evidence.items].some(te=>te.queryKey===d)),A=c?[c.queryClass]:(E.length?E:m?[]:[S]).map(C=>C.queryClass),v=d?JSON.stringify([c??d,A]):void 0,w=l.useId();l.useEffect(()=>{if(!v){s||(g.current=void 0);return}if(g.current===v)return;const C=x.current?.querySelectorAll(`[aria-label="${ho}"]`);if(C?.length){for(const te of C){const z=te.closest("details[data-query-results]");z&&(z.open=!0)}C[0].focus({preventScroll:!0}),C[0].scrollIntoView?.({block:"start"}),g.current=v}},[v,s]);const{selection:j,filterOptions:L}=t,q=j.measurement,D=yp(j.scope),X=new Map(t.scopeOptions.filter(C=>C.kind==="property").map(C=>[C.id,C.label])),G=C=>{const te=N.populations.find(z=>z.queryClass===C.queryClass)?.evidence;return{items:te?.items.filter(z=>z.queryKey===d&&(!c||z.provider===c.provider&&z.model===c.model&&z.location===c.location&&(c.runId===null||z.runId===c.runId)))??[],nextCursor:te?.nextCursor}},K=()=>{g.current=void 0;const C=f.current;C!==null&&C.row.queryKey===d&&(!c||C.row.provider===c.provider&&C.row.model===c.model&&C.row.location===c.location)&&C?.element.isConnected?C.element.focus():x.current?.querySelector(`details[data-query-results="${S.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})},Q=(C,te,z,Y,V)=>e.jsxs("div",{className:"min-w-40 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1",children:[e.jsx("label",{htmlFor:`${w}-${te}`,className:"text-sm font-medium text-heading",children:C}),e.jsx(Ve,{text:V})]}),e.jsx("select",{id:`${w}-${te}`,className:$n,value:z,onChange:U=>n({[te]:U.target.value||void 0,measurementQueryKey:void 0}),children:Y.map(U=>e.jsx("option",{value:U.value,children:U.label},U.value))})]});return e.jsxs("section",{ref:x,className:"visibility-report","aria-label":"AI visibility results",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default pb-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(ce,{tone:q.state==="measured"?"positive":"neutral",children:q.state==="measured"?"Complete":q.state==="partial"?"Partial":"Not measured"}),q.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:new Date(q.completedAt).toLocaleDateString()}):null]}),a?e.jsx(R,{variant:"outline",onClick:a,children:"Manage queries"}):null]}),j.provenance.kind==="legacy-simple"&&j.queryClass!=="unknown"&&j.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(R,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,e.jsx(wp,{report:t,queryClass:S.queryClass,onSelectionChange:n}),e.jsxs("details",{className:"border-b border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"More filters"}),e.jsxs("div",{className:"flex flex-wrap gap-4 pb-3",children:[e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:"Start date (UTC)"}),e.jsx("input",{type:"date",className:$n,value:j.time.from?.slice(0,10)??"",onChange:C=>n({measurementFrom:C.target.value?`${C.target.value}T00:00:00.000Z`:void 0})})]}),e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:"End date (UTC)"}),e.jsx("input",{type:"date",className:$n,value:j.time.to?.slice(0,10)??"",onChange:C=>n({measurementTo:C.target.value?`${C.target.value}T23:59:59.999Z`:void 0})})]}),Q("AI model","measurementModel",j.model??"",[{value:"",label:"All models"},...Array.from(new Set(L.models.filter(C=>!j.provider||C.provider===j.provider).map(C=>C.model))).map(C=>({value:C,label:C}))],"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),Q("Results from","measurementRunId",j.run.explicit?j.run.id??"":"",[{value:"",label:"Latest saved sweep"},...[...S.trend].reverse().map(C=>({value:C.runId,label:new Date(C.createdAt).toLocaleString()}))],"Choose a saved AI sweep to view its results. No new sweep starts.")]})]}),[S].map(C=>{const te=vp(C.queries.items,j.scope.kind==="property"&&!j.market&&C.queryClass==="non-brand"?new Map(t.scopeOptions.filter(V=>V.kind==="market").map(V=>[V.id,V.label])):void 0),z=G(C),Y=z.items[0]?.query??C.queries.items.find(V=>V.queryKey===d)?.query;return e.jsxs("section",{"aria-label":Is[C.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h2",{children:Is[C.queryClass]}),e.jsx(Ve,{text:C.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":C.queryClass==="branded"?"Queries that name the measured identity.":"These queries were not labeled as branded or non-brand when measured. Their saved results remain available here, separate from branded and non-brand rates."})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-8 gap-y-4 border-y border-default py-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:j.mode==="advanced"&&j.scope.kind!=="property"?"Answers mentioning a property":"Mentioned answers"}),j.mode==="advanced"?e.jsx(Ve,{text:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned."}):null]}),e.jsx(Cs,{value:C.summary.mentionCoverage,unit:"answers"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:j.mode==="advanced"&&j.scope.kind!=="property"?"Answers citing a property":"Cited answers"}),j.mode==="advanced"?e.jsx(Ve,{text:"An answer counts when it cites a matching URL for any assigned property. This does not mean every property was cited."}):null]}),e.jsx(Cs,{value:C.summary.citationCoverage,unit:"answers"})]}),j.mode==="advanced"&&j.scope.kind!=="property"?e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Properties mentioned"}),e.jsx(Cs,{value:C.summary.propertyReach,unit:"properties"})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Queries measured"}),e.jsx("strong",{className:"tabular-nums text-heading",children:C.summary.queryCount})]})]}),e.jsx(Np,{population:C}),j.mode==="advanced"?e.jsxs("details",{className:"border-t border-default text-sm text-secondary","aria-label":`${Is[C.queryClass]} property outcomes`,children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Property outcomes"}),e.jsx("div",{className:"flex flex-wrap gap-x-8 gap-y-3 pb-4",children:[["bothSignals","mentioned and cited"],["mentionedOnly","mentioned only"],["citedOnly","cited only"],["neither","neither signal"],["notMeasured","not measured"]].map(([V,U])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:C.summary.outcomes[V]}),e.jsx("span",{className:"text-sm text-secondary",children:U}),V==="notMeasured"?e.jsx(Ve,{text:"No eligible completed measurement for this selection. This is not the same as a measured answer with neither signal."}):null]},V))})]}):null,j.mode==="advanced"&&j.scope.kind!=="property"&&(C.breakdown.groups.length>0||C.breakdown.properties.length>0)?e.jsx(Cp,{population:C,scope:j.scope,scopeOptions:t.scopeOptions,marketKey:j.market?.id,onSelectionChange:n},`${j.scope.kind}:${j.scope.id}`):null,e.jsxs("details",{className:"border-t border-default","data-query-results":C.queryClass,"aria-label":`${Is[C.queryClass]} query results`,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-5 text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[e.jsx("span",{className:"font-semibold",children:"Query results"}),e.jsxs("span",{className:"ml-3 text-sm font-normal text-secondary",children:[C.queries.total," ",C.queries.total===1?"result":"results"," · ",D]})]}),e.jsxs("div",{className:"pb-5",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-3",children:[o?e.jsx("input",{type:"search","aria-label":`Search ${Is[C.queryClass]}`,placeholder:"Search queries",className:`${$n} max-w-sm`,value:i,onChange:V=>o(V.target.value)}):null,e.jsx(Ve,{text:j.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":`${Is[C.queryClass]} engine results`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Answer engine"}),e.jsx("th",{scope:"col",children:"Mentioned"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),te.map((V,U)=>e.jsx(jp,{group:V,marketHeading:V.marketLabel!==te[U-1]?.marketLabel?V.marketLabel:void 0,advanced:j.mode==="advanced",targetLabels:X,onViewAnswers:(F,T)=>{f.current={row:F,element:T},n({measurementQueryKey:F.queryKey,measurementAnswer:JSON.stringify({queryKey:F.queryKey,queryClass:C.queryClass,provider:F.provider,model:F.model,location:F.location,runId:j.run.id,revision:j.revision})})}},V.queryKey))]})}),C.queries.items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:"No measured queries match this selection."}):e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:[te.length," ",te.length===1?"query":"queries"," · ",C.queries.items.length," ",C.queries.items.length===1?"engine result":"engine results"," shown of ",C.queries.total," results"]}),C.queries.nextCursor&&r?e.jsx(R,{variant:"outline",onClick:()=>r(C.queries.nextCursor),children:"Next queries"}):null,d&&A.includes(C.queryClass)?e.jsxs("section",{tabIndex:-1,className:"scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-label":ho,"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:Y??"Answers"}),e.jsx(R,{variant:"ghost",className:"min-h-11",onClick:K,children:fp})]}),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]}),y?e.jsx(R,{variant:"outline",onClick:y,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[z.items.map(V=>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:V.provider}),V.model?e.jsx("span",{className:"text-[13px] text-secondary",children:V.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:V.location??"No location"}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(V.createdAt).toLocaleDateString()}),e.jsx(ce,{tone:"neutral",children:V.mentioned===null?V.mentionUnavailableReason==="identity-ambiguous"?Tt.ambiguous:"Mention not checked":V.mentioned?"Mentioned":"Not mentioned"}),e.jsx(ce,{tone:"neutral",children:V.cited===null?"Citation not checked":V.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(kl,{headingLevel:4,copyable:!!V.answerText?.trim(),children:V.answerText??"Answer text unavailable."})}),V.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:[nh," (",V.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:V.sources.map(U=>{const F=Bs(U);return e.jsx("li",{className:"break-all text-sm",children:F?e.jsx("a",{href:F,target:"_blank",rel:"noopener noreferrer",className:"text-link underline",children:U}):e.jsx("span",{className:"text-secondary",children:U})},U)})})]}):null]},V.answerId)),G(C).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:G(C).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,G(C).nextCursor&&p?e.jsx(R,{variant:"outline",onClick:()=>p(G(C).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"border-t border-default","aria-label":`${Is[C.queryClass]} competitors`,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-5 text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[e.jsx("span",{className:"font-semibold",children:"Competitors"}),e.jsx("span",{className:"ml-3 text-sm font-normal text-secondary",children:C.competitorAvailability.state==="unavailable"?"Not available":`${C.competitors.length} measured`})]}),e.jsxs("div",{className:"pb-5",children:[C.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):C.competitors.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No measured competitors in this selection."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Competitor"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:C.competitors.map(V=>e.jsxs("tr",{children:[e.jsx("td",{children:V.domain}),e.jsx("td",{children:e.jsx(Cs,{value:V.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:V.citationCoverage})})]},V.domain))})]})}),C.observedCompetitors.length>0?e.jsxs("details",{className:"mt-4 text-sm",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-heading",children:"Other names in answers"}),e.jsx("ul",{className:"divide-y divide-default",children:C.observedCompetitors.map(V=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:V.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[V.answerCount," ",V.answerCount===1?"answer":"answers"]})]},V.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},C.queryClass)})]})}function Cp({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const o=new Map(n.filter(u=>u.kind==="group").map(u=>[u.id,u])),i=[...o.values()].some(u=>u.parentGroupIds?.length),d=t.breakdown.groups.filter(u=>{const y=o.get(u.id)?.parentGroupIds??[];return s.kind==="project"?y.length===0:s.kind==="group"&&i?y.includes(s.id):!0}),[c,h]=l.useState(()=>s.kind==="project"&&d.length>0?"groups":"properties"),m=jn({rows:c==="groups"?d:t.breakdown.properties,getSearchText:u=>u.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(u=>e.jsx(R,{variant:c===u?"secondary":"ghost",onClick:()=>{h(u),m.setPage(1)},children:u==="groups"?"Groups":"Properties"},u))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:m.query,onChange:u=>m.setQuery(u.target.value),className:`${$n} 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:c==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:m.rows.map(u=>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:c==="groups"?"group":"property",measurementScopeKey:u.id,measurementMarketKey:a}),children:u.label})}),e.jsx("td",{children:u.queryCount}),e.jsx("td",{children:e.jsx(Cs,{value:u.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:u.citationCoverage})})]},u.id))})]})}),m.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",c," match this search."]}):null,e.jsx(Ls,{page:m.page,pageSize:m.pageSize,visibleRows:m.rows.length,totalRows:m.totalRows,itemLabel:c,onPageChange:m.setPage})]})}function kp({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,fallback:r,showUnmeasuredFallback:o=!1}){const[i,d]=l.useState(),[c,h]=l.useState(""),[m,u]=l.useState(),y=xs(),p=l.useMemo(()=>({scope:s.measurementScope,scopeKey:s.measurementScopeKey,marketKey:s.marketKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId}),[s.measurementScope,s.measurementScopeKey,s.marketKey,s.queryClass,s.provider,s.model,s.location,s.from,s.to,s.revision,s.measurementRunId]),x=Te({...sr({client:H,path:{name:t},query:{...p,limit:25,cursor:i,search:c||void 0}}),staleTime:pd,retry:!1,placeholderData:ai}),g={...p,queryKey:s.queryKey,queryClass:s.answer?.queryClass??s.queryClass,provider:s.answer?.provider??s.provider,model:s.answer?s.answer.model??void 0:s.model,location:s.answer?s.answer.location??"none":s.location,runId:s.answer?.runId??x.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??x.data?.selection.revision??s.revision,limit:50},f=JSON.stringify(g),S=Te({...sr({client:H,path:{name:t},query:{...g,cursor:m?.selection===f?m.cursor:void 0}}),enabled:!!s.queryKey&&!!x.data&&!x.isPlaceholderData,retry:!1});if(l.useEffect(()=>{if(s.queryClass!=="all"||!x.data||x.isPlaceholderData||x.isFetching||x.isError||x.data.selection.availability.state==="unsupported"||x.data.populations.length===0||s.queryKey&&!s.answer&&!Yr(x.data,s.queryKey)&&!S.data)return;const N=ci(x.data,s.queryKey,s.answer,S.data);if(!i&&!c){const{queryKey:E}=sr({client:H,path:{name:t},query:{...p,queryClass:N.queryClass,limit:25}});y.setQueryData(E,{...x.data,selection:{...x.data.selection,queryClass:N.queryClass},populations:[N]},{updatedAt:x.dataUpdatedAt})}n({queryClass:N.queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}})},[s.queryClass,s.queryKey,s.answer,x.data,x.dataUpdatedAt,x.isPlaceholderData,x.isFetching,x.isError,S.data,n,y,t,p,i,c]),x.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:r});if(o&&x.data?.selection.mode==="simple"&&x.data.selection.measurement.state==="not-measured")return e.jsx(e.Fragment,{children:r});if(x.error){const N=aa(x.error),E=s.measurementScope!=="project"&&N.includes("scope")&&N.includes("is not in this frozen definition.");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:E?"This saved group or property filter is unavailable for this measurement. Show the whole site to choose another.":N}),E?e.jsx(R,{variant:"outline",onClick:()=>{d(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:"Show whole site"}):e.jsx(R,{variant:"outline",onClick:()=>{d(void 0),x.refetch()},children:"Retry"})]})}return x.data?e.jsx("div",{"aria-busy":x.isFetching,children:e.jsx(Sp,{report:x.data,isRefreshing:x.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:S.data,isEvidenceLoading:S.isFetching||!!s.queryKey&&S.isPending,evidenceError:S.error?aa(S.error):void 0,onRetryEvidence:()=>{S.refetch()},onEvidencePage:S.isFetching?void 0:N=>u({selection:f,cursor:N}),search:c,onSearch:N=>{h(N),d(void 0)},onPage:x.isFetching?void 0:d,onSelectionChange:N=>{(!("measurementQueryKey"in N)||Object.keys(N).some(E=>E!=="measurementQueryKey"&&E!=="measurementAnswer"))&&d(void 0),u(void 0),n(N)},onManageQueries:a})}):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"})})}const Ap=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Pp=[{value:"mentioned",label:"Mentioned",description:"Your brand or domain appears in the answer text."},{value:"cited",label:"Cited",description:"Your domain appears in source or grounding links."},{value:"mentionShare",label:"Mention share",description:"On non-brand queries, the share of answer-text brand mentions for you and tracked competitors that were you. Pooled only when query classification is unavailable."}],di=it[2],Rp="var(--chart-tooltip-bg)",Ip={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function ks(t){const s=On(t);return Ip[s]??t.charAt(0).toUpperCase()+t.slice(1)}function zs(t){return Math.round(t*10)/10}function Tp(t){return t===da||t===ua||t===us}function Ql(t){return t===da?"Cited":t===ua?"Mentioned":t===us?"Mention share":ks(t)}function Xn(t,s){return t===da?qs.positive:t===ua?it[1]:t===us?di:Ym(On(t),s)}function $p(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Mp(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
|
-
`)}function Xa(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function Oa(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${Xa(s)}`:"Mention share":"Mentioned"}function la(t){return t==="cited"?"citationRate":"mentionRate"}function zl(t,s){return s==="cited"?t.cited:t.mentionedCount}function Wl(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 Hl(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Jr(t){const s=Vl(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>On(a).localeCompare(On(r))).map(([a,r])=>`${ks(a)}: ${Rs(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function Lp(t){return t.some(({event:s})=>s.to.status==="mixed")?qs.caution:t.some(({event:s})=>s.to.status==="unknown")?qs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?it[4]:qs.positive}function qp(t,s,n){const a=Hl(t,s);return a?za(a):Ys(Es(n))}function Ep({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:o,mismatch:i,buckets:d}){const c=l.useId(),h=Object.entries(o).sort(([u],[y])=>u.localeCompare(y)),m=t.buckets.length>0||t.beforeWindow.length>0;return!s||!m?null:e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":c,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:c,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:u,events:y})=>y.map(({provider:p,event:x})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:qp(d,u,x.observedAt)}),e.jsxs("span",{children:[ks(p),": ",Rs(x.from)," → ",Rs(x.to)]})]},`${p}-${x.observedAt}-${x.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:u,event:y})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Ys(Es(y.observedAt))]}),e.jsxs("span",{children:[ks(u),": ",Rs(y.from)," → ",Rs(y.to),y.anchorObservedAt?` (last seen ${Rs(y.from)} on ${Ys(Es(y.anchorObservedAt))})`:""]})]},`before-${u}-${y.observedAt}`))})]}),a.map(u=>e.jsxs("p",{className:"trend-model-evidence-note",children:[ks(u.provider),": showing the most recent ",u.shown," of ",u.total," changes."]},`truncated-${u.provider}`)),r.map(u=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",ks(u)," change."]},`incomplete-${u}`)),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:h.map(([u,y])=>{const p=op(y.latestServedModelIds),x=i[u];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Ys(Es(y.latestObservation.observedAt))}),e.jsxs("span",{children:[ks(u),": ",p??Rs(y.latestObservation.state),x?` — not the ${Rs(x.configured)} you selected`:""]})]},`served-${u}`)})})]})]})}function go(t){return t===null?"no data":`${t}%`}function br(t){return t==null?"undefined":`${zs(t*100)}%`}function Dp({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=Hl(o,s);if(!i)return null;if(a==="mentionShare"){const c=i.mentionShare.projectMentionSnapshots,h=i.mentionShare.competitorMentionSnapshots,m=c+h,u=i.mentionShare.rate==null?null:zs(i.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:za(i)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:di},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",Xa(i.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:go(u)})]}),m>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",c," / ",m," brand mentions. Competitors ",h,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:Jr(i)})]})}const d=r==="byProvider"?(n??[]).filter(c=>c.dataKey!==void 0):[{dataKey:a==="cited"?da:ua,value:zs(i[la(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:za(i)}),d.map((c,h)=>{const m=String(c.dataKey??c.name??""),u=r==="byProvider"?Wl(i,m,a):null,y=u?.count??zl(i,a),p=u?.total??i.total,x=typeof c.value=="number"?c.value:zs(u?u.rate*100:i[la(a)]*100),g=c.color??Xn(m,h);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:g},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Ql(m)}),e.jsx("span",{className:"trend-tooltip-value",children:go(x)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[y," / ",p," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${m}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:Jr(i)})]})}function Op({buckets:t,metric:s,mode:n,series:a}){const r=t[t.length-1]?.mentionShare.scope;return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[Oa(s,r)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(o=>{let i;if(s==="mentionShare"){const d=o.mentionShare.projectMentionSnapshots,c=o.mentionShare.competitorMentionSnapshots,h=d+c,m=Xa(o.mentionShare.scope);i=h>0?`${br(o.mentionShare.rate)} mention share for ${m}, ${d} of ${h} brand mentions were you`:`mention share undefined for ${m}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(d=>{const c=Wl(o,d,s);return c?`${ks(d)} ${br(c.rate)} ${Oa(s).toLowerCase()}, ${c.count} of ${c.total} snapshots`:`${ks(d)} no data`}).join("; "):i=`${br(o[la(s)])} ${Oa(s).toLowerCase()}, ${zl(o,s)} of ${o.total} snapshots`;return i+=`; ${Jr(o)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:za(o)}),e.jsx("td",{children:i})]},o.startDate)})})]})}function vr({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const o=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(i=>{const d=s===i.value,c=i.description?`${o}-${i.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":d,"aria-describedby":c,className:`segmented-option ${d?"segmented-option-active":""}`,onClick:()=>n(i.value),children:i.label}),i.description&&e.jsx("span",{id:c,className:"sr-only",children:i.description})]},i.value)})})}function Fp({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[o,i]=l.useState("mentioned"),[d,c]=l.useState("byProvider"),h=l.useMemo(()=>Mp(s),[s]),m=Te({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>hd(t,a),staleTime:ii}),u=m.data??null,y=m.error,p=o==="mentionShare"?"overall":d,x=l.useMemo(()=>u?xp(u,o,p):null,[u,o,p]),g=u?np(u):null,f=l.useMemo(()=>dp(g??{}),[g]),S=l.useMemo(()=>up(g??{}),[g]),N=l.useMemo(()=>mp(g??{}),[g]),E=l.useMemo(()=>Object.entries(g??{}).filter(([,F])=>F.anchorUnavailable).map(([F])=>F).sort(),[g]),A=l.useMemo(()=>u?ap(u):{},[u]),v=l.useMemo(()=>u?rp(u):{},[u]),w=l.useMemo(()=>u?xd(ip(u)):null,[u]),j=o!=="mentionShare"&&p==="byProvider",L=u?.buckets??[],q=L[L.length-1]?.mentionShare.scope??u?.mentionShareScope??"pooled",D=Oa(o,q),X=o==="cited"?qs.positive:o==="mentionShare"?di:it[1],G=j?hs.textDim:X,K=l.useMemo(()=>{const F=new Map(L.map(T=>[T.startDate,tp(T)]));return T=>F.get(String(T))??""},[L]),Q=o==="mentionShare"?x?co(x.rows,us):null:L.length>0?zs(L[L.length-1][la(o)]*100):null,C=o==="mentionShare"?x?$p(x.rows,us):null:L.length>0?zs(L[0][la(o)]*100):null,te=o==="mentionShare"?x?.rows.filter(F=>typeof F[us]=="number").length??0:L.length,z=Q!==null&&C!==null&&te>1?zs(Q-C):null,Y=s.length,V=e.jsxs(e.Fragment,{children:[w?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:w.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(Ve,{text:"Three separate signals over sweep buckets: answer text mentions, source citations, and your answer-text mention share against tracked competitors. Mentioned and Cited use all query-provider snapshots. Mention share uses non-brand queries when classification is available; pooled means the project has no usable brand identity for a split."})]})]}),Q!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:G},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:D}),j&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[Q,"%"]}),z!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${z>0?"text-positive-400":z<0?"text-negative-400":"text-muted"}`,children:[z>0?"+":"",z.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(vr,{options:Pp,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(vr,{options:Ap,value:d,onChange:c,ariaLabel:"Series"}),e.jsx(vr,{options:gp,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let U;if(y)U=e.jsx("p",{className:"text-sm text-negative-400",children:aa(y)});else if(m.isLoading&&!u)U=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(o==="mentionShare"&&Y===0)U=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!u||!x)U=null;else{const{rows:F,series:T,hasData:ae}=x,I=pp(u.queryChanges);if(!ae)U=e.jsx("p",{className:"text-sm text-secondary",children:o==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${Xa(q)} in this window yet.`:Kt()?Zs:"Run a sweep to start tracking citations and mentions over time."});else if(j&&T.length===0)U=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 Z=`${D} rate across ${F.length} ${F.length===1?"sweep":"sweeps"}. Latest ${Q}%${z!==null?`, ${z>=0?"up":"down"} ${Math.abs(z).toFixed(1)} points over the period`:""}.`;U=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:Z}),e.jsx(Op,{buckets:L,metric:o,mode:p,series:T}),j&&T.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:T.map((se,de)=>{const J=co(F,se),ie=lp(L,se),ye=g===null?"Attribution unavailable":ie?Rs(ie):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:Xn(se,de)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:Ql(se)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),ye]})]}),J!==null&&e.jsxs("span",{className:"trend-legend-value",children:[J,"%"]})]},se)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${D} trend chart over ${F.length} ${F.length===1?"bucket":"buckets"}`,children:e.jsx(en,{width:"100%",height:"100%",children:e.jsxs(tn,{data:F,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(oa,{stroke:ia,vertical:!1}),e.jsx(sn,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:ms},tickFormatter:K,minTickGap:24}),e.jsx(nn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:se=>`${se}%`,tick:Lt,tickLine:!1,axisLine:!1,width:40}),e.jsx(an,{cursor:{stroke:ms,strokeWidth:1},content:e.jsx(Dp,{metric:o,mode:p,buckets:L})}),f.buckets.map(({bucketStartDate:se,events:de})=>e.jsx(sh,{x:se,stroke:Lp(de),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${se}`)),T.map((se,de)=>e.jsx($s,{type:"monotone",dataKey:se,name:se,stroke:Xn(se,de),strokeDasharray:se===us?"5 4":void 0,strokeWidth:Tp(se)?2.5:2,dot:se===us?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:Xn(se,de),strokeWidth:1.5}:{r:2.5,fill:Xn(se,de),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Rp},connectNulls:se!==us,isAnimationActive:!1},se))]})})}),e.jsx(Ep,{partition:f,available:g!==null,counts:S,truncated:N,incompleteHistory:E,served:A,mismatch:v,buckets:L}),I&&e.jsx("p",{className:"visibility-trend-note",children:I})]})}}return e.jsxs("section",{className:"visibility-trend",children:[V,U]})}const fo=new Set([sa.queued,sa.running]),Mt={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 yo({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:o,scopeError:i,onRetryScope:d,templates:c=[],viewerResearchConfig:h=null}){const m=xs(),{account:u,canWrite:y}=wn(),p=u?.role==="viewer"&&h!==null,x=!y,g=Ms(),[f,S]=l.useState(""),[N,E]=l.useState(""),[A,v]=l.useState(null),[w,j]=l.useState([]),L=l.useRef(null),q=l.useRef(!1),[D,X]=l.useState(0),G=Te({...gd({client:H,path:{name:t}}),staleTime:6e4}),K=Te({...fd({client:H}),enabled:!x&&!g,staleTime:6e4}),Q={client:H,path:{name:t},query:{limit:20}},C=el({...yd(Q),initialData:void 0,initialPageParam:Q,getNextPageParam:B=>B.nextCursor?{path:Q.path,query:{...Q.query,cursor:B.nextCursor}}:void 0,refetchInterval:B=>B.state.data?.pages.some(xe=>xe.runs.some(Se=>fo.has(Se.status)))?3e3:!1}),te=C.isError&&!C.isFetchNextPageError,z=C.data?.pages.at(-1),Y=te?[]:[...new Map((C.data?.pages.flatMap(B=>B.runs)??[]).map(B=>[B.id,B])).values()],V=z?.access?.canRun??(y||p),U=z?.access?z.access.dailyRunLimit:p?h.viewerDailyRunLimit:null;l.useEffect(()=>{!A&&Y[0]&&v(Y[0].id)},[Y,A]);const F=Y.find(B=>B.id===A)??null,T=Te({...bd({client:H,path:{name:t,runId:A??""}}),enabled:!te&&!!A,refetchInterval:F&&fo.has(F.status)?3e3:!1}),ae=te||T.isError?null:T.data??null,I=G.data?.locations??[],Z=l.useMemo(()=>{if(x)return(z?.providers??[]).map(xe=>({...xe,catalog:xe}));const B=new Map((K.data?.providerCatalog??[]).map(xe=>[xe.name,xe]));return(K.data?.providers??[]).filter(xe=>xe.configured&&B.get(xe.name)?.mode==="api").map(xe=>({...xe,catalog:{...B.get(xe.name),defaultModel:xe.model||B.get(xe.name).defaultModel}}))},[x,z?.providers,K.data]),se=!(x?C.isPending:K.isPending)&&Z.length===0,de=Z.find(B=>B.name===f)??null;l.useEffect(()=>{if(!f&&G.data&&!G.isError&&!K.isError){const B=G.data.providers.find(xe=>Z.some(Se=>Se.name===xe));S(B??Z[0]?.name??"")}},[f,Z,G.data,G.isError,K.isError]);const J=de?.catalog.modelConfigurable??!1,ie=x?de?.catalog.defaultModel:(de?G.data?.providerModels[de.name]:"")||de?.catalog.defaultModel,ye=(J?N.trim():"")||ie,ee=de?[...new Map([{id:de.catalog.defaultModel,displayName:de.catalog.defaultModel},...N.trim()?[{id:N.trim(),displayName:N.trim()}]:[],...de.catalog.knownModels].map(B=>[B.id,B])).values()]:[],me=Pt({...vd(),onSuccess:async B=>{L.current=null,X(xe=>xe+1),j(B.runs),v(B.runs[0]?.id??null),await Hp(m),$e({title:"Research batch saved",detail:`${B.runs.length} ${B.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${B.runs.map(xe=>xe.id).join(":")}`,dedupeMode:"replace"})},onError:B=>{$e({title:"Could not start research",detail:B instanceof Error?B.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{q.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[g?e.jsx(pe,{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(Kp,{projectName:t,canWrite:y,researchAllowed:V&&!te,limitedAccess:x,isEmbed:oe(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:o,scopeError:i,onRetryScope:d,templates:c,locations:I,defaultLocation:G.data?.defaultLocation??null,providerOptions:Z,provider:f,onProviderChange:B=>{S(B),E("")},resolvedModel:ye,visibilityModel:ie,configurableModel:J,model:N,onModelChange:E,modelOptions:ee,settingsReady:x?!C.isPending&&!te:!K.isPending&&!K.isError&&!K.isFetching,projectReady:!G.isPending&&!G.isError&&!G.isFetching,isPending:me.isPending,errorMessage:me.isError?"The request could not be confirmed.":void 0,onSubmit:(B,xe)=>{!V||te||oe()||q.current||(L.current?.fingerprint!==xe&&(L.current={fingerprint:xe,key:crypto.randomUUID()}),q.current=!0,me.mutate({client:H,path:{name:t},body:{...B,idempotencyKey:L.current.key}}))}},`${t}:${D}`),U!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",U," destination runs per project per day."]}),!x&&K.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(R,{variant:"outline",onClick:()=>{K.refetch()},children:"Retry providers"})]}):null,G.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(R,{variant:"outline",onClick:()=>{G.refetch()},children:"Retry locations"})]}):null,!(x?te:K.isError)&&se&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:x?"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."}),w.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",w.map((B,xe)=>e.jsxs("span",{children:[xe>0?", ":"",e.jsxs("a",{href:`#research-run-${B.id}`,className:"text-link underline",onClick:()=>v(B.id),children:[B.scope?.label??"Whole site",B.location?`, ${B.location.label}`:", No location"]})]},B.id))]})]}),e.jsxs(pe,{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:Mt.historyTitle})}),C.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),te?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(R,{variant:"outline",onClick:()=>{C.refetch()},children:"Retry history"})]}):C.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):Y.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:Mt.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:Y.map(B=>e.jsxs("tr",{className:A===B.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:()=>v(B.id),children:Qp(B.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:B.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:B.requestedModel??B.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:B.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:B.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[B.completedQueries+B.failedQueries,"/",B.totalQueries]}),e.jsx("td",{children:e.jsx(ce,{tone:Yl(B.status),children:B.status})})]},B.id))})]})}),C.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:Mt.historyMoreError}),C.hasNextPage&&e.jsx(R,{className:"mt-3",variant:"outline",disabled:C.isFetching,onClick:()=>{C.fetchNextPage()},children:C.isFetchingNextPage?Mt.historyLoading:Mt.historyMore})]})]}),!te&&T.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(R,{variant:"outline",onClick:()=>{T.refetch()},children:"Retry results"})]}):te?null:e.jsx(Bp,{detail:ae,isLoading:T.isFetching,onReviewForTracking:g?void 0:s})]})}const Ss="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",Mn="__none__";function Kp(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:o}=t,i=xs(),[d,c]=l.useState("once"),[h,m]=l.useState(""),[u,y]=l.useState(""),[p,x]=l.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[g,f]=l.useState(null),[S,N]=l.useState([]),[E,A]=l.useState(""),[v,w]=l.useState({}),[j,L]=l.useState(null),[q,D]=l.useState([]),[X,G]=l.useState(null),[K,Q]=l.useState(!1),[C,te]=l.useState(!1),[z,Y]=l.useState(""),[V,U]=l.useState(""),F=l.useRef(null),T=l.useRef(!1),ae=l.useRef(null),I=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";l.useEffect(()=>{x(I),L(null)},[I]);const Z=t.scopeOptions.filter(k=>k.kind==="market"||k.kind==="property"),se=d==="markets"?"market":"property",de=Z.filter(k=>k.kind===se),J=k=>({kind:k.kind,key:k.id,label:k.label,planRevision:o??t.initialScope?.planRevision??0}),ie=k=>k===Mn?null:n.find(Ie=>Ie.label===k),ye=g??t.defaultLocation??Mn,ee=Z.find(k=>`${k.kind}:${k.id}`===p),me=ee?J(ee):null,B=d==="once"?[{scope:me,location:ie(ye)}]:d==="locations"?S.map(k=>({scope:null,location:ie(k)})):S.map(k=>de.find(Ie=>`${Ie.kind}:${Ie.id}`===k)).map(k=>k?{scope:J(k),location:ie(v[`${k.kind}:${k.id}`]??Mn)}:null),xe=[...new Map([...q,...t.templates].map(k=>[k.id,k])).values()],Se=j?xe.find(k=>k.id===j.id):null,Ce=j!==null&&Se?.version!==j.version,tt=d==="once"?h:u,Qe=tt.split(/\r?\n/).filter(k=>k.trim()),Ge=Ai(Qe),st=[...new Set([...u.matchAll(/\{([^{}]+)\}/g)].map(k=>k[1]))],qe=/[{}]/.test(u.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),O=[];Qe.length||O.push(d==="once"?"Enter at least one query.":"Enter at least one query pattern."),Qe.some(k=>k.length>4e3)&&O.push("Keep each query under 4,001 characters."),d!=="once"&&qe&&O.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),B.length||O.push(d==="locations"?"Select at least one location.":"Select at least one destination."),B.some(k=>!k||k.location===void 0)&&O.push("A selected destination or location is no longer available. Update your selection.");const Le=d==="once"&&p!=="project"||d==="markets"||d==="properties";Le&&(t.scopePending||t.scopeError||!o||B.some(k=>!k?.scope))&&O.push("Load the current published markets and properties before running scoped research.");const P=(d==="once"?Ge.length:Qe.length)*B.length;if(B.length>va&&O.push(`Select at most ${va} destinations.`),P>ar&&O.push(`${P} queries selected. Reduce the selection to ${ar} or fewer.`),Ce&&O.push("This saved pattern changed. Select its current version from Saved patterns."),d!=="once"&&!qe){for(const k of B)if(!(!k||k.location===void 0))try{nr(j??{pattern:u,variables:st},k.scope,k.location)}catch{O.push(`Choose a location for {location}, or use only variables available for ${d==="markets"?"markets":d==="properties"?"properties":"locations"}.`);break}}const ge=JSON.stringify({mode:d,source:tt,contexts:B,provider:a,resolvedModel:r,template:j,...Le?{planRevision:o}:{}}),Oe=X!==null&&X.signature!==ge,We=d==="once"?Ge.map((k,Ie)=>({id:String(Ie),query:k,scope:me,location:B[0]?.location??null})):X?.rows??[],_e=Up(We),he=[];d!=="once"&&X&&(Oe&&he.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),We.some(k=>!k.query.trim()||k.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(k.query))&&he.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),We.some(k=>k.location&&!n.some(Ie=>JSON.stringify(Ie)===JSON.stringify(k.location)))&&he.push("A preview location changed. Regenerate the preview."),_e.some(k=>Ai(k.queries).length!==k.queries.length)&&he.push("Remove duplicate queries within each destination and location."),_e.length>va&&he.push(`The preview exceeds ${va} runs.`));const xt=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!O.length&&!he.length&&(d==="once"||X!==null),Ue=()=>({runs:_e.map(k=>({queries:k.queries,provider:a,model:r,location:k.location,...k.scope?{scope:{kind:k.scope.kind,key:k.scope.key,expectedPlanRevision:k.scope.planRevision}}:{},...k.template?{template:k.template}:{}}))}),Fe=()=>{if(Q(!0),O.length)return;const k=B.flatMap((Ie,we)=>Qe.map((ze,yt)=>({id:`${we}:${yt}`,scope:Ie.scope,location:Ie.location,...j?{template:{templateId:j.id,templateVersion:j.version,bindingLocation:Ie.location}}:{},query:nr({pattern:ze,variables:[...new Set([...ze.matchAll(/\{([^{}]+)\}/g)].map(nt=>nt[1]))]},Ie.scope,Ie.location).output})));G({signature:ge,rows:k})},kt=k=>{c(k),N([]),L(null),A(""),Q(!1)},Xe=k=>{if(U(""),d==="once")try{m(nr(k,me,ie(ye)).output)}catch{U("Select a matching market, property, or location before using this pattern.");return}else y(k.pattern);L(k)},ke=k=>{const Ie=ae.current,we=Ie?.selectionStart??u.length,ze=Ie?.selectionEnd??we;y(`${u.slice(0,we)}{${k}}${u.slice(ze)}`),L(null),requestAnimationFrame(()=>{Ie?.focus(),Ie?.setSelectionRange(we+k.length+2,we+k.length+2)})},ot=Pt({...Nd(),onSuccess:async k=>{const Ie={id:k.id,version:k.updatedAt,label:k.name,pattern:k.pattern,variables:k.variables};D(we=>[...we.filter(ze=>ze.id!==k.id),Ie]),L(Ie),te(!1),Y(""),U(""),F.current=null,await i.invalidateQueries({queryKey:jd({client:H,path:{name:s}})}),$e({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>U("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{T.current=!1}}),ft=()=>{if(!t.canWrite||t.isEmbed||T.current)return;const k=d==="once"?h:u,Ie=d==="once"?[]:st;if(!z.trim()||!k.trim()||k.length>4e3||d!=="once"&&qe){U("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const we={name:z.trim(),pattern:k,variables:Ie},ze=JSON.stringify(we);F.current?.fingerprint!==ze&&(F.current={fingerprint:ze,id:crypto.randomUUID()}),T.current=!0,ot.mutate({client:H,path:{name:s,templateId:F.current.id},body:we})},qt=[...new Set([...K||tt.trim()?O:[],...he])],De=xe.filter(k=>{const Ie=d==="once"?Pi(me,ie(ye)):Pi(d==="markets"?{kind:"market",label:"Market"}:d==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return k.variables.every(we=>Ie[we]!==void 0)});return e.jsxs(pe,{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||ot.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:Ss,value:d,disabled:t.isPending,onChange:k=>kt(k.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!Z.some(k=>k.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!Z.some(k=>k.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),d==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(Z.length>0||p!=="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:Ss,value:p,onChange:k=>{x(k.target.value),L(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),p!=="project"&&!ee&&e.jsx("option",{value:p,disabled:!0,children:"Selected destination unavailable"}),Z.map(k=>e.jsxs("option",{value:`${k.kind}:${k.id}`,children:[k.label," (",k.kind,")"]},`${k.kind}:${k.id}`))]})]}),e.jsx(Xr,{label:"Answer engine location",value:ye,locations:n,onChange:k=>{f(k),L(null)}})]}),d!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:d==="locations"?"Select locations":`Select ${d}`}),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:Ss,placeholder:`Search ${d}`,value:E,onChange:k=>A(k.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(d==="locations"?n.map(k=>({key:k.label,label:k.label})):de.map(k=>({key:`${k.kind}:${k.id}`,label:k.label}))).filter(k=>k.label.toLocaleLowerCase().includes(E.toLocaleLowerCase())).map(k=>{const Ie=S.includes(k.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:Ie,onChange:()=>N(we=>Ie?we.filter(ze=>ze!==k.key):[...we,k.key])}),k.label]}),Ie&&d!=="locations"&&e.jsx(Xr,{label:`Answer engine location for ${k.label}`,value:v[k.key]??Mn,locations:n,onChange:we=>w(ze=>({...ze,[k.key]:we}))})]},k.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[S.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(R,{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:d==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:d==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${d==="markets"?"market":d==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:ae,className:`${Ss} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:tt,placeholder:d==="once"?Mt.queryPlaceholder:d==="markets"?"Best apartments in {market}":d==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:k=>{d==="once"?m(k.target.value):(y(k.target.value),L(null))}}),d!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>ke(d==="markets"?"market":d==="properties"?"property":"location"),children:["Insert ",d==="markets"?"market":d==="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:[P," / ",ar," queries",d==="once"?"":` across ${B.length} destinations`]})]}),d!=="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."}),De.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:De.map(k=>e.jsx(R,{size:"sm",variant:"outline",onClick:()=>Xe(k),children:k.label},k.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),j&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",j.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(R,{size:"sm",variant:"outline",onClick:()=>te(!C),children:C?"Cancel save":"Save as a pattern"}),C&&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:Ss,value:z,maxLength:120,onChange:k=>Y(k.target.value)})]}),e.jsx(R,{size:"sm",disabled:ot.isPending||!z.trim()||!tt.trim(),onClick:ft,children:ot.isPending?"Saving…":"Save pattern"})]})]}),V&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:V})]})]}),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:Ss,value:a,onChange:k=>t.onProviderChange(k.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose an answer engine"}),t.providerOptions.map(k=>e.jsx("option",{value:k.name,children:k.displayName??k.name},k.name))]})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Model",t.limitedAccess?e.jsxs("select",{className:Ss,value:t.model,disabled:!a||!t.configurableModel,onChange:k=>t.onModelChange(k.target.value),children:[e.jsxs("option",{value:"",children:["Use AI Visibility model · ",t.visibilityModel]}),t.modelOptions.map(k=>e.jsx("option",{value:k.id,children:k.displayName},k.id))]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{"aria-label":"Model",className:Ss,list:"research-known-models",placeholder:r??"Choose an answer engine",value:t.model,disabled:!a||!t.configurableModel,onChange:k=>t.onModelChange(k.target.value)}),e.jsx("datalist",{id:"research-known-models",children:t.modelOptions.map(k=>e.jsx("option",{value:k.id,children:k.displayName},k.id))})]})]})]}),qt.length>0&&e.jsx(_p,{errors:qt}),d!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(R,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:Fe,children:[e.jsx(ra,{size:14}),X?Mt.refreshPreview:"Preview queries"]}),X&&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:[We.length," query executions in ",_e.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(Gp,{rows:We,locations:n,onChange:(k,Ie)=>G(we=>we&&{...we,rows:we.rows.map(ze=>ze.id===k?{...ze,...Ie}:ze)})})]})]}),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(R,{size:"sm",disabled:!xt,onClick:()=>{if(xt){const k=Ue();t.onSubmit(k,JSON.stringify({projectName:s,...k}))}},children:[e.jsx(Ba,{size:14}),t.isPending?"Starting…":Mt.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[d==="once"?`${Ge.length} queries`:`${We.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function Xr({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:Ss,value:s,onChange:r=>a(r.target.value),children:[e.jsx("option",{value:Mn,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function Gp({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:`${Ss} min-h-20`,"aria-label":`Query ${r+1} for ${a.scope?.label??a.location?.label??"Whole site"}`,value:a.query,onChange:o=>n(a.id,{query:o.target.value})})]}),e.jsx(Xr,{label:`Location for query ${r+1}`,value:a.location?.label??Mn,locations:s,onChange:o=>n(a.id,{location:s.find(i=>i.label===o)??null})})]},a.id))})}function _p({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 Up(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 Bp({detail:t,isLoading:s,onReviewForTracking:n}){const[a,r]=l.useState(null);l.useEffect(()=>{r(t?.queries[0]?.id??null)},[t?.id]);const o=t?.queries.find(i=>i.id===a)??t?.queries[0]??null;return e.jsxs(pe,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":Mt.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 ${zp(t.id)}`:Mt.resultsEmpty})]}),t&&e.jsx(ce,{tone:Yl(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:Mt.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,d])=>`${i}: ${d}`).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:Mt.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:Mt.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:o?.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(ce,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?Mt.brandedQuery:i.queryClass==="non-brand"?Mt.discoveryQuery:Mt.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(ce,{tone:Wp(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(ce,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===yn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===yn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(ce,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===yn.failed?"negative":"caution",children:i.citationState===null?i.status===yn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(Vp,{query:o,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 Vp({query:t,isLoading:s,scope:n,onReviewForTracking:a}){return t?e.jsxs("div",{className:"min-w-0 space-y-4 border-t border-default pt-4 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),!oe()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(Je,{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(kl,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===yn.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-1",children:t.groundingSources.map((r,o)=>{const i=Bs(r.uri),d=r.title||r.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:d}):e.jsx("span",{className:"truncate text-secondary",children:d}),i&&e.jsx(Vm,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${r.uri}-${o}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function Qp(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 zp(t){return t.length>8?t.slice(0,8):t}function Yl(t){return t===sa.completed?"positive":t===sa.partial?"caution":t===sa.failed?"negative":"neutral"}function Wp(t){return t===yn.completed?"positive":t===yn.failed?"negative":"neutral"}async function Hp(t){await Ct(t,"researchRuns")}const Zr=new Set(["queued","seeding","probing"]);function Yp({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:o={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:d,onTrackingQueryIdChange:c}){const{account:h}=wn(),[m,u]=l.useState("tracked"),[y,p]=l.useState("find"),[x,g]=l.useState(null),f=h?.role==="viewer"?wd():null,S=h?.role!=="viewer"||f!==null,N=s??m,E=N==="research"&&!S?"tracked":N,A=a??y,v=L=>{s===void 0&&u(L),n?.(L)},w=L=>{a===void 0&&p(L),r?.(L)},j=(L,q)=>{const D=q===void 0?{...o}:{...o,measurementScope:q?.kind??"project",measurementScopeKey:q?.key};g({...L,trackingSelection:D}),q!==void 0&&i?.({measurementScope:D.measurementScope,measurementScopeKey:D.measurementScopeKey}),v("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(Wa,{active:E==="tracked",label:"Tracked",onClick:()=>v("tracked")}),S?e.jsx(Wa,{active:E==="research",label:"Research",onClick:()=>v("research")}):null]}),e.jsx("div",{className:"mt-4",children:E==="tracked"?e.jsx(yg,{projectName:t,selection:o,onSelectionChange:i,trackingQueryId:d,onTrackingQueryIdChange:c,pendingTrackingSource:x,onPendingTrackingSourceHandled:()=>g(null)}):e.jsx(Jp,{projectName:t,selection:o,mode:A,onModeChange:w,onReviewSavedSource:j,onSelectionChange:i,viewerResearchConfig:f})})]})}function Wa({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 Jp({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:o}){const{canWrite:i}=wn(),d=!i||n==="test",c=Te({...ul({client:H,path:{name:t}}),enabled:d,staleTime:6e4}),h=Te({...ml({client:H,path:{name:t}}),enabled:d,staleTime:6e4}),m=l.useMemo(()=>{const p=c.data;if(!p)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const x=new Map(p.targets.map(f=>[f.stableKey,[]]));for(const f of p.groups)for(const S of f.targetKeys)x.get(S)?.push(f.stableKey);const g=new Map(p.markets.map(f=>[f.stableKey,new Set]));for(const f of p.markets)for(const S of f.usageEdges)for(const N of x.get(S.targetKey)??[])g.get(f.stableKey)?.add(N);return[{id:"project",label:"Whole site",kind:"project",targetCount:p.targets.length},...p.groups.map(f=>({id:f.stableKey,label:f.label,kind:"group",targetCount:f.targetKeys.length,...f.parentGroupKey?{parentGroupIds:[f.parentGroupKey]}:{}})),...p.markets.map(f=>{const S=[...g.get(f.stableKey)??[]];return{id:f.stableKey,label:f.label,kind:"market",targetCount:0,...S.length?{parentGroupIds:S}:{}}}),...p.targets.map(f=>({id:f.stableKey,label:f.label,kind:"property",targetCount:1,...x.get(f.stableKey)?.length?{parentGroupIds:x.get(f.stableKey)}:{}}))]},[c.data]),u=l.useMemo(()=>(h.data?.templates??[]).map(p=>({id:p.id,version:p.updatedAt,label:p.name,pattern:p.pattern,variables:p.variables})),[h.data]),y={projectName:t,scopeOptions:m,planRevision:c.data?.active?.revision??null,selectedScope:(()=>{const p=m.find(g=>g.kind===s.measurementScope&&g.id===s.measurementScopeKey),x=c.data?.active?.revision;return p&&x&&(p.kind==="market"||p.kind==="property")?{kind:p.kind,key:p.id,label:p.label,planRevision:x,expectedPlanRevision:x}:(s.measurementScope==="market"||s.measurementScope==="property")&&s.measurementScopeKey?{kind:s.measurementScope,key:s.measurementScopeKey,label:s.measurementScopeKey,planRevision:x??0,expectedPlanRevision:x??0}:null})(),scopePending:c.isPending||c.isFetching,scopeError:c.isError,onRetryScope:()=>{c.refetch()},templates:u};return i?e.jsxs("div",{children:[e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(Wa,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(Wa,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(bg,{projectName:t,onReviewDiscoveryProbe:p=>r({source:"discovery",discoveryProbeId:p})}):e.jsx(yo,{...y,onReviewForTracking:({researchRunQueryId:p,scope:x})=>r({source:"research",researchRunQueryId:p},x??null)})})]}):e.jsx(yo,{...y,viewerResearchConfig:o})}function Xp({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:d,preview:c,isPreviewing:h,isCommitting:m,onPreview:u,onCommit:y}){const[p,x]=l.useState(null),[g,f]=l.useState(()=>Fa(s)),[S,N]=l.useState(null),E=l.useRef(null),A=l.useRef(null),v=sg(t,s),w=l.useMemo(()=>ng(t.tracked,s,t.mode),[s,t.mode,t.tracked]),j=jn({rows:w,getSearchText:C=>`${C.queryText} ${C.provenance?.source??"legacy"} ${C.assignments.map(te=>te.queryClass??"unknown").join(" ")}`});l.useEffect(()=>{if(v)return;if(!a){A.current=null;return}const C=`${a}:${wr(s)}`;if(A.current===C)return;const te=t.tracked.find(z=>z.queryId===a);te&&(A.current=C,x({kind:"edit",row:te,audience:t.mode==="advanced"?jr(s):void 0,scopeLabel:Nr(s,t)}),f(bo(te,s)),N(null))},[s,a,v,t]),l.useEffect(()=>{if(v||!o)return;const C=Fa(o.trackingSelection??s);x({kind:"add"}),f(o.source==="research"?{...C,source:"research",researchRunQueryId:o.researchRunQueryId}:{...C,source:"discovery",discoveryProbeId:o.discoveryProbeId}),N(null),i()},[i,o,s,v]),l.useEffect(()=>{v&&(x(null),N(null),a!==void 0&&r?.(void 0))},[r,a,v]),l.useEffect(()=>{if(!p||p.kind==="remove")return;const C=E.current;C&&(C.scrollIntoView?.({block:"start"}),C.focus({preventScroll:!0}))},[p]);function L(C="manual"){x({kind:"add"}),f({...Fa(s),source:C}),N(null),r?.(void 0)}function q(C){A.current=`${C.queryId}:${wr(s)}`,x({kind:"edit",row:C,audience:t.mode==="advanced"?jr(s):void 0,scopeLabel:Nr(s,t)}),f(bo(C,s)),N(null),r?.(C.queryId)}function D(C){A.current=`${C.queryId}:${wr(s)}`,x({kind:"remove",row:C,audience:t.mode==="advanced"?jr(s):void 0,scopeLabel:Nr(s,t)}),N(null),r?.(C.queryId)}function X(){x(null),N(null),r?.(void 0)}const G=p?Zp(p,g,t.mode):null,K=p!==null&&p.kind==="add"&&t.mode==="advanced"&&!ui(g),Q=G!==null&&(!K||g.contexts.length>0)&&!h;return v?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(R,{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:[e.jsx(rg,{workspace:t,selection:s,onSelectionChange:n}),t.mode==="advanced"?e.jsx(ag,{selection:s,onSelectionChange:n}):null,e.jsx(Hs,{value:j.query,onChange:j.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!oe()&&e.jsxs(Je,{type:"button",size:"sm",onClick:()=>L(),children:[e.jsx(Qm,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[j.totalRows.toLocaleString("en-US")," saved query ",j.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."}),j.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:j.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:j.rows.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:C.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(og,{row:C,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(cg,{row:C})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:ig(C)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(dg,{row:C,outsidePlan:t.mode==="advanced"&&C.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!oe()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(Je,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${C.queryText}`,onClick:()=>q(C),children:[e.jsx(zm,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(Je,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${C.queryText}`,onClick:()=>D(C),children:[e.jsx(Nl,{"aria-hidden":"true",size:13})," Remove"]})]})})]},C.queryId))})]})}),e.jsx(Ls,{page:j.page,pageSize:j.pageSize,visibleRows:j.rows.length,totalRows:j.totalRows,itemLabel:"queries",onPageChange:j.setPage})]}),p&&!oe()&&e.jsx(ug,{workspace:t,templates:d,action:p,draft:g,onDraftChange:C=>{f(C),N(null)},onClose:X,canReview:Q,isPreviewing:h,editorHeadingRef:E,onReview:()=>{G&&(N(G),u(G))}}),c&&S&&p&&e.jsx(pg,{preview:c,workspace:t,isCommitting:m,onConfirm:()=>{y({...S,expectedWorkspaceVersion:c.workspaceVersion,previewToken:c.previewToken,reviewedAt:c.reviewedAt})}})]})}function Fa(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 bo(t,s){return{...Fa(s),text:t.queryText,queryClass:"keep"}}function Zp(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=eg(s);if(!a||ei(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=tg(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!ui(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function eg(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 tg(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 ui(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function ei(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function jr(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 sg(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 Nr(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 mi(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 ng(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=>mi(r,s)))}function ag({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 wr(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function rg({workspace:t,selection:s,onSelectionChange:n}){const a=l.useMemo(()=>{const o=new Map(t.targets.map(i=>[i.stableKey,[]]));for(const i of t.groups)for(const d of i.targetKeys)o.get(d)?.push(i.stableKey);return[{id:"project",label:"Whole site",kind:"project",targetCount:t.targets.length},...t.groups.map(i=>({id:i.stableKey,label:i.label,kind:"group",targetCount:i.targetKeys.length,...i.parentGroupKey?{parentGroupIds:[i.parentGroupKey]}:{}})),...t.markets.map(i=>({id:i.stableKey,label:i.label,kind:"market",targetCount:new Set(i.usageEdges.map(d=>d.targetKey)).size,...i.groupKey?{parentGroupIds:[i.groupKey]}:{}})),...t.targets.map(i=>({id:i.stableKey,label:i.label,kind:"property",targetCount:1,...o.get(i.stableKey)?.length?{parentGroupIds:o.get(i.stableKey)}:{}}))]},[t.groups,t.markets,t.targets]),r=a.find(o=>o.kind===s.measurementScope&&(o.kind==="project"||o.id===s.measurementScopeKey))??a[0];return e.jsx(Ul,{options:a,selected:r,onSelect:o=>{n?.({measurementScope:o.kind,measurementScopeKey:o.kind==="project"?void 0:o.id})}})}function ig(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 Jl(t,s,n){const a=new Map(s.targets.map(g=>[g.stableKey,g.label])),r=new Map(s.groups.map(g=>[g.stableKey,g.label])),o=new Map(s.markets.map(g=>[g.stableKey,g.label])),i=new Set(t.assignments.map(g=>g.targetKey));if(i.size===0)return"Whole site";const d=n?t.assignments.filter(g=>mi(g,n)):t.assignments,c=new Set(d.map(g=>g.targetKey));if(n?.measurementScope==="group"){const g=c.size,f=Math.max(0,i.size-g);return[`${g} ${g===1?"property":"properties"} in this group`,...f?[`Shared with ${f} other ${f===1?"property":"properties"}`]:[]].join(" · ")}const h=new Set,m=new Set;for(const g of d)g.groupKeys.forEach(f=>h.add(f)),g.marketKeys.forEach(f=>m.add(f));const y=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"}`]:c.size===1?[a.get([...c][0])??[...c][0]]:[`${c.size} properties`],p=h.size===1?r.get([...h][0])??[...h][0]:null,x=m.size===1?o.get([...m][0])??[...m][0]:null;return p&&x&&p===x?y.push(`${p} (group and market)`):(p?y.push(`Group: ${p}`):h.size>1&&y.push(`${h.size} groups`),x?y.push(`Market: ${x}`):m.size>1&&y.push(`${m.size} markets`)),y.join(" · ")}function og({row:t,workspace:s,selection:n}){const a=lg(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:Jl(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 lg(t,s,n){const a=new Map(s.targets.map(c=>[c.stableKey,c.label])),r=new Map(s.groups.map(c=>[c.stableKey,c.label])),o=new Map(s.markets.map(c=>[c.stableKey,c.label])),d=t.assignments.filter(c=>mi(c,n)).map(c=>{const h=a.get(c.targetKey)??c.targetKey??"Whole site",m=n.measurementScope==="group"&&n.measurementScopeKey?c.groupKeys.filter(y=>y===n.measurementScopeKey).map(y=>r.get(y)??y):c.groupKeys.map(y=>r.get(y)??y),u=n.measurementScope==="market"&&n.measurementScopeKey?c.marketKeys.filter(y=>y===n.measurementScopeKey).map(y=>o.get(y)??y):c.marketKeys.map(y=>o.get(y)??y);return[h,m.length?`Groups: ${m.join(", ")}`:null,u.length?`Markets: ${u.join(", ")}`:null].filter(y=>y!==null).join(" · ")});return[...new Set(d)].length?[...new Set(d)]:["Whole site"]}function cg({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(ce,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function dg({row:t,outsidePlan:s=!1}){return s?e.jsx(ce,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(ce,{tone:"positive",children:"Measured"}):e.jsx(ce,{tone:"caution",children:"Awaiting sweep"})}function ug({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:o,canReview:i,isPreviewing:d,editorHeadingRef:c,onReview:h}){const m=s.length>0;return n.kind==="remove"?e.jsxs(pe,{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(Sr,{canReview:i,isPreviewing:d,onCancel:o,onReview:h})]}):n.kind==="edit"?e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:c,tabIndex:-1,children:"Edit query"}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:o,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:u=>r({...a,text:u.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:u=>r({...a,queryClass:u.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(Sr,{canReview:i,isPreviewing:d,onCancel:o,onReview:h})]}):e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:c,tabIndex:-1,children:"Add query"}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:o,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:u=>r({...a,text:u.target.value})})]}):null,a.source==="template"?e.jsx(mg,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(vo,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(u=>({id:u.researchRunQueryId,label:u.queryText,detail:u.researchRunId})),onChange:u=>r({...a,researchRunQueryId:u})}):null,a.source==="discovery"?e.jsx(vo,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(u=>({id:u.discoveryProbeId,label:u.queryText,detail:u.discoverySessionId})),onChange:u=>r({...a,discoveryProbeId:u})}):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":m?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:u=>r({...a,source:u.target.value}),children:[e.jsx("option",{value:"manual",children:"Write a question"}),m?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)":""]})]})]}),m?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(xg,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!ui(a)?e.jsx("div",{className:"mt-4",children:e.jsx(hg,{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:u=>r({...a,queryClass:u.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(Sr,{canReview:i,isPreviewing:d,onCancel:o,onReview:h})]})}function mg({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":ei(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(o=>o.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]}),ei(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 vo({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:o=>r(o.target.value),children:[e.jsx("option",{value:"",children:"Choose a saved query"}),a.map(o=>e.jsxs("option",{value:o.id,children:[o.label," · ",o.detail]},o.id))]})]})}function hi(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function Zn(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 Xl(t){return[...new Map(t.map(s=>[Zn(s),s])).values()]}function xi(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 hg({workspace:t,draft:s,onDraftChange:n}){const a=l.useMemo(()=>Xl([...t.defaultContexts.map(hi),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?Zn(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:o=>{const i=a.find(c=>Zn(c)===o.target.value),d=o.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:d})},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(o=>e.jsx("option",{value:Zn(o),children:xi(o)},Zn(o)))]}),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 xg({workspace:t,draft:s,onDraftChange:n}){const[a,r]=l.useState(""),[o,i]=l.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),d=l.useMemo(()=>[...t.targets.map(p=>({kind:"target",key:p.stableKey,label:p.label,detail:"Property"})),...t.groups.map(p=>({kind:"group",key:p.stableKey,label:p.label,detail:"Group"})),...t.markets.map(p=>({kind:"market",key:p.stableKey,label:p.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),c=a.trim().toLocaleLowerCase(),h=c?d.filter(p=>`${p.label} ${p.detail}`.toLocaleLowerCase().includes(c)):d,m=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function u(p,x,g){const f=p==="target"?"targetKeys":p==="group"?"groupKeys":"marketKeys",S=s[f];n({...s,wholeSite:!1,[f]:g?[...S,x]:S.filter(N=>N!==x)})}function y(p,x){return(p==="target"?s.targetKeys:p==="group"?s.groupKeys:s.marketKeys).includes(x)}if(!o){const p=t.targets.find(x=>x.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: ",p?.label??s.targetKeys[0]]}),e.jsx(R,{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:p=>{n({...s,wholeSite:p.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),"Whole site"]}),!s.wholeSite&&!m?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(Hs,{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:h.length===0?e.jsx("p",{className:"px-1 py-2 text-sm text-muted",children:"No assignment matches that search."}):h.map(p=>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":`${p.label}, ${p.detail}`,checked:y(p.kind,p.key),onChange:x=>u(p.kind,p.key,x.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:p.label}),e.jsx("span",{className:"text-xs text-muted",children:p.detail})]},`${p.kind}:${p.key}`))})]})}function Sr({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(Je,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(R,{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 pg({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=l.useRef(null);l.useEffect(()=>{const d=r.current;d&&(typeof d.scrollIntoView=="function"&&d.scrollIntoView({block:"start"}),d.focus({preventScroll:!0}))},[t]);const o=!t.diff.noOp,i=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(d=>d.rows.length>0);return e.jsxs(pe,{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:o?"Confirm tracked query changes":"No tracking changes"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:o?"Changes apply to future sweeps. Earlier results stay unchanged.":"This request leaves tracking unchanged."})]}),e.jsx(ce,{tone:o?"caution":"neutral",children:o?"Ready to confirm":"No-op"})]}),i.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:i.map(d=>e.jsx(jo,{label:d.label,rows:d.rows,workspace:s,tracked:t.tracked},d.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(jo,{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(Je,{type:"button",size:"sm",disabled:!o||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function jo({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`:fg(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(gg,{row:a.find(o=>o.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function gg({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 o=s.targets.find(c=>c.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",d=a.contexts.map(c=>xi(hi(c))).join("; ");return e.jsx("li",{children:[o,i,d].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function fg(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=Xl(a.assignments.flatMap(i=>i.contexts).map(hi)),o=r.length===1?xi(r[0]):r.length>1?`${r.length} contexts`:null;return[Jl(a,n),o].filter(i=>i!==null).join(" · ")}function yg({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i}){const d=xs(),[c,h]=l.useState(null),m=Te({...ul({client:H,path:{name:t}})}),u=Te({...ml({client:H,path:{name:t}}),staleTime:6e4}),y=Pt({...Cd(),onSuccess:x=>h(x),onError:async x=>{h(null),await d.invalidateQueries({queryKey:Sd({client:H,path:{name:t}})}),$e({title:"Could not review tracking changes",detail:x instanceof Error?x.message:"Update the draft and review it again.",tone:"negative"})}}),p=Pt({...kd(),onSuccess:async x=>{h(null),r?.(void 0),await Ri(d,t),$e({title:x.committed?"Tracked queries updated":"No tracked-query change",detail:x.active?`Measurement revision ${x.active.revision}.`:"No measurement revision is published yet.",tone:x.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async x=>{h(null),await Ri(d,t),$e({title:"Could not confirm tracking changes",detail:x instanceof Error?x.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return m.isLoading?e.jsx(pe,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):m.isError||!m.data?e.jsxs(pe,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{m.refetch()},children:"Try again"})]}):e.jsx(Xp,{workspace:m.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:u.data?.templates??[],preview:c,isPreviewing:y.isPending,isCommitting:p.isPending,onPreview:x=>{h(null),y.mutate({client:H,path:{name:t},body:{...x,expectedWorkspaceVersion:m.data.workspaceVersion}})},onCommit:x=>p.mutate({client:H,path:{name:t},body:x})})}function bg({projectName:t,onReviewDiscoveryProbe:s}){const n=xs(),[a,r]=l.useState(null),[o,i]=l.useState(""),[d,c]=l.useState("100"),h=Te({...Ad({client:H,path:{name:t},query:{limit:"10"}}),refetchInterval:N=>N.state.data?.some(A=>Zr.has(A.status))?3e3:!1}),m=h.data??[];l.useEffect(()=>{!a&&m[0]&&r(m[0].id)},[a,m]);const u=m.find(N=>N.id===a)??null,y=Te({...Pd({client:H,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:u&&Zr.has(u.status)?3e3:!1}),p=y.data??null,x=Pt({mutationFn:()=>{const N={},E=o.trim();E&&(N.icpDescription=E);const A=Number.parseInt(d,10);return Number.isFinite(A)&&A>0&&(N.maxProbes=A),Rd(t,N)},onSuccess:async N=>{r(N.sessionId),i(""),await wg(n,t,N.sessionId),$e({title:"Discovery started",detail:`Run ${Cr(N.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${N.sessionId}`,dedupeMode:"replace"})},onError:N=>{$e({title:"Discovery failed to start",detail:N instanceof Error?N.message:"Could not start discovery.",tone:"negative"})}}),g=p??u,f=l.useMemo(()=>(p?.probes??[]).slice(0,30),[p?.probes]);async function S(){try{const N=await h.refetch();if(N.error)throw N.error;const E=N.data?.length??0;$e({title:"Discovery sessions refreshed",detail:`${E} recent session${E===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(N){$e({title:"Discovery refresh failed",detail:N instanceof Error?N.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:oe()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:h.isFetching,onClick:()=>{S()},children:[e.jsx(ra,{className:`size-3.5 ${h.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(ce,{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:o,onChange:N=>i(N.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:d,onChange:N=>c(N.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!oe()&&e.jsxs(Je,{type:"button",size:"sm",disabled:x.isPending,onClick:()=>x.mutate(),children:[e.jsx(Ba,{size:14}),x.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),h.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),m.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:m.map(N=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===N.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(N.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:Cr(N.id)}),e.jsx(ce,{tone:No(N.status),children:N.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",N.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",N.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",N.wastedCount??0]})]})]},N.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:g?Cr(g.id):"No run selected"})]}),g&&e.jsx(ce,{tone:No(g.status),children:g.status})]}),g?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Aa,{label:"Questions tested",value:g.probeCount??0}),e.jsx(Aa,{label:"Cited queries",value:g.citedCount??0,tone:"positive"}),e.jsx(Aa,{label:"Worth tracking",value:g.aspirationalCount??0,tone:"caution"}),e.jsx(Aa,{label:"Skip",value:g.wastedCount??0,tone:"negative"})]}),g.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:g.error}),g.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:g.warning}),g.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:g.icpDescription})]}),g.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:g.competitorMap.slice(0,8).map(N=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[N.domain," ",e.jsx("span",{className:"text-muted",children:N.hits})]},N.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),g?.status==="completed"&&e.jsxs(pe,{className:"surface-card",children:[e.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(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),y.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),f.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:f.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:N.query}),e.jsx("td",{children:e.jsx(ce,{tone:vg(N.bucket),children:Ng(N.bucket)})}),e.jsx("td",{className:"text-secondary",children:N.citedDomains.length>0?N.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!oe()&&s&&(N.bucket==="cited"||N.bucket==="aspirational")&&e.jsx(Je,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(N.id),children:"Review for tracking"})})]},N.id))})]})})]})]})]})]})}function Aa({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 No(t){return t==="completed"?"positive":t==="failed"?"negative":Zr.has(t)?"caution":"neutral"}function vg(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const jg={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Ng(t){return t?jg[t]:"Not classified"}function Cr(t){return t.length>8?t.slice(0,8):t}async function wg(t,s,n){await Promise.all([Ct(t,"discovery"),t.invalidateQueries({queryKey:Id({client:H})})])}function wo(t){return`${(t*100).toFixed(1)}%`}function Sg({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),d=Te({...Td({client:H,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=Te({...$d({client:H,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(c.data??[]).filter(f=>(f.status==="completed"||f.status==="partial")&&f.trigger!=="probe").reverse(),m=o??h[0]?.id??"",u=a??h.find(f=>f.id!==m)?.id??"",y=!!(u&&m&&u!==m),p=Te({...Md({client:H,path:{name:t},query:{run1:u,run2:m}}),enabled:s==="compare"&&y}),x=d.data??[],g=p.data?.diff.filter(f=>f.changed||f.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(([f,S])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===f,className:`filter-chip ${s===f?"filter-chip-active":""}`,onClick:()=>n(f),children:S},f))}),s==="changes"?e.jsx(ih,{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."})]}),d.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!d.isLoading&&x.length===0?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:Kt()?Zs:"Complete an answer visibility sweep to create the first snapshot."})]}):null,x.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:x.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(f.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.mentionedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:wo(f.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.citedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:wo(f.overallCitedRate)})]},f.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:u,onChange:f=>r(f.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:m,onChange:f=>i(f.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]})]}),c.isLoading||p.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!c.isLoading&&h.length<2?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:Kt()?Zs:"Run another answer visibility sweep before comparing historical evidence."})]}):null,p.data&&g.length===0?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,g.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:g.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:f.query??"Archived query"}),e.jsx("td",{children:e.jsxs(ce,{tone:f.changed?"caution":"neutral",children:[f.run1State??"none"," → ",f.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(ce,{tone:f.visibilityChanged?"caution":"neutral",children:[f.run1MentionState??"none"," → ",f.run2MentionState??"none"]})})]},f.queryId??f.query??"unknown"))})]})}):null]}):null]})}const So={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},Cg={contract:null,assessment:null,googleAds:So,gtm:So,snapshots:[]};function kg(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Ig(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Ag(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 Pg(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 Rg(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 Zl(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"&&Tg(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 Ig(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Tg(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function ec(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 $g(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 Mg(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 un(t){return t.length<=12?t:`…${t.slice(-10)}`}function Lg(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 qg(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 kr={"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 Co(t){return t.outcome==="pass"?{label:kr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:kr[t.code],tone:"negative",outcome:"Fail"}:{label:kr[t.code],tone:"caution",outcome:"Unknown"}}function Eg(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Dg(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 Og(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function ko({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=ec(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(ce,{tone:o.tone,children:o.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),i?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:i}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Ht(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(Je,{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 Fg="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.",Kg="Available once Google Ads and Tag Manager are connected.",Gg="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 _g({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:o}){const i=t.googleAds.state==="connected",d=t.gtm.state==="connected",c=t.googleAds.state==="unavailable",h=t.gtm.state==="unavailable",m=c||h||t.gtm.state==="unavailable",u={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},y=!i&&!d,p=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:c?u:Pg(t)},{title:"Tag Manager",state:t.gtm.state,ready:d,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?u:Rg(t)}],x=i&&d&&!m?Zl(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(Ve,{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."})]}),y?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:Gg}):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(Ve,{text:Fg})]}),x&&s?e.jsx(Je,{type:"button",disabled:r,onClick:()=>s(x.id),children:r?"Working…":x.label}):e.jsx("p",{className:"text-sm text-secondary",children:Kg})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:p.map(g=>{const f=g.ready?{label:"Ready",tone:"positive"}:ec(g.state),S=g.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:g.title}),e.jsx(ce,{tone:f.tone,children:f.label}),g.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:g.summary}):null,S&&s?S.id==="retry-connection-status"?e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(S.id),children:r?"Working…":S.label}):e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(S.id),children:r?"Working…":S.label}):null,g.summary&&g.onChange?e.jsx(Je,{type:"button",variant:"ghost",size:"sm","aria-label":g.changeLabel,disabled:r,onClick:g.onChange,children:"Change"}):null]},g.title)})}),o?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:o}):null]})]})}function Ug({workspace:t=Cg,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:o=null,onSelectContract:i,contractError:d=null,onRetryContracts:c,onRetryEvidence:h,onChangeGoogleAdsSelection:m,onChangeGtmSelection:u,onAddContract:y}){const p=kg(t),x=Ag(p),g=Zl(t),f=t.assessment?.findings??[],S=f.filter(v=>v.outcome!=="pass"),N=f.filter(v=>v.outcome==="pass"),E=S.some(v=>v.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&d===null?e.jsx(_g,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:m,onChangeGtmSelection:u,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(ce,{tone:x.tone,children:x.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Ht(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:x.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(v=>e.jsxs("li",{className:"break-words",children:[Og(v)," ",v.kind,", captured ",Ht(v.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",v.id,")"]})]},v.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?g.id==="review-findings"||g.id==="review-runtime-verification"||g.id==="retry-connection-status"||g.id==="select-contract"||g.id==="retry-integrity"||g.id==="waiting-for-integrity"?e.jsx(R,{type:"button",disabled:n||g.id==="waiting-for-integrity",onClick:()=>s(g.id),children:n?"Working…":g.label}):e.jsx(Je,{type:"button",disabled:n,onClick:()=>s(g.id),children:n?"Working…":g.label}):g.id==="review-findings"?e.jsx(R,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):p==="runtime-unverified"?e.jsx(R,{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:g.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&&y?e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:y,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:o??"",onChange:v=>i?.(v.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(v=>e.jsx("option",{value:v.id,children:v.name},v.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:Lg(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:qg(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:un(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:un(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:un(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:un(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."}),d?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:d}),c?e.jsx(R,{type:"button",variant:"outline",onClick:c,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),S.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(ce,{tone:E,children:[S.length," ",S.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:S.map(v=>{const w=Co(v);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:w.label}),e.jsx(ce,{tone:w.tone,children:w.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",v.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",v.code]}),v.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",v.evidenceIds.join(", ")]}):null]},`${v.code}:${v.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(Ve,{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(v=>{const w=$g(v.key,p);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 ${w==="positive"?"bg-positive-fill":w==="caution"?"bg-caution-fill":w==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:v.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:v.detail}),e.jsx(ce,{tone:w,children:Mg(v.key,p)})]},v.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:[ko({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:m}:{},actionPending:n}),ko({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:u}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&h?e.jsx(R,{type:"button",variant:"outline",className:"mt-3",onClick:h,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:v.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:v.kind}),e.jsx("td",{className:"text-secondary",children:Ht(v.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:un(v.id)})]},v.id))})]})})]}):null,N.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[N.length," ",N.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:N.map(v=>{const w=Co(v);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:w.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",v.code]}),v.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",v.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(ce,{tone:w.tone,children:w.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:v.subject})]},`${v.code}:${v.subject}`)})})]})})]}):null,p==="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 ",Eg(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:un(t.contract.gtm.tagId)})," fires with ",Dg(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:un(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const mn=3e4,Ao={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},$t="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",ds="text-sm font-medium text-secondary";function Po(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:jt(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function Pa(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function Bg(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 Vg(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Qg(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:Vg(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 zg(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:Pa(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:Pa(t.triggerIds),variableIds:Pa(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:Pa(t.productionHosts)}}}function Ro(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 Ra(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 Ia(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Ta({id:t,label:s,value:n,onChange:a,children:r,disabled:o=!1}){return e.jsxs("label",{htmlFor:t,className:ds,children:[s,e.jsx("select",{id:t,className:$t,value:n,onChange:i=>a(i.target.value),disabled:o,children:r})]})}function Pn({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 Io({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[d,c]=l.useState(null),h=l.useRef(null),m=l.useRef(null),u=l.useRef(!1);l.useEffect(()=>{const g=u.current;u.current=a,a?m.current?.focus():g&&h.current?.querySelector("button")?.focus()},[a]);function y(){c(null),r(!0)}function p(){c(null),r(!1)}async function x(){i(!0),c(null);try{await n()}catch(g){c(jt(g)),i(!1)}}return e.jsx("div",{ref:h,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(R,{ref:m,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:o,onClick:p,children:"Keep connected"}),e.jsx(Je,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||o,onClick:()=>{x()},children:o?"Disconnecting…":`Disconnect ${t}`})]}),d?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:d}):null]}):e.jsxs(Je,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:y,children:["Disconnect ",t]})})}function To({id:t,label:s,options:n,synced:a,loading:r,failed:o,onRetry:i,emptyHint:d,value:c,onChange:h}){const m=n.some(g=>g.id===c),[u,y]=l.useState(!1),p=u||c!==""&&!m&&n.length>0,x=e.jsx("label",{htmlFor:t,className:ds,children:s});return r?e.jsxs("div",{children:[x,e.jsx("select",{id:t,className:$t,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):o?e.jsxs("div",{children:[x,e.jsx("input",{id:t,required:!0,className:$t,value:c,onChange:g=>h(g.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:[x,e.jsx("input",{id:t,required:!0,className:$t,value:c,onChange:g=>h(g.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":d})]}):e.jsxs("div",{children:[x,p?e.jsx("input",{id:t,required:!0,className:$t,value:c,onChange:g=>h(g.target.value)}):e.jsxs("select",{id:t,required:!0,className:$t,value:c,onChange:g=>h(g.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(g=>e.jsxs("option",{value:g.id,children:[g.name,g.detail?` (${g.detail})`:"",g.active?"":" — inactive"]},g.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{y(!p),h("")},children:p?"Choose from synced list":"Enter an ID manually"})]})}function Wg({projectId:t,projectName:s}){const n=wn(),[a,r]=l.useState(null),[o,i]=l.useState(null),[d,c]=l.useState(!1),[h,m]=l.useState(""),[u,y]=l.useState(null),[p,x]=l.useState(!1),[g,f]=l.useState(!1),[S,N]=l.useState(""),[E,A]=l.useState(""),[v,w]=l.useState(""),[j,L]=l.useState(""),[q,D]=l.useState(""),[X,G]=l.useState(!1),[K,Q]=l.useState(Ao),[C,te]=l.useState(null),z=l.useRef(null),Y=Te({...Ld({client:H,path:{name:s}}),staleTime:mn}),V=Te({...qd({client:H,path:{name:s}}),staleTime:mn}),U=Te({...Ed({client:H,path:{name:s}}),staleTime:mn}),F=Te({...Dd({client:H,path:{name:s}}),staleTime:mn}),T=F.data,ae=Te({...Od({client:H,path:{name:s},query:{limit:5}}),staleTime:mn}),I=Te({...Fd({client:H,path:{name:s},query:{limit:5}}),staleTime:mn}),Z=U.data??[],de=(C?Z.find(M=>M.id===C)??null:null)??(Z.length===1?Z[0]??null:null),J=Z.length>1&&!de,ie=Te({...Kd({client:H,path:{name:s,contractId:de?.id??""}}),enabled:!!de,staleTime:mn}),ye=Te({...Gd({client:H,path:{name:s}}),enabled:u==="google-ads"&&Y.data?.connected===!0,staleTime:0}),ee=Te({..._d({client:H,path:{name:s}}),enabled:u==="gtm"&&V.data?.connected===!0,staleTime:0}),me=Te({...Ud({client:H,path:{name:s,accountId:v}}),enabled:u==="gtm"&&!!v,staleTime:0}),B=Te({...Bd({client:H,path:{name:s,accountId:v,containerId:j}}),enabled:u==="gtm"&&!!v&&!!j,staleTime:0}),xe=Pt(Vd({client:H})),Se=Pt(Qd({client:H})),Ce=Pt(zd({client:H})),tt=Pt(Wd({client:H})),Qe=Pt(Hd({client:H})),Ge=Pt(Yd({client:H})),st=Pt(Jd({client:H})),qe=Pt(Xd({client:H})),O=Pt(Zd({client:H}));l.useEffect(()=>{if(u!=="google-ads"||p||!Y.isSuccess)return;const M=Y.data.connection?.selection;N(M?.customerId??""),A(M?.loginCustomerId??""),x(!0)},[p,Y.data,Y.isSuccess,u]),l.useEffect(()=>{if(u!=="gtm"||g||!V.isSuccess)return;const M=V.data.selection;w(M?.accountId??""),L(M?.containerId??""),D(M?.workspaceId??""),f(!0)},[g,V.data,V.isSuccess,u]),l.useEffect(()=>{!C||!U.data||U.data.some(M=>M.id===C)||te(null)},[U.data,C]);const Le=l.useMemo(()=>{const M=ae.data?.snapshots??[],be=I.data?.snapshots??[],rt=[...M.map(pt=>({id:pt.id,provider:"google-ads",kind:pt.kind,capturedAt:pt.capturedAt})),...be.map(pt=>({id:pt.id,provider:"gtm",kind:pt.kind,capturedAt:pt.capturedAt}))].sort((pt,Ds)=>Ds.capturedAt.localeCompare(pt.capturedAt)).slice(0,5),wt=[],is=ie.data?.googleAdsSnapshot,Be=ie.data?.gtmSnapshot;return is&&wt.push({id:is.id,provider:"google-ads",kind:is.kind,capturedAt:is.capturedAt}),Be&&wt.push({id:Be.id,provider:"gtm",kind:Be.kind,capturedAt:Be.capturedAt}),{contract:ie.data?.assessment.contract??de,assessment:ie.data?.assessment??null,contractSelectionRequired:J,assessmentState:de?ie.isError?"unavailable":ie.isLoading?"loading":void 0:void 0,assessmentError:ie.isError?jt(ie.error):null,googleAds:Bg(Y.data,Po(ae.data?.total??0,ae.isLoading,ae.isError,ae.error),Y.isError),gtm:Qg(V.data,Po(I.data?.total??0,I.isLoading,I.isError,I.error),V.isError),snapshots:rt,assessmentEvidenceSnapshots:wt}},[de,J,ae.data,ae.error,ae.isError,ae.isLoading,Y.data,Y.isError,I.data,I.error,I.isError,I.isLoading,V.data,V.isError,ie.data,ie.error,ie.isError,ie.isLoading]),P=l.useSyncExternalStore(cl,Ka,Ka),ge=Object.values(P.runs).some(M=>M.projectId===t&&(M.kind===Xs["google-ads-sync"]||M.kind===Xs["gtm-sync"])),Oe=xe.isPending||Se.isPending||Ce.isPending||tt.isPending||Qe.isPending||Ge.isPending||st.isPending||qe.isPending||O.isPending||ge;async function We(){await Promise.all([Y.refetch(),V.refetch(),U.refetch(),ae.refetch(),I.refetch(),F.refetch(),de?ie.refetch():Promise.resolve()])}async function _e(M){await We();for(let be=0;be<10&&!M();be+=1)await new Promise(rt=>setTimeout(rt,1500)),await We()}function he(){const M=document.activeElement;z.current=M instanceof HTMLElement?M:null}function xt(M){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(M);return}globalThis.setTimeout(M,0)}function Ue(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Fe(M){if(!M)return;!M.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!M.hasAttribute("tabindex")&&(M.tabIndex=-1),M.focus({preventScroll:!0})}function kt(M,be=M){const rt=document.getElementById(M);rt instanceof HTMLDetailsElement&&(rt.open=!0);const wt=rt?.scrollIntoView;typeof wt=="function"&&wt.call(rt,{behavior:Ue()?"auto":"smooth",block:"start"}),Fe(document.getElementById(be)??rt)}function Xe(M,be){he(),xt(()=>kt(M,be))}function ke(){const M=z.current;z.current=null,M&&xt(()=>{M.isConnected&&M.focus({preventScroll:!0})})}function ot(){r(null),c(!1),ke()}function ft(){r(null),y(null),ke()}function qt(){r(null),G(!1),ke()}function De(){r(null),y(null),c(!0),Xe("google-ads-connect-panel","google-ads-connect-title")}function k(){r(null),N(""),A(""),x(!1),y("google-ads"),c(!1),Xe("google-ads-selection-panel","google-ads-selection-title")}function Ie(){r(null),w(""),L(""),D(""),f(!1),y("gtm"),c(!1),Xe("gtm-selection-panel","gtm-selection-title")}function we(){r(null),G(!0),Xe("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function ze(M,be){ll({id:M.id,projectId:M.projectId,kind:M.kind,projectLabel:s,sourceAction:be}),$e({title:be==="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:${M.id}`,dedupeMode:"replace"})}async function yt(){Ns(n),r(null);try{const M=await xe.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});m(""),c(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Ro(M.authorizationUrl,()=>{We(),i(null),ke()})}catch(M){r(jt(M))}}async function nt(){Ns(n),r(null);try{const M=await Se.mutateAsync({path:{name:s},body:{provider:"gtm"}});i("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),Ro(M.authorizationUrl,()=>{We(),i(null),ke()})}catch(M){r(jt(M))}}async function Rt(){if(Ns(n),!S){r("Select a Google Ads customer before saving.");return}r(null);try{await Ce.mutateAsync({path:{name:s},body:{customerId:S,...E.trim()?{loginCustomerId:E.trim()}:{}}}),y(null),ke(),await _e(()=>Y.data?.selectedCustomer!=null)}catch(M){r(jt(M))}}async function Ye(){if(Ns(n),!v||!j){r("Select a Tag Manager account and container before saving.");return}r(null);try{await tt.mutateAsync({path:{name:s},body:{accountId:v,containerId:j,...q?{workspaceId:q}:{}}}),y(null),ke(),await _e(()=>V.data?.status==="connected")}catch(M){r(jt(M))}}async function ne(){Ns(n),r(null),await st.mutateAsync({path:{name:s}}),y(null),c(!1),N(""),A(""),x(!1),i(null),await We(),$e({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),z.current=null,xt(()=>Fe(document.getElementById("conversion-integrity-title")))}async function Ee(){Ns(n),r(null),await qe.mutateAsync({path:{name:s}}),y(null),w(""),L(""),D(""),f(!1),i(null),await We(),$e({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),z.current=null,xt(()=>Fe(document.getElementById("conversion-integrity-title")))}async function Pe(){Ns(n),r(null);try{const M=await Qe.mutateAsync({path:{name:s}});ze(M,"google-ads-sync")}catch(M){r(jt(M))}}async function Ae(){Ns(n),r(null);try{const M=await Ge.mutateAsync({path:{name:s}});ze(M,"gtm-sync")}catch(M){r(jt(M))}}async function Yt(){Ns(n),r(null);try{const M=await Promise.allSettled([Qe.mutateAsync({path:{name:s}}),Ge.mutateAsync({path:{name:s}})]),[be,rt]=M;be.status==="fulfilled"&&ze(be.value,"google-ads-sync"),rt.status==="fulfilled"&&ze(rt.value,"gtm-sync");const wt=M.find(is=>is.status==="rejected");if(wt?.status==="rejected")throw wt.reason}catch(M){r(jt(M))}}async function Jt(){Ns(n);const M=Y.data?.connection?.selection.customerId,be=V.data?.selection;if(!M||!be?.accountId||!be.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const rt=await O.mutateAsync({path:{name:s},body:zg(K,M,{accountId:be.accountId,containerId:be.containerId})});Q(Ao),G(!1),ke(),(await U.refetch()).data?.some(is=>is.id===rt.id)&&te(rt.id)}catch(rt){r(jt(rt))}}function _t(M){switch(M){case"connect-google-ads":De();return;case"connect-gtm":he(),nt();return;case"select-google-ads":k();return;case"select-gtm":Ie();return;case"sync-google-ads":Pe();return;case"sync-gtm":Ae();return;case"sync-static-evidence":Yt();return;case"declare-contract":we();return;case"review-findings":Xe("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":Xe("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":We();return;case"select-contract":Xe("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ie.refetch();return;case"waiting-for-integrity":return}}const bt=ye.data?.customers??[],lt=ee.data?.accounts??[],Ut=me.data?.containers??[],as=B.data?.workspaces??[],Bt=!!S&&!bt.some(M=>M.customerId===S),Vt=!!v&&!lt.some(M=>M.id===v),mt=!!j&&!Ut.some(M=>M.id===j),rs=!!q&&!as.some(M=>M.id===q),Ze=Bt&&ye.isSuccess&&ye.data.truncated===!1,Et=Vt&&ee.isSuccess&&ee.data.truncated===!1,Qt=mt&&me.isSuccess&&me.data.truncated===!1,fs=rs&&B.isSuccess&&B.data.truncated===!1,ps=Et||Qt||fs,zt=Et?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Qt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":fs?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,ys=Ia(Ze,ye.data,ye.isError),Xt=Ia(Et,ee.data,ee.isError),Nt=Ia(Qt,me.data,me.isError),Zt=Ia(fs,B.data,B.isError),vt=ye.isError?jt(ye.error):null,es=ee.isError?jt(ee.error):me.isError?jt(me.error):B.isError?jt(B.error):null,bs=u==="google-ads"?vt:u==="gtm"?es:null,_=Ra("customer",ye.data,bt.length),re=Ra("account",ee.data,lt.length),je=Ra("container",me.data,Ut.length),le=Ra("draft workspace",B.data,as.length),Ne=ee.isError||me.isError||B.isError&&!!q,Ke=d||u!==null||X;function ht(){ye.refetch()}function ct(){if(ee.isError){ee.refetch();return}if(me.isError){me.refetch();return}B.isError&&B.refetch()}return Y.isLoading||V.isLoading||U.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(M=>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"})]},M))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):U.isError&&!U.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: ",jt(U.error)]}),e.jsx(R,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{U.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ug,{workspace:Le,onPrimaryAction:_t,actionPending:Oe,actionError:Ke?null:a,contracts:Z,selectedContractId:de?.id??null,onSelectContract:M=>te(M||null),contractError:U.isError?jt(U.error):null,onRetryContracts:()=>{U.refetch()},onRetryEvidence:()=>{Promise.all([ae.refetch(),I.refetch()])},onChangeGoogleAdsSelection:k,onChangeGtmSelection:Ie,onAddContract:()=>_t("declare-contract")}),o?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:o}):null,d?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:He(async M=>{M.preventDefault(),await yt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:ds,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:M=>m(M.target.value),className:$t,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(Je,{type:"submit",disabled:xe.isPending,children:xe.isPending?"Starting…":"Continue to Google"}),e.jsx(R,{type:"button",variant:"outline",onClick:ot,children:"Cancel"})]})]})]}):null,u==="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(R,{type:"button",variant:"outline",size:"sm",onClick:ht,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Ze?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(Ta,{id:"google-ads-customer",label:"Customer account",value:S,onChange:M=>{x(!0),N(M);const be=bt.find(rt=>rt.customerId===M);A(be?.parentCustomerId??"")},disabled:ye.isLoading,children:[e.jsx("option",{value:"",children:ye.isLoading?"Loading accessible customers…":"Select a customer"}),Bt?e.jsxs("option",{value:S,disabled:Ze,children:["Saved customer ",S," (",ys,")"]}):null,bt.map(M=>e.jsx("option",{value:M.customerId,children:M.descriptiveName??`Customer ${M.customerId}`},M.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:ds,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:$t,value:E,onChange:M=>{x(!0),A(M.target.value)},placeholder:"Use only when a manager context is required"})]})]}),_?e.jsx("p",{role:"status",className:`mt-3 text-sm ${ye.data?.truncated?"text-caution":"text-secondary"}`,children:_}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Je,{type:"button",disabled:Ce.isPending||ye.isLoading||ye.isError||Ze||!S,onClick:He(Rt),children:Ce.isPending?"Saving…":"Save customer selection"}),e.jsx(R,{type:"button",variant:"outline",onClick:ft,children:"Cancel"})]}),Y.data?.connected?e.jsx(Io,{providerLabel:"Google Ads",disabled:Oe,onDisconnect:ne}):null]}):null,u==="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(R,{type:"button",variant:"outline",size:"sm",onClick:ct,children:ee.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,zt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:zt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Ta,{id:"gtm-account",label:"Account",value:v,onChange:M=>{f(!0),M!==v&&(L(""),D("")),w(M)},disabled:ee.isLoading,children:[e.jsx("option",{value:"",children:ee.isLoading?"Loading accounts…":"Select an account"}),Vt?e.jsxs("option",{value:v,disabled:Et,children:["Saved account ",v," (",Xt,")"]}):null,lt.map(M=>e.jsx("option",{value:M.id,children:M.name},M.id))]}),e.jsxs(Ta,{id:"gtm-container",label:"Container",value:j,onChange:M=>{f(!0),M!==j&&D(""),L(M)},disabled:!v||me.isLoading,children:[e.jsx("option",{value:"",children:me.isLoading?"Loading containers…":"Select a container"}),mt?e.jsxs("option",{value:j,disabled:Qt,children:["Saved container ",j," (",Nt,")"]}):null,Ut.map(M=>e.jsx("option",{value:M.id,children:M.name},M.id))]}),e.jsxs(Ta,{id:"gtm-workspace",label:"Draft workspace (optional)",value:q,onChange:M=>{f(!0),D(M)},disabled:!j||B.isLoading,children:[e.jsx("option",{value:"",children:B.isLoading?"Loading workspaces…":"No draft workspace"}),rs?e.jsxs("option",{value:q,disabled:fs,children:["Saved draft workspace ",q," (",Zt,")"]}):null,as.map(M=>e.jsx("option",{value:M.id,children:M.name},M.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[re?e.jsx("p",{role:"status",className:ee.data?.truncated?"text-caution":"text-secondary",children:re}):null,je?e.jsx("p",{role:"status",className:me.data?.truncated?"text-caution":"text-secondary",children:je}):null,le?e.jsx("p",{role:"status",className:B.data?.truncated?"text-caution":"text-secondary",children:le}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Je,{type:"button",disabled:tt.isPending||ee.isLoading||me.isLoading||B.isLoading&&!!q||Ne||ps||!v||!j,onClick:He(Ye),children:tt.isPending?"Saving…":"Save container selection"}),e.jsx(R,{type:"button",variant:"outline",onClick:ft,children:"Cancel"})]}),V.data?.connected?e.jsx(Io,{providerLabel:"Tag Manager",disabled:Oe,onDisconnect:Ee}):null]}):null,X?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:He(async M=>{M.preventDefault(),await Jt()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:ds,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:$t,value:K.name,onChange:M=>Q(be=>({...be,name:M.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:ds,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:$t,value:K.eventName,onChange:M=>Q(be=>({...be,eventName:M.target.value})),placeholder:"booking_complete"})]}),e.jsx(To,{id:"contract-conversion-action",label:"Google Ads conversion action",options:T?.googleAds.conversionActions??[],synced:T?.googleAds.syncedAt!=null,loading:F.isLoading,failed:F.isError,onRetry:()=>{F.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:K.conversionActionId,onChange:M=>Q(be=>({...be,conversionActionId:M}))}),e.jsx(To,{id:"contract-gtm-tag",label:"Tag Manager tag",options:T?.gtm.tags??[],synced:T?.gtm.syncedAt!=null,loading:F.isLoading,failed:F.isError,onRetry:()=>{F.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:K.tagId,onChange:M=>Q(be=>({...be,tagId:M}))})]}),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:ds,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:$t,value:K.conversionId,onChange:M=>Q(be=>({...be,conversionId:M.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:ds,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:$t,value:K.conversionLabel,onChange:M=>Q(be=>({...be,conversionLabel:M.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:ds,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:$t,value:K.triggerIds,onChange:M=>Q(be=>({...be,triggerIds:M.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:ds,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:$t,value:K.variableIds,onChange:M=>Q(be=>({...be,variableIds:M.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:ds,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:$t,value:K.campaignIds,onChange:M=>Q(be=>({...be,campaignIds:M.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:ds,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:$t,value:K.productionHosts,onChange:M=>Q(be=>({...be,productionHosts:M.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(Pn,{id:"contract-primary-action",checked:K.requirePrimaryAction,onChange:M=>Q(be=>({...be,requirePrimaryAction:M})),children:"Google Ads action is primary"}),e.jsx(Pn,{id:"contract-biddable-goal",checked:K.requireBiddableGoal,onChange:M=>Q(be=>({...be,requireBiddableGoal:M})),children:"Google Ads goal is biddable"}),e.jsx(Pn,{id:"contract-runtime-verification",checked:K.verificationRequired,onChange:M=>Q(be=>({...be,verificationRequired:M})),children:"Runtime proof is required"}),e.jsx(Pn,{id:"contract-transaction-id",checked:K.requireTransactionId,onChange:M=>Q(be=>({...be,requireTransactionId:M})),children:"Transaction ID is required"}),e.jsx(Pn,{id:"contract-value",checked:K.requireValue,onChange:M=>Q(be=>({...be,requireValue:M})),children:"Conversion value is required"}),e.jsx(Pn,{id:"contract-currency",checked:K.requireCurrency,onChange:M=>Q(be=>({...be,requireCurrency:M})),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(Je,{type:"submit",disabled:O.isPending,children:O.isPending?"Saving…":"Save conversion contract"}),e.jsx(R,{type:"button",variant:"outline",onClick:qt,children:"Cancel"})]})]})]}):null]})}const Hg=6e4,Yg=["7d","14d","30d"],pi="not available",Jg='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%.',Xg="No Google Ads snapshot stored yet",Zg="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.",ef="No closed days yet",tf="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.",sf={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},Us=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),Ar=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),tc=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),nf=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Rn(t,s){return t===null||!Number.isFinite(t)?pi:s===null?nf.format(t/1e6):bh(t,s)}function Pr(t){if(t===null||!Number.isFinite(t))return pi;const s=t*100;return s>0&&s<.1?"<0.1%":`${tc.format(s)}%`}function af(t,s){if(t===null||!Number.isFinite(t))return`${pi} vs prior ${s}d`;if(t===0)return`no change vs prior ${s}d`;const n=Math.abs(t*100),a=n<.1?"<0.1%":`${tc.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function rf(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function of(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function lf(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 cf({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=Te({...eu({client:H,path:{name:t},query:{window:s}}),staleTime:Hg}),i=o.data,d=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(Ve,{text:Jg})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Gt(i.startDate)," to ",Gt(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(Ja,{windows:Yg,value:s,onChange:n,label:"Google Ads time period"})]});if(o.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[d,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(v=>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"})]},v))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(o.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[d,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",jt(o.error)]}),e.jsx(R,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{o.refetch()},children:"Retry performance"})]});const{totals:c,daily:h,campaigns:m,comparison:u,comparisonUnavailableReason:y,source:p}=i;if(!p){const v=y==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[d,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:v?ef:Xg}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:v?tf:Zg})]})]})}const x=p.currencyCode,g=p.campaignsInInventory>0&&p.campaignsQueried<p.campaignsInInventory?{queried:p.campaignsQueried,inInventory:p.campaignsInInventory}:null,f=c.costMicros>0&&c.conversions===0,S=[{key:"spend",comparable:!0,label:"Spend",value:Rn(c.costMicros,x),change:u?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:Ar.format(c.conversions),change:u?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:f?"no conversions":Rn(c.costPerConversionMicros,x),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Pr(c.conversionRate),change:u?.change.conversionRate??null,direction:"up-good",seriesKey:null}],N=[{key:"clicks",label:"Clicks",value:Us.format(c.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:Us.format(c.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Pr(c.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:Rn(c.cpcMicros,x),seriesKey:null}],E={costMicros:{label:"Spend",color:it[1],axisId:"spend",formatValue:v=>Rn(v,x)},conversions:{label:"Conversions",color:it[0],axisId:"conversions",formatValue:v=>Ar.format(v)},clicks:{label:"Clicks",color:it[2],axisId:"clicks",formatValue:v=>Us.format(v)},impressions:{label:"Impressions",color:it[3],axisId:"impressions",formatValue:v=>Us.format(v)}},A=[...a].map(v=>({dataKey:v,...E[v]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[d,g!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",Us.format(g.queried)," of"," ",Us.format(g.inInventory)," campaigns, so they are a subset of the account."]}):null,p.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,!u&&y==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:sf["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:S.map(v=>{const w=v.seriesKey!==null&&a.has(v.seriesKey),j=w&&a.size===1,L=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[v.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:w?E[v.seriesKey].color:"var(--color-mono-600)"}}):null,v.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:v.value}),u&&v.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${lf(v.change,v.direction)}`,children:af(v.change,u.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:v.comparable?`no prior ${s} period stored`:" "})]});return v.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:L},v.key):e.jsx("button",{type:"button","aria-pressed":w,disabled:j,onClick:()=>r(q=>{const D=new Set(q);return D.has(v.seriesKey)?D.delete(v.seriesKey):D.add(v.seriesKey),D.size===0?q:D}),className:`rounded-md border px-3 py-2 text-left transition-colors ${w?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${j?"cursor-default":""}`,children:L},v.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:N.map(v=>{const w=v.seriesKey!==null&&a.has(v.seriesKey),j=w&&a.size===1,L=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[v.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:w?E[v.seriesKey].color:"var(--color-mono-600)"}}):null,v.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:v.value})]});return v.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:L},v.key):e.jsx("button",{type:"button","aria-pressed":w,disabled:j,onClick:()=>r(q=>{const D=new Set(q);return D.has(v.seriesKey)?D.delete(v.seriesKey):D.add(v.seriesKey),D.size===0?q:D}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${j?"cursor-default":"hover:bg-surface-hover"}`,children:L},v.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Sl,{data:h,xKey:"date",series:A,xTickFormatter:Nn,labelFormatter:Gt}),e.jsx("ul",{className:"sr-only",children:h.map(v=>e.jsxs("li",{children:[Gt(v.date),":"," ",A.map(w=>`${w.label} ${E[w.dataKey].formatValue(v[w.dataKey])}`).join(", "),v.origin==="filled"?", no delivery reported":""]},v.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:m.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):m.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:v.name??v.campaignId,children:v.name??e.jsx("span",{className:"font-mono text-secondary",children:v.campaignId})}),e.jsx("td",{children:e.jsx(ce,{tone:rf(v.status),children:of(v.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Us.format(v.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Us.format(v.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Rn(v.totals.costMicros,x)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ar.format(v.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Pr(v.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:v.totals.costMicros>0&&v.totals.conversions===0?e.jsx(ce,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:Rn(v.totals.costPerConversionMicros,x)})})]},v.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Ys(Es(p.capturedAt))," · ","customer ",p.customerId," · ","latest closed day ",Gt(p.asOfDate),p.openDate?e.jsxs(e.Fragment,{children:[" · ",Gt(p.openDate)," still open, excluded"]}):null,p.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",p.timeZone]}):null]})]})]})}const Rr=20,Ts=50,df=50,uf=50;function gi(t){return t==="viewer"}function fi(t){return t?.status==="unavailable"}function sc(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function nc(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 $a(t,s,n){if(t.kind==="all")return s.map(o=>o.id);if(t.kind==="specific")return s.filter(o=>t.propertyIds.includes(o.id)).map(o=>o.id);const a=new Set(t.groupIds),r=new Set(n.filter(o=>a.has(o.id)).flatMap(o=>o.propertyIds));return s.filter(o=>r.has(o.id)).map(o=>o.id)}function mf(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(o=>o.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function Ir(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 $o(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Mo(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 Ma(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 ti(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Tr(t){return ti(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function si({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[o,i]=l.useState(""),[d,c]=l.useState(!1),h=o.trim().toLocaleLowerCase(),m=h?t.filter(x=>x.label.toLocaleLowerCase().includes(h)):t,u=d?m:m.slice(0,df),y=u.length<m.length;function p(){const x=new Set([...s,...u.map(g=>g.id)]);n(t.filter(g=>x.has(g.id)).map(g=>g.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:o,onChange:x=>i(x.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(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:u.length===0,onClick:p,children:"Select all shown"}),e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),m.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 ",u.length," of ",m.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:u.map(x=>{const g=s.includes(x.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 ${x.label}`,checked:g,type:"checkbox",onChange:f=>n(sc(s,x.id,f.currentTarget.checked))}),e.jsx("span",{children:x.label})]}),x.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[x.urlCount," URLs"]})]},x.id)})}),y?e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>c(!0),children:"Show all Properties"}):null]})]})}function yi(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(ce,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function bi({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(ce,{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 hf({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,i]=l.useState(null),d=t.preview,c=d?.counts.needsAttention??0,h=d?.rows.filter(j=>j.status==="matched")??[],m=d?.rows??[],u=m.filter(j=>j.status!=="matched"),y=Math.max(1,Math.ceil(m.length/Ts)),p=Math.min(s,y-1),x=m.slice(p*Ts,(p+1)*Ts),g=Math.max(1,Math.ceil(u.length/Ts)),f=Math.min(a,g-1),S=u.slice(f*Ts,(f+1)*Ts),N=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,E=h.length>0&&!t.isApplying,A=d!==null&&o===d.previewChecksum,v=u.length>0&&f===g-1;l.useEffect(()=>{n(0),r(0),i(null)},[d?.previewChecksum]);async function w(j){if(j)try{t.onCsvChange(await j.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:j=>{w(j.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:j=>t.onCsvChange(j.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(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!N,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]}),d?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:[d.counts.matchedRows," matched · ",d.counts.groupsReady," group",d.counts.groupsReady===1?"":"s"," ready",c>0?` · ${c} need${c===1?"s":""} attention`:""]}),d.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:d.groupChanges.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:j.label}),e.jsx("td",{className:"text-secondary",children:j.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:j.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[j.addedTargetKeys.length,j.unchangedTargetKeys.length>0?` · ${j.unchangedTargetKeys.length} already members`:""]})]},j.groupKey))})]})}):null,d.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 (",d.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:x.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:j.dataRow}),e.jsx("td",{className:"text-heading",children:j.property}),e.jsx("td",{className:"text-secondary",children:j.group}),e.jsxs("td",{children:[e.jsx(ce,{tone:$o(j.status),children:Mo(j.status)}),Ma(j)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Ma(j)}):null]})]},j.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",p+1," of ",y," · ",d.rows.length," rows"]}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===0,onClick:()=>n(j=>Math.max(0,j-1)),children:"Previous 50 rows"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===y-1,onClick:()=>n(j=>Math.min(y-1,j+1)),children:"Next 50 rows"})]})]}):null,c>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",c," row",c===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:S.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:j.dataRow}),e.jsx("td",{className:"text-heading",children:j.property}),e.jsx("td",{className:"text-secondary",children:j.group}),e.jsxs("td",{children:[e.jsx(ce,{tone:$o(j.status),children:Mo(j.status)}),Ma(j)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Ma(j)}):null]})]},j.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 ",f+1," of ",g]}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===0,onClick:()=>r(j=>Math.max(0,j-1)),children:"Previous 50 exceptions"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===g-1,onClick:()=>r(j=>Math.min(g-1,j+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:A,disabled:t.isApplying||!v,onChange:j=>i(j.currentTarget.checked?d.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",c," row",c===1?"":"s"," will be skipped."]}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!E||!A,onClick:()=>{t.onApply(h.map(j=>j.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(R,{type:"button",className:"mt-3 min-h-11",disabled:!E,onClick:()=>{t.onApply(h.map(j=>j.dataRow))},children:t.isApplying?"Creating groups…":`Create ${d.counts.groupsReady} group${d.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const xf="—";function pf({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:o=!1,isBusy:i=!1,canContinue:d=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:h,onClearQueryAssignments:m,onRemoveQuery:u,onCreateQueries:y,onCreateAndPairQuestions:p,isCreatingQueries:x=!1,createQueriesError:g=null,onManageProjectQueries:f,groups:S,audience:N,onAudienceChange:E,assignmentImpact:A=null,isPreviewingAssignmentImpact:v=!1,assignmentImpactError:w=null,onRetryAssignmentImpact:j,assignmentNotice:L=null,onReplaceAssignments:q,isReplacingAssignments:D=!1,onBack:X,onContinue:G}){const[K,Q]=l.useState(""),[C,te]=l.useState(!1),[z,Y]=l.useState(!1),[V,U]=l.useState(""),[F,T]=l.useState(""),[ae,I]=l.useState(null);if(fi(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(bi,{message:s.message})});const Z=gi(t),se=N,de=E,J=$a(se,n,S),ie=J.length,ye=ie>0&&r.length>0&&!o&&!i&&!v&&A!==null&&w===null,ee=m??u,me=K.trim().toLocaleLowerCase(),B=me?a.filter(P=>Tr(P).toLocaleLowerCase().includes(me)):a,xe=B.filter(P=>(P.propertyIds?.length??0)===0),Se=z?xe:B,Ce=C?Se:Se.slice(0,uf),tt=Ce.filter(P=>!ti(P)),Qe=[...new Set(V.split(`
|
|
4
|
-
`).map(P=>P.trim()).filter(Boolean))],Ge=[...F.matchAll(/\{([a-z][\w-]*)\}/gi)].map(P=>P[1]),st=n.filter(P=>J.includes(P.id)),qe=Ge.length===0||F.trim()===""?[]:st.map(P=>({propertyId:P.id,text:Ge.reduce((ge,Oe)=>ge.replaceAll(`{${Oe}}`,P.label),F.trim())})),O=[...new Set(qe.map(P=>P.text))];function Le(){const P=new Set([...r,...tt.map(ge=>ge.id)]);c(a.filter(ge=>P.has(ge.id)).map(ge=>ge.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."})]})}),Z?e.jsx(yi,{}):null,Z?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:se.kind==="all"?"all":se.kind==="specific"?"specific":`group:${se.groupIds[0]??""}`,onChange:P=>{const ge=P.currentTarget.value;ge==="all"?de({kind:"all"}):ge==="specific"?de({kind:"specific",propertyIds:[]}):ge.startsWith("group:")&&de({kind:"groups",groupIds:[ge.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]}),S.length>0?e.jsx("optgroup",{label:"Groups",children:S.map(P=>{const ge=$a({kind:"groups",groupIds:[P.id]},n,S).length;return e.jsx("option",{value:`group:${P.id}`,disabled:ge===0,children:Ir(P,n)},P.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),se.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:se.groupIds.map(P=>{const ge=S.find(Oe=>Oe.id===P);return ge?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:[Ir(ge,n),e.jsx("button",{type:"button","aria-label":`Remove ${ge.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 Oe=se.groupIds.filter(We=>We!==ge.id);de(Oe.length>0?{kind:"groups",groupIds:Oe}:{kind:"all"})},children:"×"})]},ge.id):null})}),S.some(P=>!se.groupIds.includes(P.id)&&$a({kind:"groups",groupIds:[P.id]},n,S).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:P=>{P.currentTarget.value&&de({kind:"groups",groupIds:[...se.groupIds,P.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"}),S.filter(P=>!se.groupIds.includes(P.id)).map(P=>{const ge=$a({kind:"groups",groupIds:[P.id]},n,S).length;return e.jsx("option",{value:P.id,disabled:ge===0,children:Ir(P,n)},P.id)})]})]}):null,ie===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,se.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(si,{legend:"Specific Properties",properties:n,selectedPropertyIds:se.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:P=>{de({kind:"specific",propertyIds:P})}})}):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."})]}),Z||!y?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:V,onChange:P=>U(P.currentTarget.value),placeholder:`best apartments in dallas
|
|
5
|
-
luxury apartments atlanta
|
|
6
|
-
pet friendly apartments austin`}),g?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:g}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Qe.length===0||x||i,onClick:()=>{Promise.resolve(y(Qe)).then(()=>U(""),()=>{})},children:x?"Adding…":`Add ${Qe.length||""} ${Qe.length===1?"query":"queries"}`.replace(" "," ")}),f?e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:f,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:F,onChange:P=>T(P.target.value),placeholder:"apartments near {property}"}),F.trim()===""?null:Ge.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."]}):st.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(P=>e.jsx("li",{className:"text-sm text-strong",children:P},P))}),O.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",O.length-3," more"]}):null]}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:qe.length===0||x||i||!p,onClick:()=>{p&&Promise.resolve(p(qe)).then(()=>T(""),()=>{})},children:x?"Adding…":`Add ${qe.length||""} ${qe.length===1?"query":"queries"}`.replace(" "," ")}),qe.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"," ",qe.length," assignment",qe.length===1?"":"s","."]}):null]})]})]}),Z?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(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:tt.length===0,onClick:Le,children:"Select all shown queries"}),e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>c([]),children:"Clear query selection"}),e.jsx(R,{type:"button",size:"sm",className:"min-h-11",disabled:!ye,onClick:()=>{h({queryIds:r,propertyIds:J,...se.kind==="groups"?{groupIds:se.groupIds}:{}})},children:o?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${mf(se,S,ie)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[v?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,A?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",A.assignmentCount," Property assignment",A.assignmentCount===1?"":"s"," · ",A.addedAssignments," new, ",A.alreadyPresentAssignments," already assigned"," · ",A.fullRunProviderCalls," provider request",A.fullRunProviderCalls===1?"":"s"," per full run"," · ",A.addedProviderCalls," new",se.kind==="groups"?` · ${A.resolvedPropertyCount} unique ${A.resolvedPropertyCount===1?"Property":"Properties"}${A.overlapCount>0?`, ${A.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):w?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:w}),j?e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:j,children:"Retry impact"}):null,X?e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:X,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",ie," Properties = ",r.length*ie," assignments"]})]}),L?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:L}):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:K,onChange:P=>{Q(P.currentTarget.value),te(!1)},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400",placeholder:"Query text"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:["Showing ",Ce.length," of ",Se.length," queries,"," ",B.length-xe.length," of ",B.length," applied"]}),Z||xe.length===0?null:e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{Y(P=>!P),te(!1)},children:z?"Show all queries":`Show the ${xe.length} not applied`})]})]}):null,Ce.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:[Z?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),Z?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:Ce.map(P=>{const ge=ti(P),Oe=Tr(P),We=r.includes(P.id),_e=(P.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[Z?null:ge?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 ${Oe}`,checked:We,type:"checkbox",onChange:he=>c(sc(r,P.id,he.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:Oe})}),e.jsx("td",{className:"text-secondary",children:nc(P.propertyIds??[],n)}),Z?null:e.jsx("td",{className:"text-right",children:_e?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[q?e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||D,onClick:()=>I({queryId:P.id,propertyIds:[...P.propertyIds??[]]}),"aria-label":`Replace query assignments for ${Oe}`,children:"Replace assignments"}):null,e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{ee(P.id)},"aria-label":`Clear query assignments for ${Oe}`,children:"Clear assignments"})]}):null})]},P.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,Z||!ae?null:(()=>{const P=a.find(We=>We.id===ae.queryId),ge=P?Tr(P):"this query",Oe=ae.propertyIds.filter(We=>n.some(_e=>_e.id===We));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 “",ge,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(si,{legend:"Properties for this query",properties:n,selectedPropertyIds:Oe,onSelectedPropertyIdsChange:We=>I(_e=>_e&&{..._e,propertyIds:[...We]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:D||i,onClick:()=>I(null),children:"Keep current assignments"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Oe.length===0||D||i||!q,onClick:()=>{q&&Promise.resolve(q({queryId:ae.queryId,propertyIds:Oe}))},children:D?"Replacing assignments…":`Replace with ${Oe.length} ${Oe.length===1?"Property":"Properties"}`})]})]})})(),Ce.length<Se.length?e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>te(!0),children:"Show all queries"}):null,Z?null:e.jsxs(e.Fragment,{children:[d?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 ${X?"justify-between":"justify-end"}`,children:[X?e.jsx(R,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:X,children:"Back"}):null,e.jsx(R,{type:"button",variant:ye?"outline":"default",className:"min-h-11",disabled:!d||i,onClick:G,children:"Continue"})]})]})]})}function gf({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:o=!1,onGroupDraftChange:i,onSaveGroup:d,onEditGroup:c,onRemoveGroup:h,onClearGroupDraft:m,membershipImport:u,onBack:y,onContinue:p}){if(fi(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(bi,{message:s.message})});const x=gi(t),g=r.name.trim().length>0&&r.propertyIds.length>0&&!o,f=n.filter(A=>r.propertyIds.includes(A.id)).length,S=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,N=!x&&(c!==void 0||h!==void 0);function E(){if(m){m();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."})]})}),x?e.jsx(yi,{}):null,x||!u?null:e.jsx(hf,{value:u}),x?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:A=>i({...r,name:A.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:[f," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(si,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:A=>i({...r,propertyIds:A})})})]}),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:A=>i({...r,competitorDomains:A.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!g,onClick:()=>{d(r)},children:o?"Saving group…":"Save group"}),e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!S,onClick:E,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."})]}),S?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"}),N?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:A.name}),e.jsx("td",{className:"text-secondary",children:nc(A.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:A.competitors.length>0?A.competitors.join(", "):"None"}),N?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[c?e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${A.name}`,onClick:()=>c(A),children:"Edit"}):null,h?e.jsx(R,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${A.name}`,onClick:()=>{h(A.id)},children:"Remove"}):null]})}):null]},A.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,x?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${y?"justify-between":"justify-end"}`,children:[y?e.jsx(R,{type:"button",variant:"outline",className:"min-h-11",onClick:y,children:"Back"}):null,e.jsx(R,{type:"button",className:"min-h-11",disabled:S,onClick:p,children:a.length===0&&!S?"Continue without groups":"Continue"})]})]})}function ff({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:o,onReviewChanges:i,isReviewing:d=!1,canReviewChanges:c=!0,reviewedChanges:h,reviewChangesError:m,canPublish:u,isPublishing:y=!1,onPublish:p}){const[x,g]=l.useState(Rr),[f,S]=l.useState(Rr),[N,E]=l.useState(Rr);if(fi(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(bi,{message:s.message})});const A=gi(t),v=r?.items??[],w=r?.coverageItems??[],j=v.slice(0,x),L=w.slice(0,f),q=a.slice(0,N),D=i!==void 0,X=h!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),A?e.jsx(yi,{}):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,")"]}),v.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:j.map(G=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:G.url}),e.jsx("p",{className:"mt-1 text-secondary",children:G.reason})]},`${G.url}-${G.reason}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected sitemap URLs before confirming."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",j.length," of ",v.length]}),j.length<v.length?e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>g(G=>G+Ts),children:"Show next 50 URLs"}):null]})]}):null,A?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,")"]}),L.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[L.map(G=>e.jsxs("section",{"aria-label":`${G.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:G.property}),e.jsxs("div",{className:"mt-2 grid gap-3 text-sm md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Saved URLs"}),e.jsx("ul",{className:"mt-1 space-y-1",children:G.savedUrls.map(K=>e.jsx("li",{className:"break-all text-secondary",children:K},K))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),G.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:G.currentSitemapUrls.map(K=>e.jsx("li",{className:"break-all text-secondary",children:K},K))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},G.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",L.length," of ",w.length]}),L.length<w.length?e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>S(G=>G+Ts),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(R,{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??xf})]})})]})}),n.providerCalls===void 0?e.jsx("p",{className:"supporting-copy",children:"Review changes to see how many provider requests one run will make."}):null,n.assignments!==void 0&&n.assignments>n.queries?e.jsxs("p",{className:"supporting-copy",children:[n.queries," ",n.queries===1?"query":"queries"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a query aimed at a market is measured on every Property in it."]}):null,h?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:h.title}),h.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:h.items.map((G,K)=>e.jsx("li",{children:G},`${G}-${K}`))}):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:q.map(G=>e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-heading",children:G.title}),G.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:G.detail}):null]}),e.jsx(ce,{tone:G.tone??"caution",children:"Needs attention"})]},G.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",q.length," of ",a.length]}),q.length<a.length?e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>E(G=>G+Ts),children:"Show next 50 exceptions"}):null]})]})]}),A?null:e.jsxs(e.Fragment,{children:[D&&m?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:m}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${o?"justify-between":"justify-end"}`,children:[o?e.jsx(R,{type:"button",variant:"outline",className:"min-h-11",onClick:o,children:"Back"}):null,i!==void 0&&!X?e.jsx(R,{type:"button",className:"min-h-11",disabled:d||!c,onClick:()=>{i()},children:d?"Reviewing changes…":"Review changes"}):e.jsx(R,{type:"button",className:"min-h-11",disabled:!u||y,onClick:()=>{p()},children:y?"Publishing setup…":"Publish setup"})]})]})]})}const yf={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function bf(t){return t.trim().toLocaleLowerCase()}function vf(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function jf({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 Nf({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const o=!t||r==="reviewing",i=o||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function d(c,h){n({...s,[c]:h})}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(ce,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:c=>{c.preventDefault(),!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:o,onChange:c=>d("sitemapUrl",c.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:o,onChange:c=>d("examplePropertyUrl",c.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:o,onChange:c=>d("preferredHost",c.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:o,onChange:c=>d("propertyPathPattern",c.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:o,onChange:c=>d("additionalHost",c.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:o,onChange:c=>d("additionalPathPattern",c.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:o,onChange:c=>d("excludedPaths",c.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(R,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function wf({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:o,onSelectedPropertyIdsChange:i,onContinue:d,isContinuing:c=!1,onRetryProperties:h,onReturnToImport:m,maxVisibleProperties:u,onShowAllProperties:y}){const p=bf(a),x=s.filter(q=>vf(q,p)),g=Math.max(1,u??x.length),f=x.slice(0,g),S=new Set(o),N=s.filter(q=>S.has(q.id)).map(q=>q.id),E=f.length<x.length;function A(q){const D=new Set(q);i(s.filter(X=>D.has(X.id)).map(X=>X.id))}function v(q,D){if(!t||c)return;const X=new Set(N);D?X.add(q):X.delete(q),A(X)}function w(){!t||c||A([...N,...f.map(q=>q.id)])}function j(){!t||c||i([])}function L(){!t||c||N.length===0||d(N)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||c,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:m,children:"Review sitemap"})]}):null,n==="ready"&&s.length>0?e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:a,disabled:c,onChange:q=>r(q.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(R,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:w,children:"Select all shown"}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",disabled:c||N.length===0,onClick:j,children:"Clear selection"})]}):null]}),x.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(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:m,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 ",f.length," of ",x.length," Properties"]}),e.jsxs("p",{children:[N.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:f.map(q=>{const D=yf[q.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:q.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(jf,{property:q})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(ce,{tone:D.tone,children:D.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 ${q.name}`,checked:N.includes(q.id),disabled:c,onChange:X=>v(q.id,X.target.checked),className:"size-6 accent-accent"})})}):null]},q.id)})})]})}),E&&y?e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:c,onClick:y,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(R,{type:"button",variant:"ghost",disabled:c,onClick:m,children:"Back"}),e.jsx(R,{type:"button",disabled:c||N.length===0,onClick:L,children:c?"Saving Properties…":"Continue"})]}):null]}):null]})}function Sf(t){return t.activeStep==="import"?e.jsx(Nf,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(wf,{...t})}const Cf=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function kf({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:o}){const i=l.useRef(null),d=l.useRef(null),c=l.useRef(null),h=l.useRef(null),m=l.useRef(!1),[u,y]=l.useState(!1);return l.useEffect(()=>{s||y(!1)},[s]),l.useEffect(()=>{const p=m.current;m.current=u,u?c.current?.focus():p&&h.current?.focus()},[u]),l.useEffect(()=>{const p=i.current;if(i.current=t,p===null||p===t)return;const x=d.current?.querySelector('h1, h2, h3, [role="heading"]');x&&(x.tabIndex=-1,x.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(ce,{tone:"caution",children:"Unpublished changes"}),n&&a?u?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(R,{ref:c,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>y(!1),children:"Keep editing"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(R,{ref:h,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>y(!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:Cf.map(p=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===p.id?"step":void 0,onClick:()=>r(p.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===p.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:p.label}):e.jsx("span",{"aria-current":t===p.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===p.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:p.label})},p.id))})}),e.jsx("div",{ref:d,children:o})]})}function Af(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Sf,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(pf,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(gf,{...t.groups,access:s}):"review"in t?e.jsx(ff,{...t.review,access:s}):null}function La(t){return e.jsx(kf,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Af(t)})}function ac(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Ot(t){return{"If-Match":t,"Idempotency-Key":ac()}}function hn(t){return t instanceof bn&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function cs(t,s){return t instanceof bn?s:(t instanceof Error?t.message.trim():"")||s}function Pf(t){const s="Could not calculate assignment impact.";if(!(t instanceof bn)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const Rf={loadSetup:t=>gt(()=>Nu({client:H,path:{name:t}})),loadDraft:t=>gt(()=>ju({client:H,path:{name:t}})),createDraft:(t,s)=>gt(()=>vu({client:H,path:{name:t},headers:{"Idempotency-Key":ac()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>gt(()=>bu({client:H,path:{name:t},headers:Ot(s),body:n})),applySitemapSelection:(t,s,n,a)=>gt(()=>yu({client:H,path:{name:t},headers:Ot(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>gt(()=>fu({client:H,path:{name:t},body:s})),applyAssignments:(t,s,n)=>gt(()=>gu({client:H,path:{name:t},headers:Ot(s),body:n})),replaceAssignments:(t,s,n)=>gt(()=>pu({client:H,path:{name:t},headers:Ot(s),body:n})),applyPairedAssignments:(t,s,n)=>gt(()=>xu({client:H,path:{name:t},headers:Ot(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>gt(()=>hu({client:H,path:{name:t},headers:Ot(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>gt(()=>mu({client:H,path:{name:t},headers:Ot(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>gt(()=>uu({client:H,path:{name:t},headers:Ot(s),body:{target:n}})),upsertGroup:(t,s,n)=>gt(()=>du({client:H,path:{name:t},headers:Ot(s),body:{group:n}})),removeGroup:(t,s,n)=>gt(()=>cu({client:H,path:{name:t},headers:Ot(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>gt(()=>lu({client:H,path:{name:t},headers:Ot(s),body:n})),removeCompetitor:(t,s,n,a)=>gt(()=>ou({client:H,path:{name:t},headers:Ot(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>gt(()=>iu({client:H,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>gt(()=>ru({client:H,path:{name:t},headers:Ot(s),body:n})),compilePreview:t=>gt(()=>au({client:H,path:{name:t}})),diffPreview:t=>gt(()=>nu({client:H,path:{name:t}})),publish:(t,s,n)=>gt(()=>su({client:H,path:{name:t},headers:Ot(s),body:n})),discard:(t,s)=>gt(()=>tu({client:H,path:{name:t},headers:Ot(s)}))},Lo={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},Yn={name:"",propertyIds:[],competitorDomains:""},qo=50;function ea(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function If(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 Eo(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 Tf(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,d=i.startsWith("*"),c=i.endsWith("*"),h=i.slice(d?1:0,c?-1:void 0).trim();if(!h)throw new Error("Ignored URL patterns must include text besides *.");const m=d&&c?"contains":d?"suffix":c?"prefix":"exact",u=`${m}:${h}`;n.has(u)||(n.add(u),s.push({kind:m,value:h}))}return s}function $f(t){const s=If(t.sitemapUrl),n=t.examplePropertyUrl.trim()?ea(t.examplePropertyUrl):null,a=ea(t.preferredHost)??n??ea(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=ea(t.additionalHost),o=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(o!==i||o&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const d=Tf(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:Eo(t)},...r?{aliases:[{host:r,pathTemplate:Eo({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...d.length>0?{excludedSlugPatterns:d}:{}}}}function Mf(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 Lf(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 Do(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function qf(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function $r(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 Oo(t){return ea(t)}function rc(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 ic(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 oc(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function lc(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Ef(t,s){const n=rc(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="urlMatchers"&&typeof r=="number"){const o=n.urlMatchers[r];return o?`${n.label} — ${o}`:n.label}if(a==="aliases"&&typeof r=="number"){const o=n.aliases[r];return o?`${n.label} — ${o}`:n.label}return n.label}function Df(t,s){const n=ic(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="competitors"&&typeof r=="number"){const o=n.competitors.at(r)?.domain;return o?`${n.label} — ${o}`:n.label}if(a==="targetKeys"&&typeof r=="number"){const o=lc(t.authoring,n.targetKeys[r]);return`${n.label} — ${o}`}return n.label}function Of(t,s){const n=oc(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${lc(t.authoring,n.targetKey)} — ${a}`}function Ff(t,s){return s.path[0]==="identities"?"Project domain":Ef(t,s)??Df(t,s)??Of(t,s)}function Fo(t,s,n){const a=oc(t.authoring,s.path);if(!a)return;const r={...t.authoring?.defaultContext,...a.contextOverride},o=s.path.at(-1);if(n==="models"&&typeof o=="string")return r.models?.[o];if(n==="locations"&&typeof o=="number")return r.locations?.[o]}function Kf(t,s){const n=Ff(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,Fo(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,Fo(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 qa(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function cc(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 Gf(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${qa(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${qa(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${qa(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${qa(n,"item")} need review.`:s}})()}${cc(a)}`}function _f(t,s){const n=new Map;for(const a of t){const r=Kf(a,s),o=[a.ruleId,a.severity,r.title,r.detail].join("\0"),i=n.get(o)??{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(o,i)}return[...n.values()].map((a,r)=>({id:`${a.ruleId}-${a.severity}-${r}`,title:a.meaning.title,detail:Gf(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function Mr(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function Lr(t,s,n){const a=rc(n,t.path),r=ic(n,t.path),o=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=o?n?.targets.find(m=>m.stableKey===o):void 0,d=a?.label??r?.label,c=cc(d?[d]:[]),h={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...h,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${c}`};case"excluded-target-has-assignments":return{...h,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${c}`};case"group-unknown-target":return{...h,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${c}`};case"measurement.discovery.proposed_new_target":{const m=Mr(a)??"the proposed Property";return{...h,title:"Review a new Property",detail:`Review ${m}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const m=Mr(a)??"the proposed Property",u=i?.label??"an existing Property";return{...h,title:"Review a moved Property",detail:`Review ${m}. It may be the same Property as ${u}.`}}case"measurement.discovery.rebind_ambiguous":{const m=Mr(a)??"the proposed Property",u=i?.label??"an existing Property";return{...h,title:"Choose an existing Property",detail:`Review ${m}. It may match ${u}; choose the correct Property.`}}default:return{...h,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function Uf(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,o=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),o>0&&n.push(`${o} query assignment ${o===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 ws(t){return[...new Set(t)]}function Ws(t){return ws(t).sort()}function Bf(t,s,n){return t.kind==="groups"?{groupKeys:Ws(t.groupIds),queryIds:Ws(n)}:{targetKeys:Ws(t.kind==="all"?s:t.propertyIds),queryIds:Ws(n)}}function Vf(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 Ko(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function Qf(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(Ko).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(Ko).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 zf({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:o,canEdit:i=!0,onCreateQueries:d,onManageProjectQueries:c,onPublished:h,service:m=Rf}){const[u,y]=l.useState(null),[p,x]=l.useState(null),[g,f]=l.useState("import"),[S,N]=l.useState(!0),[E,A]=l.useState(null),[v,w]=l.useState(null),[j,L]=l.useState([]),[q,D]=l.useState({...Lo}),[X,G]=l.useState("idle"),[K,Q]=l.useState(""),[C,te]=l.useState(qo),[z,Y]=l.useState([]),[V,U]=l.useState([]),[F,T]=l.useState({kind:"all"}),[ae,I]=l.useState(null),[Z,se]=l.useState(null),[de,J]=l.useState(!1),[ie,ye]=l.useState(null),[ee,me]=l.useState(0),[B,xe]=l.useState(null),[Se,Ce]=l.useState({...Yn}),[tt,Qe]=l.useState(null),[Ge,st]=l.useState(""),[qe,O]=l.useState(null),[Le,P]=l.useState(!1),[ge,Oe]=l.useState(!1),[We,_e]=l.useState(null),[he,xt]=l.useState(null),[Ue,Fe]=l.useState(null),[kt,Xe]=l.useState(null),[ke,ot]=l.useState(null),ft=l.useRef(0),qt=l.useRef(0),De=p?.draft??null,k=p?.etag??null,Ie=l.useMemo(()=>!i&&o?{baseActiveRevision:o.revision,authoring:Qf(o)}:null,[i,o]),we=De??Ie;async function ze(_){const re=++ft.current;N(!0),A(null);try{let[je,le]=await Promise.all([m.loadSetup(t),m.loadDraft(t)]);if(!le.draft&&_&&i&&(await m.createDraft(t,je.activeRevision),[je,le]=await Promise.all([m.loadSetup(t),m.loadDraft(t)])),re!==ft.current)return;y(je),x(le),f(Mf(le.draft));const Ne=$r(le.draft);Y(Ne)}catch(je){if(re!==ft.current)return;A(cs(je,"Could not load advanced measurement setup."))}finally{re===ft.current&&N(!1)}}l.useEffect(()=>(ze(!0),()=>{ft.current+=1}),[t,i,m]),l.useEffect(()=>{!S&&!De&&Ie&&f("properties")},[De,S,Ie]);async function yt(){const _=await m.loadDraft(t);return x(_),_}async function nt(_){ot(null);try{const[re,je]=await Promise.all([m.loadSetup(t),m.loadDraft(t)]);y(re),x(je);const le=$r(je.draft);Y(le),f(Ne=>Lf(je.draft,Ne)),w(_)}catch(re){w(cs(re,_))}}async function Rt(_,re,je,le={}){const{preserveBusyAction:Ne=!1}=le;if(!i||!k||Ue&&!Ne)return null;Ne||Fe(_),w(null),ot(null);try{const Ke=await re(k),ht=await yt();return L((Ke.warnings??[]).map((ct,vs)=>Lr(ct,vs,ht.draft?.authoring))),ht}catch(Ke){return hn(Ke)?await nt("This setup changed in another session. The latest draft is loaded; review your changes again."):w(cs(Ke,je)),null}finally{Ne||Fe(null)}}const Ye=l.useMemo(()=>(we?.authoring.targets??[]).map(_=>{const re=Do(_);return{id:_.stableKey,name:_.label,url:re[0]??"No URL",urls:re,state:qf(_.status)}}),[we]),ne=l.useMemo(()=>we?.authoring.targets.filter(_=>_.status==="included")??[],[we]),Ee=l.useMemo(()=>ne.map(_=>({id:_.stableKey,label:_.label,urlCount:Do(_).length})),[ne]),Pe=we?.authoring.assignments.length??0,Ae=l.useMemo(()=>{if(!we)return[];const _=new Set(s.map(le=>le.id)),re=s.map(le=>({id:le.id,text:le.query,source:"saved-project-queries",propertyIds:ws(we.authoring.assignments.filter(Ne=>Ne.queryId===le.id).map(Ne=>Ne.targetKey))})),je=ws(we.authoring.assignments.map(le=>le.queryId).filter(le=>!_.has(le))).map(le=>({id:le,source:"unavailable-tracked-query",state:"missing",propertyIds:ws(we.authoring.assignments.filter(Ne=>Ne.queryId===le).map(Ne=>Ne.targetKey))}));return[...re,...je]},[s,we]),Yt=l.useMemo(()=>(we?.authoring.groups??[]).map(_=>({id:_.stableKey,name:_.label,propertyIds:_.targetKeys,competitors:_.competitors.map(re=>re.domain)})),[we]),Jt=l.useMemo(()=>{if(V.length===0)return null;const _=Bf(F,Ee.map(je=>je.id),V);return(_.groupKeys?.length??_.targetKeys?.length??0)>0?_:null},[F,Ee,V]),_t=Jt?JSON.stringify(Jt):"";l.useEffect(()=>{const _=Jt,re=++qt.current;if(!i||!De||!k||!_){I(null),se(null),ye(null),J(!1);return}I(null),se(null),ye(null),J(!0);const je=window.setTimeout(()=>{m.previewAssignments(t,_).then(le=>{if(re===qt.current){if(le.draftEtag!==k){I(null),se(null),ye("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}I(le),se(_t)}}).catch(le=>{re===qt.current&&(I(null),se(null),ye(Pf(le)))}).finally(()=>{re===qt.current&&J(!1)})},250);return()=>{window.clearTimeout(je),qt.current+=1}},[Jt,_t,ee,i,De,k,t,m]);const bt=l.useMemo(()=>[...Pe===0?[{id:"no-query-assignments",title:"Assign at least one query",detail:"Apply a tracked query to at least one Property before publishing.",tone:"negative"}]:[],...we?.authoring.assignments.some(_=>_.queryClass==="unclassified")&&!(Ie&&o?.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"}]:[],...j],[Pe,Ie,o,j,we]),lt=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 Ut(_){let re;try{re=$f(_)}catch(le){w(cs(le,"Check the sitemap details and try again."));return}D(_),G("reviewing");const je=await Rt("import",le=>m.importSitemap(t,le,re),"Could not review this sitemap.");if(je?.draft){const le=je.draft.authoring.targets.filter(Ke=>Ke.status==="proposed").map(Ke=>Ke.stableKey),Ne=je.draft.authoring.targets.filter(Ke=>Ke.status==="included").map(Ke=>Ke.stableKey);Y([...Ne,...le]),Q(""),te(qo),f("properties"),G("idle")}else G("error")}async function as(_){if(!d||_.length===0||Ue)return[];Fe("create-queries"),Xe(null);try{return await d(_)}catch(re){throw Xe(jt(re)),re}finally{Fe(null)}}async function Bt(_){if(!De||!k||Ue)return;const re=new Set(_),le=De.authoring.targets.filter(Ke=>Ke.status==="proposed"&&Ke.discoveryIdentity).map(Ke=>({discoveryIdentity:Ke.discoveryIdentity,action:re.has(Ke.stableKey)?"create":"ignore"})),Ne=le.length>0||De.authoring.targets.some(Ke=>Ke.status!=="proposed"&&Ke.status==="included"!==re.has(Ke.stableKey));Fe("properties"),w(null),ot(null);try{if(!Ne){Y([...re]),T({kind:"all"}),f("groups");return}await m.applySitemapSelection(t,k,le,[...re]);const Ke=await yt(),ht=$r(Ke.draft);Y(ht),T({kind:"all"}),f("groups")}catch(Ke){hn(Ke)?await nt("This setup changed in another session. The latest Properties are loaded."):w(cs(Ke,"Could not save the selected Properties."))}finally{Fe(null)}}async function Vt(_){const re=_.groupIds&&_.groupIds.length>0?{groupKeys:Ws(_.groupIds),queryIds:Ws(_.queryIds)}:{targetKeys:Ws(_.propertyIds),queryIds:Ws(_.queryIds)};if(!ae||Z!==JSON.stringify(re)||!k||ae.draftEtag!==k){w("Review the latest assignment impact before assigning queries.");return}await Rt("assignments",le=>m.applyAssignments(t,le,re),"Could not apply these queries.")&&(U([]),xe(`${ae.assignments.added} new assignment${ae.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function mt(_){if(_.propertyIds.length===0)return;await Rt("replace-assignments",je=>m.replaceAssignments(t,je,{targetKeys:ws(_.propertyIds),queryIds:[_.queryId]}),"Could not replace this query assignment.")&&(U(je=>je.filter(le=>le!==_.queryId)),xe("Query assignments replaced."))}async function rs(_,re=!1){if(_.length===0)return;if(!await Rt("paired-assignments",le=>m.applyPairedAssignments(t,le,[..._]),"Could not assign these queries.",{preserveBusyAction:re}))throw new Error("Could not assign these queries.")}async function Ze(_){if(!(!i||!d||_.length===0||Ue)){Fe("create-and-pair-questions"),Xe(null);try{let re;try{re=await d(ws(_.map(Ne=>Ne.text)))}catch(Ne){throw Xe(jt(Ne)),Ne}const je=new Map(re.map(Ne=>[Ne.query,Ne.id])),le=_.map(Ne=>({targetKey:Ne.propertyId,queryId:je.get(Ne.text)})).filter(Ne=>Ne.queryId!==void 0);if(le.length!==_.length){const Ne=new Error("The created queries could not be matched to their Properties.");throw Xe("The queries were added, but could not be paired with every Property. Try again to pair them."),Ne}try{await rs(le,!0)}catch(Ne){throw Xe("The queries were added, but could not be assigned to their Properties. Try again to pair them."),Ne}}finally{Fe(null)}}}async function Et(_){if(!De)return;const re=ws(De.authoring.assignments.filter(le=>le.queryId===_).map(le=>le.targetKey));if(re.length===0)return;await Rt(`remove-${_}`,le=>m.removeAssignment(t,le,re,_),"Could not clear this query assignment.")&&U(le=>le.filter(Ne=>Ne!==_))}async function Qt(_){if(!De||!k||Ue)return;const re=_.name.trim();if(!re)return;const je=tt??ni(re,"group"),le=De.authoring.groups.find(ct=>ct.stableKey===je);if(le&&tt===null){w(`A group named "${le.label}" already exists. Edit it or choose a different name.`);return}const Ne=_.competitorDomains.split(/[\s,]+/).map(ct=>ct.trim()).filter(Boolean),Ke=Ne.find(ct=>Oo(ct)===null);if(Ke){w(`"${Ke}" is not a valid competitor domain.`);return}const ht=ws(Ne.map(ct=>Oo(ct)));Fe("group"),w(null),ot(null);try{const ct=await m.upsertGroup(t,k,{stableKey:je,label:re,targetKeys:ws(_.propertyIds),competitors:ht.map(M=>le?.competitors.find(be=>be.domain===M)??{stableKey:ni(M,"competitor"),label:M,domain:M,aliases:[]})}),vs=await yt();L(ct.warnings.map((M,be)=>Lr(M,be,vs.draft?.authoring))),Ce({...Yn}),Qe(null)}catch(ct){hn(ct)?await nt("This setup changed in another session. The latest groups are loaded."):w(cs(ct,"Could not save this group."))}finally{Fe(null)}}function fs(_){const re=De?.authoring.groups.find(je=>je.stableKey===_);re&&(Qe(_),Ce({name:re.label,propertyIds:[...re.targetKeys],competitorDomains:re.competitors.map(je=>je.domain).join(", ")}))}async function ps(_){await Rt("remove-group",je=>m.removeGroup(t,je,_),"Could not remove this group.")&&(T(je=>je.kind==="groups"&&je.groupIds.includes(_)?{kind:"all"}:je),tt===_&&(Qe(null),Ce({...Yn})))}function zt(_){st(_),O(null),_e(null),xt(null)}async function ys(){if(!(!i||!Ge.trim()||Le||ge)){P(!0),_e(null),xt(null);try{O(await m.previewGroupMembership(t,{csv:Ge}))}catch(_){O(null),_e(cs(_,"Could not review this CSV."))}finally{P(!1)}}}async function Xt(_){if(!(!i||!k||!qe||_.length===0||Ue)){if(qe.draftEtag!==k){_e("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}Oe(!0),Fe("group-import"),_e(null),xt(null),ot(null);try{const re=await m.applyGroupMembership(t,k,{csv:Ge,sourceChecksum:qe.sourceChecksum,previewChecksum:qe.previewChecksum,acceptedRows:ws(_.map(String)).map(Number)}),je=await yt();L(re.warnings.map((le,Ne)=>Lr(le,Ne,je.draft?.authoring))),st(""),O(null),xt(`${re.addedMemberships} membership${re.addedMemberships===1?"":"s"} added${re.unchangedMemberships>0?`; ${re.unchangedMemberships} already present`:""}.`)}catch(re){hn(re)?(await nt("This setup changed in another session. The latest draft is loaded; review the CSV again."),_e("The setup changed while this CSV was open. Review the latest CSV before applying it.")):_e(cs(re,"Could not apply this CSV."))}finally{Fe(null),Oe(!1)}}}async function Nt(){if(!(!De||!k||Ue||Pe===0)){Fe("review"),w(null),ot(null);try{const[_,re]=await Promise.all([m.compilePreview(t),m.diffPreview(t)]),je=[..._.checks,...re.checks],le=je.some(Ne=>Ne.ruleId==="active-revision-schema-v1");if(L(_f(je.filter(Ne=>Ne.ruleId!=="active-revision-schema-v1"),{authoring:we?.authoring,queries:s})),!_.ok||!re.ok)return;if(re.diff.activeRevision!==De.baseActiveRevision){await nt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(_.compiledChecksum!==re.compiledChecksum){w("The setup changed while it was being reviewed. Review the latest changes again.");return}ot({etag:k,baseActiveRevision:De.baseActiveRevision,compiledChecksum:_.compiledChecksum,changes:Uf(re.diff,le),providerCalls:_.plan.executionNodes.reduce((Ne,Ke)=>Ne+Ke.expectedSnapshots,0)})}catch(_){w(cs(_,"Could not review this setup."))}finally{Fe(null)}}}async function Zt(){if(!(!De||!k||!ke||Ue)){if(k!==ke.etag||De.baseActiveRevision!==ke.baseActiveRevision){ot(null),w("The setup changed after review. Review the latest changes before publishing.");return}Fe("publish"),w(null);try{await m.publish(t,k,{expectedActiveRevision:ke.baseActiveRevision,expectedCompiledChecksum:ke.compiledChecksum}),x({draft:null,etag:null}),ot(null),h?.()}catch(_){hn(_)?await nt("The setup changed before it could be published. Review the latest draft and publish again."):w(cs(_,"Could not publish this setup."))}finally{Fe(null)}}}async function vt(){if(!(!k||Ue)){Fe("discard"),w(null);try{await m.discard(t,k),x({draft:null,etag:null}),ot(null),h?.()}catch(_){hn(_)?await nt("This setup changed in another session. The latest draft is loaded."):w(cs(_,"Could not discard these changes."))}finally{Fe(null)}}}async function es(){if(!(!De||!k||!u||Ue)){Fe("restart"),w(null),ot(null);try{await m.discard(t,k),await m.createDraft(t,u.activeRevision),D({...Lo}),Q(""),Y([]),U([]),T({kind:"all"}),I(null),ye(null),xe(null),Ce({...Yn}),Qe(null),st(""),O(null),_e(null),xt(null),await ze(!1)}catch(_){hn(_)?await nt("The setup changed again. Reloaded the latest draft and published setup."):w(cs(_,"Could not restart this setup."))}finally{Fe(null)}}}if(S)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(E)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}),e.jsx(R,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{ze(!0)},children:"Try again"})]})]});if(!we||i&&!k)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&&De&&u&&De.baseActiveRevision!==u.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(R,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:Ue==="restart",onClick:()=>{es()},children:Ue==="restart"?"Restarting…":"Discard draft and restart"})]}),v?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:v}):null]});const bs=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(R,{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:[u?.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,v?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:v}):null,bs,g==="import"||g==="properties"?e.jsx(La,{currentStep:g,hasDraft:De!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{vt()},importProperties:{importDraft:q,onImportDraftChange:_=>{D(_),G("idle"),w(null)},onReviewSitemap:_=>{Ut(_)},reviewState:X,properties:Ye,propertiesState:"ready",propertiesSearch:K,onPropertiesSearchChange:Q,maxVisibleProperties:C,onShowAllProperties:()=>te(Ye.length),selectedPropertyIds:z,onSelectedPropertyIdsChange:_=>Y([..._]),onContinue:_=>{Bt(_)},isContinuing:Ue==="properties",onRetryProperties:()=>{yt()},onReturnToImport:()=>f("import")}}):g==="queries"?e.jsx(La,{currentStep:"queries",hasDraft:De!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{vt()},onManageProjectQueries:c,queries:{onCreateQueries:d?_=>as(_):void 0,isCreatingQueries:Ue==="create-queries"||Ue==="create-and-pair-questions",isBusy:Ue!==null,createQueriesError:kt,availability:lt,properties:Ee,queries:Ae,selectedQueryIds:V,isApplying:Ue==="assignments"||Ue==="paired-assignments",onSelectedQueryIdsChange:_=>U([..._]),onApplySelectedQueries:_=>Vt(_),groups:Yt,audience:F,onAudienceChange:_=>{T(_),xe(null)},assignmentImpact:ae&&Z===_t&&ae.draftEtag===k?Vf(ae):null,isPreviewingAssignmentImpact:de,assignmentImpactError:ie,onRetryAssignmentImpact:()=>me(_=>_+1),assignmentNotice:B,onReplaceAssignments:mt,isReplacingAssignments:Ue==="replace-assignments",onCreateAndPairQuestions:i&&d?Ze:void 0,onClearQueryAssignments:Et,onRemoveQuery:Et,canContinue:Pe>0,onBack:()=>f("groups"),onContinue:()=>f("review")}}):g==="groups"?e.jsx(La,{currentStep:"groups",hasDraft:De!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{vt()},groups:{properties:Ee,groups:Yt,groupDraft:Se,isSaving:Ue==="group",onGroupDraftChange:Ce,onSaveGroup:Qt,onEditGroup:_=>fs(_.id),onRemoveGroup:ps,onClearGroupDraft:()=>{Qe(null),Ce({...Yn})},membershipImport:{csv:Ge,preview:qe,isReviewing:Le,isApplying:ge,error:We,notice:he,onCsvChange:zt,onReview:ys,onApply:Xt},onBack:()=>{f("properties")},onContinue:()=>f("queries")}}):e.jsx(La,{currentStep:"review",hasDraft:De!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{vt()},review:{counts:{properties:ne.length,queries:new Set(we.authoring.assignments.map(_=>_.queryId)).size,groups:we.authoring.groups.length,assignments:we.authoring.assignments.length,providerCalls:ke?.providerCalls},flaggedExceptions:bt,reviewedChanges:ke?.changes,isReviewing:Ue==="review",canReviewChanges:Pe>0&&!Ue,onReviewChanges:Nt,onBack:()=>f("queries"),canPublish:ke!==null&&!Ue,isPublishing:Ue==="publish",onPublish:Zt}})]})}const Wf=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function Go(t){return t.label!=="Complete"}const xn="__all_properties__",Hf=50,dc=50,Yf=20,Jf=50,Xf=250,Zf=5,ey=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],ty={"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"},uc={plan_v1:"Setup update required.",no_completed_run:"Not measured yet.",no_population:"No matching queries.",evidence_incomplete:"Evidence incomplete.",not_applicable:"Not applicable.",incomplete:"The latest measurement is incomplete.","evidence-incomplete":"Some source evidence is incomplete.","no-population":"No measurements are available for this selection.",unavailable:"This measurement is unavailable."},sy={numerator:null,denominator:null,reason:"plan_v1"};function na(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 ny(t){return na(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function mc(t){if(na(t))return"";const s=t.reason??"unavailable";return uc[s]??s}function _o(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 ay(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function ry(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function iy(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function ta({metric:t,compact:s=!1}){const n=s?na(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":na(t)?"text-lg font-semibold text-heading":"text-lg font-semibold text-secondary";return e.jsx("span",{className:"inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums",...na(t)?{}:{title:mc(t)},children:e.jsx("span",{className:n,children:ny(t)})})}function vi({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(R,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Uo({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,o]=l.useState(dc),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((d,c)=>e.jsx("li",{className:a,children:d},`${d}:${c}`))}),e.jsx(vi,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>o(Number.MAX_SAFE_INTEGER)})]})]})}function oy({evidence:t,state:s="ready",onRetry:n}){const[a,r]=l.useState(dc),o=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(R,{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:o.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(ce,{tone:i.tone,children:ty[i.kind]}),i.historical?e.jsx(ce,{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(vi,{shown:o.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function ly({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Uo,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Uo,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(oy,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function cy({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(ta,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function Bo({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function o(i){if(r)return;const d=n.findIndex(m=>m.value===s);let c=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?c=(d+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?c=(d-1+n.length)%n.length:i.key==="Home"?c=0:i.key==="End"&&(c=n.length-1),c===null)return;i.preventDefault();const h=n[c];a(h.value),i.currentTarget.querySelectorAll('[role="radio"]')[c].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:o,children:n.map(i=>{const d=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":d,tabIndex:d?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${d?"segmented-option-active":""}`,children:i.label},i.value)})})}function dy({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(Ve,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function uy({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:o=!1,isViewLoading:i=!1,isLoadingMore:d=!1,isLoadMoreError:c=!1,viewSearch:h,onViewChange:m,onLoadMore:u,onPropertyExpand:y,onRetryEvidence:p,renderPropertyLink:x}){const g=t.currentView!=null,f=t.classReporting==="available"&&(g||t.classScopes!=null),[S,N]=l.useState(t.currentView?.queryClass??"all"),[E,A]=l.useState(t.currentView?.scope.key??xn),[v,w]=l.useState(h??""),[j,L]=l.useState(Hf),[q,D]=l.useState(Yf),[X,G]=l.useState(t.currentView?.sort??"label-asc"),[K,Q]=l.useState(null),C=l.useRef(h??""),te=f&&!g&&S!=="all"?S==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,z=g?{aggregate:t.currentView.aggregate,groups:[]}:te,Y=l.useCallback(O=>{if(!g||!m)return;const Le=O.scope??(E===xn?"all":"group"),P=O.search??v;C.current=P,m({scope:Le,...Le==="group"?{groupKey:O.groupKey??E}:{},queryClass:O.queryClass??S,...P?{search:P}:{},...O.sort?{sort:O.sort}:{}})},[m,v,S,E,g]);l.useEffect(()=>{!t.currentView||i||(N(t.currentView.queryClass),A(t.currentView.scope.key??xn),t.currentView.sort&&G(t.currentView.sort))},[i,t.currentView]),l.useEffect(()=>{h!==void 0&&(C.current=h,w(O=>O.trim()===h.trim()?O:h))},[h]),l.useEffect(()=>{if(!g||!m||v===C.current)return;const O=window.setTimeout(()=>Y({search:v}),Xf);return()=>window.clearTimeout(O)},[m,Y,v,g]);const V=t.availableGroups??z.groups;l.useEffect(()=>{E===xn||V.some(O=>O.id===E)||A(xn)},[V,E]);const U=g?void 0:z.groups.find(O=>O.id===E),F=U?.aggregate??z.aggregate,T=O=>f?O:sy,ae=X,I=v.trim().toLocaleLowerCase(),Z=l.useMemo(()=>!g&&I?F.properties.filter(O=>O.name.toLocaleLowerCase().includes(I)):F.properties,[F.properties,I,g]),se=g?Z:Z.slice(0,j),de=(g?t.currentView?.scope.kind==="group":U!=null)&&S==="non-brand"&&f&&(g||U.confirmedCompetitorCount>0)&&(F.shareOfVoice?.length??0)>0,J=f?F.unavailablePropertyCount??0:0,ie=t.flaggedResults.reduce((O,Le)=>O+(Le.count??1),0),ye=t.flaggedResultsTotal??ie,ee=[T(F.metrics.propertiesMentioned),T(F.metrics.mentionCoverage),T(F.metrics.citationCoverage)].map(mc).find(Boolean),me=f?t.nextActionText??ee??(J>0?`${J} ${J===1?"property is":"properties are"} unavailable.`:ye>0?`${ye} flagged ${ye===1?"result needs":"results need"} review.`:null):uc.plan_v1,Se=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?ay(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Ce=ry(t.latestMeasurement.date),tt=[{value:xn,label:"All properties"},...V.map(O=>({value:O.id,label:O.label}))],Qe=V.length>Zf;function Ge(O){A(O),Y(O===xn?{scope:"all"}:{scope:"group",groupKey:O})}function st(O){N(O),Y({queryClass:O})}function qe(O){const Le=K!==O;Q(Le?O:null),Le&&y?.(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(ce,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(ce,{tone:"caution",children:"Includes historical data"}):null,Se?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:Se}):null,Ce?e.jsx("span",{className:"text-sm text-secondary",children:Ce}):null,me?e.jsx("span",{className:"text-sm text-secondary",children:me}):null,s&&f&&n?e.jsx(R,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!f?e.jsx(R,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||o,children:o?"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:Qe?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),Qe?e.jsx("select",{id:"advanced-measurement-group",value:E,onChange:O=>Ge(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:tt.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))}):e.jsx(Bo,{ariaLabelledBy:"advanced-measurement-group-label",value:E,options:tt,onChange:Ge})]}),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(Bo,{ariaLabelledBy:"advanced-measurement-class-label",value:S,options:ey,onChange:st,disabled:!f})]}),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:v,onChange:O=>w(O.target.value),placeholder:"Search properties",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]})]}),!i&&de?e.jsx(cy,{values:F.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(Ve,{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??Z.length," ",(t.currentView?.propertyTotal??Z.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(dy,{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:[Wf.map(O=>{const Le=ae.startsWith(`${O.key}-`),P=Le&&ae.endsWith("-desc")?"descending":Le?"ascending":"none";return e.jsx("th",{"aria-sort":P,className:(O.numeric,void 0),children:m?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const ge=`${O.key}-${Le&&ae.endsWith("-asc")?"desc":"asc"}`;G(ge),Y({sort:ge})},"aria-label":`Sort by ${O.label.toLowerCase()}`,children:[O.label,e.jsx(vn,{className:`h-3 w-3 transition-transform ${Le?"opacity-100":"opacity-0"} ${P==="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:[se.map(O=>{const Le=K===O.id;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:P=>{iy(P.target)||qe(O.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[x?x({id:O.id,name:O.name}):O.name,Go(O.status)||O.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[Go(O.status)?e.jsx(ce,{tone:O.status.tone,children:O.status.label}):null,O.historical?e.jsx(ce,{tone:"caution",children:"Historical"}):null]}):null,_o(O)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:_o(O)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(ta,{metric:O.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(ta,{metric:O.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(R,{size:"icon",variant:"ghost","aria-expanded":Le,"aria-label":Le?`Hide details for ${O.name}`:`Show details for ${O.name}`,onClick:()=>qe(O.id),children:e.jsx(vn,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${Le?"rotate-180":""}`,"aria-hidden":"true"})})})]},O.id),Le?(O.providers??[]).map(P=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:P.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(ta,{metric:P.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(ta,{metric:P.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${O.id}:${P.provider}`)):null,Le?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(ly,{property:O,onRetryEvidence:p})})},`${O.id}:details`):null]},O.id)}),se.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]})]})}),g&&t.currentView.nextCursor&&u?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",se.length," of ",t.currentView.propertyTotal]}),c?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(R,{size:"sm",variant:"outline",disabled:d,onClick:()=>u(t.currentView.nextCursor),children:d?"Loading…":c?"Retry loading more properties":"Show 50 more"})]}):g?se.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",se.length," of ",t.currentView.propertyTotal]}):null:e.jsx(vi,{shown:se.length,total:Z.length,itemLabel:"properties",onShowAll:()=>L(Number.MAX_SAFE_INTEGER)})]}),!i&&!I&&ye>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 (",ye,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,q).map(O=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(ce,{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))}),q<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,q).reduce((O,Le)=>O+(Le.count??1),0)," of ",ye," flagged results"]}),e.jsx(R,{size:"sm",variant:"outline",onClick:()=>D(O=>Math.min(t.flaggedResults.length,O+Jf)),children:"Show 50 more"})]}):ie<ye?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",ie," of ",ye," flagged results"]}),g&&t.currentView.nextCursor&&u?e.jsx(R,{size:"sm",variant:"outline",disabled:d,onClick:()=>u(t.currentView.nextCursor),children:d?"Loading…":c?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function hc(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function my(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 hy({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:o,onRunMeasurement:i,onRetryReport:d,onViewChange:c,onLoadMore:h,onPropertyExpand:m,onRetryEvidence:u,renderPropertyLink:y,isRunningMeasurement:p,isOpeningSetup:x,isViewLoading:g,isLoadingMore:f,isLoadMoreError:S,viewSearch:N}){return t.surface==="simple-overview"?n:e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&o?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(R,{type:"button",size:"sm",disabled:x,onClick:o,children:x?"Opening setup…":hc(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."}),d?e.jsx(R,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:d,children:"Retry report"}):null]}):a?e.jsx(uy,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:o,onViewChange:c,onLoadMore:h,onPropertyExpand:m,onRetryEvidence:u,renderPropertyLink:y,isRunningMeasurement:p,isRepublishingSetup:x,isViewLoading:g,isLoadingMore:f,isLoadMoreError:S,viewSearch:N}):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 In={numerator:null,denominator:null,reason:"plan_v1"};function xy(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Vo(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function py(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function gy(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function fy(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 yy(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function by(t){const s=new Map;for(const n of t){const a=yy(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function vy(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(x=>[x.stableKey,x])),r=new Map(n.querySnapshots.map(x=>[x.queryId,x.queryText])),o=new Map;for(const x of n.targetQuerySelections){const g=o.get(x.targetKey)??[];g.push(...x.queryIds.map(f=>r.get(f)).filter(f=>!!f)),o.set(x.targetKey,[...new Set(g)])}const i=by(s.evidence),d=n.executionNodes.reduce((x,g)=>x+g.expectedSnapshots,0),c=s.run?.status==="completed"&&d>0,h=c?d:0,m=c?d:0,u=s.targets.map(x=>{const g=a.get(x.id),f=i.get(x.id)??[],S=f.map(A=>({id:`${A.observationId}:${A.usageEdgeId}:${A.sourceUrl}`,kind:py(A.classification),query:A.queryText,url:A.sourceUrl,tone:gy(A.classification),historical:A.historical||A.bridged})),N=f.some(A=>A.historical||A.bridged),E=s.run?x.completeness.complete?g?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${x.completeness.executed} of ${x.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:x.id,name:x.label,mentionCoverage:Vo(x.mentionCoverage),citationCoverage:Vo(x.citationCoverage),status:E,assignedQueries:o.get(x.id)??[],urls:g?.urls.map(xy)??[],evidence:S,historical:N}}),y=new Map(u.map(x=>[x.id,x])),p=new Map(n.groups.map(x=>[x.stableKey,x]));return{classReporting:"plan-v1",latestMeasurement:{status:s.run?.status==="completed"?{label:"Complete",tone:"positive"}:s.run?.status==="partial"?{label:"Partial result",tone:"caution"}:{label:"Not measured",tone:"neutral"},completedSlots:h,totalSlots:m,date:fy(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:In,mentionCoverage:In,citationCoverage:In},properties:u},groups:s.groups.map(x=>({id:x.id,label:x.label,confirmedCompetitorCount:p.get(x.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:In,mentionCoverage:In,citationCoverage:In},properties:x.targetIds.map(g=>y.get(g)).filter(g=>!!g)}}))},flaggedResults:[]}}function jy({visibility:t}){const s=t.populations.filter(a=>a.queryClass!=="unknown"||a.summary.answerCount>0),n=t.populations.filter(a=>a.queryClass!=="unknown"||a.trend.some(r=>r.answerCount>0));return e.jsxs("section",{id:"client-summary",className:"page-section-divider","aria-label":Tt.title,children:[e.jsx("h2",{className:"text-xl font-semibold text-heading",children:Tt.title}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:t.selection.mode==="advanced"?Tt.description:Tt.simpleDescription}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:wu(t)}),e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsx("tr",{children:[Tt.queryType,Tt.queries,Tt.answers,Tt.mentioned,Tt.cited].map(a=>e.jsx("th",{children:a},a))})}),e.jsx("tbody",{children:s.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:Ii(a.queryClass)}),e.jsx("td",{children:a.summary.queryCount}),e.jsx("td",{children:a.summary.answerCount}),[a.summary.mentionCoverage,a.summary.citationCoverage].map((r,o)=>e.jsxs("td",{children:[e.jsx("strong",{children:Ti(r)}),e.jsx("p",{className:"text-xs text-secondary",children:$i(r)})]},o))]},a.queryClass))})]})}),e.jsxs("details",{className:"mt-4",children:[e.jsx("summary",{className:"cursor-pointer text-sm text-secondary",children:Su(t)}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsx("tr",{children:[Tt.date,Tt.queryType,Tt.mentioned,Tt.cited,Tt.comparison].map(a=>e.jsx("th",{children:a},a))})}),e.jsx("tbody",{children:n.flatMap(a=>a.trend.map(r=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("time",{dateTime:r.createdAt,children:r.createdAt.slice(0,10)})}),e.jsx("td",{children:Ii(a.queryClass)}),[r.mentionCoverage,r.citationCoverage].map((o,i)=>e.jsxs("td",{children:[Ti(o),e.jsx("p",{className:"text-xs text-secondary",children:$i(o)})]},i)),e.jsx("td",{children:Cu(r.continuity.state,r.continuity.comparedRunId!==null&&!a.trend.some(o=>o.runId===r.continuity.comparedRunId))})]},`${a.queryClass}:${r.runId}`)))})]})})]})]})}const Ny={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function St(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function wy(t){if(!t)return"—";const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Sy(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function Cy({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[o,i]=l.useState(ku),d=Te({...Au({client:H,path:{name:t},query:{period:o}}),placeholderData:ai});async function c(){n(!0),r(null);try{await Iu(t,"client",o)}catch(m){const u=m instanceof bn||m instanceof Error?m.message:"Download failed";r(u)}finally{n(!1)}}if(d.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(d.error){const m=d.error instanceof Error?d.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-negative-400",children:m})})}const h=d.data;return h?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:h.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[h.meta.project.canonicalDomain," · ",h.meta.project.country," / ",h.meta.project.language.toUpperCase(),h.visibility?.selection.mode==="advanced"?` · ${Pu(h.visibility)}`:h.meta.location?` · Location: ${Sy(h.meta.location)}`:" · No location set"," · ","Last ",h.meta.periodDays," days"," · ","Generated ",wy(h.meta.generatedAt)]}),a&&e.jsx("p",{className:"mt-2 text-xs text-negative-400",children:a})]}),e.jsxs("div",{className:"page-header-right flex flex-col items-end gap-2",children:[e.jsx(Ay,{period:o,onChange:i}),e.jsxs(R,{variant:"secondary",size:"sm",onClick:He(c),disabled:s,children:[e.jsx(vl,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),h.visibility?e.jsx(jy,{visibility:h.visibility}):e.jsx(Ly,{report:h}),h.visibility?.selection.mode!=="advanced"&&e.jsx(ky,{report:h}),!h.visibility&&e.jsx(Ky,{report:h,audience:"client"}),e.jsx(Iy,{report:h}),e.jsx(Dy,{report:h,audience:"client",projectName:t}),e.jsx(Oy,{report:h})]}):null}function ky({report:t}){const s=[t.mentionLandscape.nonBrand?.shareOfVoice,t.mentionLandscape.branded?.shareOfVoice?.queryClass==="branded"?t.mentionLandscape.branded.shareOfVoice:void 0];return e.jsx("div",{className:"space-y-2 text-sm text-secondary","aria-label":"Share of voice",children:s.map(n=>n?e.jsxs("div",{children:[e.jsx("p",{children:Tu(n.percent,n.queryClass,n)}),n.reason?e.jsx("p",{children:sl(n.reason)}):null]},n.queryClass):null)})}function Ay({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:Ru.map(n=>{const a=n===t;return e.jsxs("button",{type:"button",onClick:()=>s(n),"aria-pressed":a,className:`segmented-option ${a?"segmented-option-active":""}`,children:[n,"d"]},n)})})}const Qo="AI Visibility — Server-Side",zo="AI engine attention",Py=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,Ry="Live telemetry from your server logs.";function Iy({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ca,{eyebrow:zo,title:Qo,subtitle:Ry}),e.jsx("p",{className:"text-sm text-muted",children:"Your server-side traffic source is connected. Numbers will appear after the next sync."})]});const n={current:s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,prior:s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior,deltaPct:dh(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,r=`vs prior ${a} days`,o=or(n,"requests",r),i=`${St(s.verifiedCrawlerHits.current)} verified · ${St(s.unverifiedCrawlerHits.current)} unverified${o?` · ${o}`:""}`,d=or(s.aiUserFetchHits,"requests",r),c=or(s.referralArrivals,"sessions",r),h=s.referralRedirects>0?`${St(s.referralRedirects)} blocked by redirects`:"",m=[c,s.referralArrivalsClassSummary,h].filter(Boolean).join(" · "),u=s.byOperator.filter(y=>y.verifiedHits>0||y.unverifiedHits>0||y.userFetchHits>0||y.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ca,{eyebrow:zo,title:Qo,subtitle:Py(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Dr,{label:"AI bot requests observed",value:St(n.current),subtitle:i}),e.jsx(Dr,{label:"AI user-fetch requests",value:St(s.aiUserFetchHits.current),subtitle:d||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(Dr,{label:"AI referral sessions",value:St(s.referralArrivals.current),subtitle:m})]}),u.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:"By AI tool"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"AI tool"}),e.jsxs("th",{children:["Bot requests (",a,"d)"]}),e.jsxs("th",{children:["User fetches (",a,"d)"]}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:u.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:y.operator}),e.jsx("td",{children:St(y.verifiedHits+y.unverifiedHits)}),e.jsx("td",{children:St(y.userFetchHits)}),e.jsx("td",{children:St(y.referralArrivals)})]},y.operator))})]})}),e.jsx("p",{className:"mt-2 text-[11px] text-muted",children:"Bot requests are bulk crawl (GPTBot, PerplexityBot, …). User fetches are on-demand reads triggered by real users inside an AI surface (ChatGPT-User, Perplexity-User, …). Verified means the request came from an IP the operator publishes as its own; unverified means the user-agent matched but the IP is not in a published range. User-fetch totals count both, since many genuine user fetches come from outside any published range."})]})]})}function Ty(t,s){return t.audience==="both"||t.audience===s}const $y={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Ha(t){return $y[t]??t.charAt(0).toUpperCase()+t.slice(1)}function My(t){if(!t)return null;const s=t.window??1,n=s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`;return t.direction==="up"?{text:`Up ${t.deltaAbs.toFixed(1)} points ${n}`,tone:"positive",arrow:"↑"}:t.direction==="down"?{text:`Down ${Math.abs(t.deltaAbs).toFixed(1)} points ${n}`,tone:"negative",arrow:"↓"}:{text:`Holding steady ${s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`}`,tone:"neutral",arrow:"→"}}function Ly({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount??0,r=a>0?`${s.mentionRate}%`:"—",o=a>0?`When customers asked AI ${a} ${a===1?"query":"queries"} about your industry, AI mentioned you in ${s.mentionedQueryCount} of ${a===1?"them":"those queries"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer queries about your business.",i=My(t.whatsChanged.mentionRate),d=n.providers.length>0?n.providers.map(Ha).join(", "):`${St(s.queryCount)} ${s.queryCount===1?"query":"queries"} tested`;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"rounded-2xl border border-default bg-bg-elevated/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-primary sm:text-7xl",children:r}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-neutral sm:text-lg",children:o}),i&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${i.tone==="positive"?"text-positive-400":i.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:i.arrow}),i.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(qr,{label:"AI mentions your name",value:`${s.mentionRate}%`,subtitle:a>0?`Says your name in ${s.mentionedQueryCount} of ${a} ${a===1?"query":"queries"}`:"No data yet"}),e.jsx(qr,{label:"AI links to your website",value:`${s.citationRate}%`,subtitle:a>0?`Cites your site as a source in ${s.citedQueryCount} of ${a} ${a===1?"query":"queries"}`:"No data yet"}),e.jsx(qr,{label:"AI tools tested",value:St(s.providerCount),subtitle:d})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-bg/40 px-4 py-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-semibold text-strong",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-strong",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-strong",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Customer queries we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["These are the ",n.queries.length," ",n.queries.length===1?"query we asked":"queries we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((c,h)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-bg/40 px-3 py-2 text-sm text-strong",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-muted",children:String(h+1).padStart(2,"0")}),e.jsxs("span",{children:['"',c,'"']})]},h))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"How often each AI tool mentions you"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Higher is better. Each bar shows the share of customer queries where the AI named you in the answer."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(c=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:Ha(c.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-positive-500/70",style:{width:`${Math.max(c.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[c.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",c.mentionedCount,"/",c.totalCount,")"]})]})]},c.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((c,h)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:c},h))})]})}function qr({label:t,value:s,subtitle:n}){return e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx("p",{className:"mt-3 text-4xl font-bold tracking-tight text-primary sm:text-5xl",children:s}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:n})]})}function qy(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function Ey(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function Dy({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(u=>Ty(u,s)),r=gh(t,a),o=s==="client",i=$u(),[d,c]=l.useState(new Set),h=d.size>0?r.filter(u=>!u.targetRef||!d.has(u.targetRef)):r,m=u=>{if(!u.targetRef)return;const y=u.targetRef;c(p=>new Set(p).add(y)),i.mutate({projectName:n,body:{targetRef:y}},{onSuccess:()=>{$e({tone:"positive",title:`Dismissed "${u.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:p=>{$e({tone:"negative",title:`Couldn't dismiss "${u.title}"`,detail:String(p)}),c(x=>{const g=new Set(x);return g.delete(y),g})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ca,{eyebrow:o?"Action plan":"Agency actions",title:o?"What to do next":"Agency Action Plan",subtitle:o?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),h.length===0?e.jsx(wi,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:h.map((u,y)=>{const p=u.evidence.length>0?u.evidence:u.why,x=u.why.length>0||u.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-default bg-surface p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-mono-800/80 text-sm font-semibold text-heading",title:"Priority — 1 will move the needle fastest",children:y+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(ce,{tone:Lu(u),children:o?qy(u.horizon):Mu(u.horizon)}),!o&&e.jsx(ce,{tone:"neutral",children:qu(u.category)}),e.jsx(ce,{tone:"neutral",children:o?Ey(u.confidence):`${Eu(u.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:u.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:u.action}),e.jsx(Gy,{items:p,limit:3,className:"mt-3"}),x&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:o?"See the data behind this":"Evidence details"}),u.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:o?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:u.why.map((g,f)=>e.jsx("li",{children:g},f))})]}),u.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:o?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:u.evidence.map((g,f)=>e.jsx("li",{children:g},f))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:o?"What success looks like:":"Win condition:"})," ",u.successMetric]}),u.targetRef&&!oe()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>m(u),className:"rounded-md border border-default bg-bg-elevated/50 px-2.5 py-1 text-[11px] font-medium text-neutral hover:border-mono-600 hover:bg-mono-800/70 hover:text-heading",title:"Stop showing this recommendation. The page-detection logic relies on GSC/GA syncs that lag by days — if you've already addressed it, dismissing keeps the report current.",children:"Mark addressed"})})]},`${u.priority}-${u.title}`)})})]})}function Wo({label:t,value:s,displayValue:n,max:a,barClass:r}){const o=a>0?Math.max(s/a*100,1.5):0;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-neutral",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${r}`,style:{width:`${o}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function Oy({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=fh(t).slice(0,5),o=s.length>0?Math.max(...s.map(c=>c.count)):0,i=n?Math.max(...n.topQueries.slice(0,5).map(c=>c.impressions),1):0,d=s.length>0||n!==null||a!==null||r.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ca,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),d?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"The websites AI tools cited most often when answering customer queries about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(c=>e.jsx(Wo,{label:c.domain+(c.isCompetitor?" (competitor)":""),value:c.count,displayValue:`${St(c.count)}×`,max:o,barClass:"bg-mono-400/70"},c.domain))})]}),a&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${a.indexedPct>=90?"text-positive-400":a.indexedPct>=70?"text-caution-400":"text-negative-400"}`,children:[a.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[St(a.indexed)," of ",St(a.total)," pages indexed"]}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${a.indexedPct>=90?"bg-positive-500/70":a.indexedPct>=70?"bg-caution-500/70":"bg-negative-500/70"}`,style:{width:`${Math.max(a.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-medium text-strong",children:St(a.notIndexed)})," ",a.notIndexed===1?"page is":"pages are"," not indexed yet."]})]}),n&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"What people search Google for"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["You appeared in ",e.jsx("span",{className:"font-semibold text-strong",children:St(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:St(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(c=>e.jsx(Wo,{label:c.query,value:c.impressions,displayValue:`${St(c.impressions)} ${c.impressions===1?"search":"searches"}`,max:i,barClass:"bg-info-500/70"},c.query))})]}),r.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Customer queries where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:r.map((c,h)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:c.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[Du(c.action),c.winnabilityClass==="ceded"&&e.jsx(ce,{tone:"caution",children:"Ceded surface"})]})]},h))})]})]}):e.jsx(wi,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function ji(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function Ni(t){return t==="up"?"↑":t==="down"?"↓":"→"}function Er({label:t,delta:s,unit:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"No prior data"})]});const a=n==="%"?"%":"",r=ji(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:uh(s);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:Ni(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function Ho({label:t,delta:s,countLabel:n,comparisonWindowDays:a}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Not enough trend data"})]});const r=ji(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=mh(s,n,`vs prior ${a} days`);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[St(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:Ni(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function Fy({movements:t,audience:s}){const n=t.filter(r=>r.direction!=="flat");if(n.length===0)return null;const a=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:a?"How each AI tool changed":"AI engine movements"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a?"AI tool":"Engine"}),e.jsx("th",{children:a?"Was":"Prior"}),e.jsx("th",{children:a?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(r=>{const o=r.deltaAbs>0?"+":"",i=ji(r.direction),d=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?Ha(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:d,children:[o,r.deltaAbs.toFixed(1),"% ",Ni(r.direction)]})]},r.provider)})})]})})]})}function Yo({insights:t,heading:s,emptyMessage:n,audience:a}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-surface p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-muted",children:n})]});const r=a==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:s}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!r&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:r?"What changed":"Title"}),e.jsx("th",{children:r?"Customer query":"Query"}),e.jsx("th",{children:r?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(o=>e.jsxs("tr",{children:[!r&&e.jsxs("td",{children:[e.jsx(ce,{tone:Ny[o.severity],children:Ou(o.severity)}),o.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",o.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[o.title,r&&o.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",o.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:o.query}),e.jsx("td",{className:"text-xs text-secondary",children:r?Ha(o.provider):o.provider})]},o.id))})]})})]})}function Ky({report:t,audience:s}){const n=t.whatsChanged,a=s==="client",r=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,o=e.jsx(ca,{eyebrow:a?"Since last check":"Section 2",title:a?"What's different since last check":"What's Changed",subtitle:a?void 0:n.headline});return r?e.jsxs("section",{className:"page-section-divider",children:[o,e.jsx(wi,{message:a?"No comparison yet — trends will appear after a few more checks.":"Trends will appear after a few more checks."})]}):e.jsxs("section",{className:"page-section-divider",children:[o,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Er,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(Er,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(Er,{label:a?"Queries AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(Ho,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(Ho,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(Fy,{movements:n.providerMovements,audience:s}),e.jsx(Yo,{insights:n.wins,heading:a?"What got better":"Wins",emptyMessage:a?"No new wins this period.":"No new gains in the latest check.",audience:s}),e.jsx(Yo,{insights:n.regressions,heading:a?"What got worse":"Regressions",emptyMessage:a?"Nothing got worse this period.":"No new regressions in the latest check.",audience:s})]})}function Dr({label:t,value:s,tone:n,subtitle:a}){const r=n==="positive"?"text-positive-400":n==="caution"?"text-caution-400":n==="negative"?"text-negative-400":"text-heading";return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${r}`,children:s}),a&&e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:a})]})}function ca({eyebrow:t,title:s,subtitle:n}){return e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("h2",{className:"page-title",children:s}),n&&e.jsx("p",{className:"page-subtitle mt-1",children:n})]})}function Gy({items:t,limit:s=3,className:n}){if(t.length===0)return null;const a=t.slice(0,s),r=t.length-a.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[a.map((o,i)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:o},i)),r>0&&e.jsxs("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-secondary",children:["+",r," more"]})]})}function wi({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function _y({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[d,c]=l.useState(null),[h,m]=l.useState(t.displayName),[u,y]=l.useState(t.canonicalDomain),[p,x]=l.useState(t.country),[g,f]=l.useState(t.language),[S,N]=l.useState(t.ownedDomains??[]),[E,A]=l.useState(""),[v,w]=l.useState(t.aliases??[]),[j,L]=l.useState(""),[q,D]=l.useState(null),[X,G]=l.useState(!1),[K,Q]=l.useState(!1),[C,te]=l.useState(""),[z,Y]=l.useState(""),[V,U]=l.useState(""),[F,T]=l.useState(""),[ae,I]=l.useState(""),[Z,se]=l.useState(null),[de,J]=l.useState(null);l.useEffect(()=>{a||(m(t.displayName),y(t.canonicalDomain),x(t.country),f(t.language),N(t.ownedDomains??[]),w(t.aliases??[]))},[t,a]);function ie(){r(!1),c(null),m(t.displayName),y(t.canonicalDomain),x(t.country),f(t.language),N(t.ownedDomains??[]),w(t.aliases??[]),A(""),L("")}function ye(){const P=E.trim();P&&(S.includes(P)||N([...S,P]),A(""))}function ee(P){N(S.filter(ge=>ge!==P))}function me(){const P=j.trim();if(!P)return;const ge=P.toLowerCase();v.some(Oe=>Oe.toLowerCase()===ge)||w([...v,P]),L("")}function B(P){w(v.filter(ge=>ge!==P))}async function xe(){if(!(!h.trim()||!u.trim()||!p.trim()||!g.trim())){i(!0),c(null);try{await s(t.name,{displayName:h.trim(),canonicalDomain:u.trim(),ownedDomains:S,aliases:v,country:p.trim(),language:g.trim()}),r(!1),$e({title:"Project settings saved",detail:`${h.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(P){c(P instanceof Error?P.message:"Failed to save")}finally{i(!1)}}}async function Se(){const P=C.trim(),ge=z.trim(),Oe=V.trim(),We=F.trim();if(!(!P||!ge||!Oe||!We)){G(!0),D(null);try{const _e={label:P,city:ge,region:Oe,country:We};ae.trim()&&(_e.timezone=ae.trim()),await Gu(t.name,_e),n(),te(""),Y(""),U(""),T(""),I(""),Q(!1),$e({title:"Location added",detail:`${P} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${P}`,dedupeMode:"drop"})}catch(_e){D(_e instanceof Error?_e.message:"Failed to add location")}finally{G(!1)}}}async function Ce(P){G(!0),D(null);try{await Ku(t.name,P),n(),$e({title:"Location removed",detail:`${P} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${P}`,dedupeMode:"drop"})}catch(ge){D(ge instanceof Error?ge.message:"Failed to remove location")}finally{G(!1)}}async function tt(P){G(!0),D(null);try{await Fu(t.name,P),n(),$e({title:"Default location updated",detail:`${P} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(ge){D(ge instanceof Error?ge.message:"Failed to set default location")}finally{G(!1)}}async function Qe(P){se(P),J(null);try{await _u(t.name,P),$e({title:`${P.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(ge){J(ge instanceof Error?ge.message:"Could not download tracking results.")}finally{se(null)}}const Ge=h!==t.displayName||u!==t.canonicalDomain||p!==t.country||g!==t.language||JSON.stringify(S)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(v)!==JSON.stringify(t.aliases??[]),st=!oe()&&!Ms(),qe="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",Le=C.trim()&&z.trim()&&V.trim()&&F.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"})]}),st&&!a&&e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),d&&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:[d,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>c(null),children:"×"})]}),st&&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:qe,type:"text",value:h,onChange:P=>m(P.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:O,children:"Canonical domain"}),e.jsx("input",{className:qe,type:"text",value:u,onChange:P=>y(P.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:O,children:"Country"}),e.jsx("input",{className:qe,type:"text",value:p,onChange:P=>x(P.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:O,children:"Language"}),e.jsx("input",{className:qe,type:"text",value:g,onChange:P=>f(P.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:S.map(P=>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:[P,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>ee(P),"aria-label":`Remove ${P}`,children:"×"})]},P))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${qe} flex-1`,type:"text",placeholder:"docs.example.com",value:E,onChange:P=>A(P.target.value),onKeyDown:P=>P.key==="Enter"&&(P.preventDefault(),ye())}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:!E.trim(),onClick:ye,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:v.map(P=>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:[P,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>B(P),"aria-label":`Remove ${P}`,children:"×"})]},P))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${qe} flex-1`,type:"text",placeholder:"Facebook",value:j,onChange:P=>L(P.target.value),onKeyDown:P=>P.key==="Enter"&&(P.preventDefault(),me())}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:!j.trim(),onClick:me,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(R,{type:"button",disabled:o||!Ge||!h.trim()||!u.trim(),onClick:He(xe),children:o?"Saving...":"Save changes"}),e.jsx(R,{type:"button",variant:"outline",disabled:o,onClick:ie,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(P=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:P},P))}):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(P=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:P},P))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.country})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.language})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[q&&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:[q,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>D(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(P=>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 ${P.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[P.label,P.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:P.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:P.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:P.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:P.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[st&&P.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:X,onClick:()=>{tt(P.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${P.label} as default location`,children:"Set default"}),st&&e.jsx("button",{type:"button",disabled:X,onClick:()=>{Ce(P.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${P.label}`,children:"Remove"})]})})]},P.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),st?K?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:qe,type:"text",value:C,onChange:P=>te(P.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:qe,type:"text",value:z,onChange:P=>Y(P.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:qe,type:"text",value:V,onChange:P=>U(P.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:qe,type:"text",value:F,onChange:P=>T(P.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:qe,type:"text",value:ae,onChange:P=>I(P.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(R,{type:"button",size:"sm",disabled:X||!Le,onClick:He(Se),children:X?"Adding...":"Add location"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:X,onClick:()=>{Q(!1),D(null)},children:"Cancel"})]})]}):e.jsx(R,{type:"button",size:"sm",variant:"outline",onClick:()=>Q(!0),children:"+ Add location"}):null]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted",children:"Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"max-w-xl text-xs leading-5 text-muted",children:"Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:Z!==null,onClick:He(()=>Qe("csv")),children:Z==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:Z!==null,onClick:He(()=>Qe("json")),children:Z==="json"?"Preparing JSON...":"Download JSON"})]})]}),de&&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:de})]})]})]})}function Jn(t){return{...t??{}}}function Uy(t,s){const n=Object.entries(t).sort(([r],[o])=>r.localeCompare(o)),a=Object.entries(s).sort(([r],[o])=>r.localeCompare(o));return n.length===a.length&&n.every(([r,o],i)=>{const d=a[i];return d?.[0]===r&&d[1]===o})}function By({project:t,onSave:s}){const{isAdmin:n}=wn(),a=Te({queryKey:["settings"],queryFn:ol,staleTime:6e4,enabled:n&&!oe()}),[r,o]=l.useState(t.providers.length===0),[i,d]=l.useState(t.providers),[c,h]=l.useState(()=>Jn(t.providerModels)),[m,u]=l.useState({providers:t.providers,providerModels:Jn(t.providerModels)}),[y,p]=l.useState(!1),[x,g]=l.useState(!1),[f,S]=l.useState(null),[N,E]=l.useState(null),A=l.useRef(null),v=a.data?.providerCatalog??[],w=l.useMemo(()=>new Set((a.data?.providers??[]).filter(Q=>Q.configured).map(Q=>Q.name)),[a.data]),j=l.useMemo(()=>{const Q=new Map(a.data?.providers.map(te=>[te.name,te.model])),C=new Map(v.map(te=>[te.name,{...te,defaultModel:Q.get(te.name)||te.defaultModel}]));for(const te of Object.keys(c))C.has(te)||C.set(te,{name:te,displayName:te,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...C.values()].sort((te,z)=>te.displayName.localeCompare(z.displayName))},[v,c,a.data?.providers]),L=!Uy(c,m.providerModels);l.useEffect(()=>{if(y||x)return;const Q={providers:t.providers,providerModels:Jn(t.providerModels)};u(Q),o(Q.providers.length===0),d(Q.providers),h(Q.providerModels)},[t]);function q(){g(!0),o(!1),i.length===0&&d([...w])}function D(Q,C,te=!1){g(!0),h(z=>{const Y={...z};return C==="__inherit__"?delete Y[Q]:C==="__custom__"?Y[Q]=te?"":Y[Q]??"":Y[Q]=C,Y}),C==="__custom__"&&queueMicrotask(()=>A.current?.focus())}function X(Q,C){g(!0),d(te=>C?[...new Set([...te,Q])]:te.filter(z=>z!==Q))}function G(){g(!1),o(m.providers.length===0),d(m.providers),h(Jn(m.providerModels)),S(null),E(null)}async function K(){if(!(a.isError||a.isLoading||!r&&i.length===0)){p(!0),S(null),E(null);try{const Q=Object.fromEntries(Object.entries(c).filter(([te,z])=>z.trim()!==""&&(r||i.includes(te)))),C={providers:r?[]:i,providerModels:Q};await s(C),u({providers:[...C.providers],providerModels:Jn(C.providerModels)}),g(!1),E("Engine settings saved. They apply on the next sweep.")}catch(Q){S(aa(Q))}finally{p(!1)}}}return oe()||!n?null:a.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):a.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):v.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(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):w.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(As,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":y,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:y,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:r,onChange:()=>{g(!0),o(!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:q})," Choose engines"]}),!r&&e.jsx("div",{className:"project-engine-list",children:j.map(Q=>{const C=i.includes(Q.name),te=w.has(Q.name),z=C&&!te,Y=c[Q.name],V=Q.knownModels.some(F=>F.id===Y),U=Y===void 0?"__inherit__":V?Y:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:C,disabled:!te&&!C,onChange:F=>X(Q.name,F.target.checked)})," ",e.jsx("span",{children:Q.displayName}),z&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),C&&(Q.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${Q.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${Q.name}`,value:U,onChange:F=>D(Q.name,F.target.value,V),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",Q.defaultModel||"default"]}),Q.knownModels.map(F=>e.jsx("option",{value:F.id,children:F.displayName},F.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),U==="__custom__"&&e.jsx("input",{ref:A,"aria-label":`${Q.displayName} custom model ID`,value:Y??"",onChange:F=>{g(!0),h(T=>({...T,[Q.name]:F.target.value}))},"aria-describedby":`project-model-hint-${Q.name}`}),e.jsxs("p",{id:`project-model-hint-${Q.name}`,className:"project-engine-help",children:[Y?"Project override":"Inherited from instance settings",". ",Q.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},Q.name)})})]}),!r&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),f&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:f}),N&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:N}),L&&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(R,{type:"button",onClick:()=>{K()},disabled:y||!r&&i.length===0,children:y?"Saving engines…":"Save engines"}),e.jsx(R,{type:"button",variant:"outline",onClick:G,disabled:y,children:"Cancel"})]})]})}const Ea={edit:"Edit schedule",pause:"Pause",resume:"Resume",save:"Save schedule"},Vy=[{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"}],Jo=["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 Or(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),[o,i]=t.time.split(":").map(Number),d=Number.isInteger(o)&&Number.isInteger(i)?new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",timeZone:"UTC"}).format(new Date(Date.UTC(1970,0,1,o,i))):t.time;return`Every ${t.everyDays} days starting ${r} at ${d} · ${n}`}function Qy({projectName:t}){const s=Kt(),n=!oe()&&!Ms()&&!s,a=xs(),[r,o]=l.useState(!1),[i,d]=l.useState("daily"),[c,h]=l.useState(6),[m,u]=l.useState(""),[y,p]=l.useState(14),[x,g]=l.useState(""),[f,S]=l.useState("00:00"),[N,E]=l.useState("UTC"),[A,v]=l.useState(!1),[w,j]=l.useState(""),[L,q]=l.useState(!1),[D,X]=l.useState(!1),[G,K]=l.useState(null),[Q,C]=l.useState(void 0),te=Uu({client:H,path:{name:t}}),z=Te({...hl({client:H,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),Y=z.isPending||z.isFetching,V=z.isError,U=z.data?.find(ee=>ee.kind==="answer-visibility")??null,F=r&&Q!==void 0&&(U?.updatedAt??null)!==Q,T=ee=>{a.setQueryData(te,me=>{const B=(me??[]).filter(xe=>xe.kind!=="answer-visibility");return ee?[...B,ee]:B})},ae=ee=>{if(ee){if(ee.recurrence)d("calendar"),p(ee.recurrence.everyDays),g(ee.recurrence.startDate),S(ee.recurrence.time);else{const B=zu(ee.preset??null,ee.cronExpr);d(B.freq),h(B.hour),u(B.customCron)}const me=Jo.includes(ee.timezone);E(me?ee.timezone:"Other"),v(!me),j(me?"":ee.timezone)}else d("daily"),h(6),u(""),p(14),g(""),S("00:00"),E("UTC"),v(!1),j("");C(ee?.updatedAt??null)},I=()=>{n&&(ae(U),K(null),o(!0))},Z=()=>{ae(U),K(null)},se=async()=>{(await z.refetch()).isError?K("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):K(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},de=async(ee,me)=>{if(ee instanceof bn&&ee.code==="SCHEDULE_VERSION_CONFLICT"){await se();return}K(ee instanceof Error?ee.message:me)},J=async()=>{if(n&&!(F||Q===void 0)){q(!0),K(null);try{const ee=await z.refetch();if(ee.isError||ee.data===void 0){K("Canonry could not verify the latest schedule. Try again before saving.");return}const me=ee.data.find(Ce=>Ce.kind==="answer-visibility")??null;if((me?.updatedAt??null)!==Q)return;const xe={timezone:A?w.trim()||"UTC":N,enabled:me?.enabled??!0,providers:me?.providers??[],expectedUpdatedAt:Q};i==="calendar"?xe.recurrence={everyDays:y,startDate:x,time:f}:i==="custom"?xe.cron=m.trim():xe.preset=Qu(i,c);const Se=await Mi(t,xe);o(!1),C(void 0),T(Se),$e({title:"Schedule saved",detail:Se.recurrence?Or(Se.recurrence,Se.timezone):rr(Se.preset??null,Se.cronExpr,Se.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(ee){await de(ee,"Failed to save schedule")}finally{q(!1)}}},ie=async()=>{if(!n||!U)return;const ee=U.updatedAt;q(!0),K(null);try{const me=await z.refetch();if(me.isError||me.data===void 0){K("Canonry could not verify the latest schedule. Try again before updating it.");return}const B=me.data.find(Ce=>Ce.kind==="answer-visibility")??null;if(!B||B.updatedAt!==ee){K("This schedule changed elsewhere. Review the latest version and try again.");return}const xe={timezone:B.timezone,enabled:!B.enabled,providers:B.providers,expectedUpdatedAt:ee};B.recurrence?xe.recurrence=B.recurrence:B.preset?xe.preset=B.preset:xe.cron=B.cronExpr;const Se=await Mi(t,xe);T(Se),$e({title:Se.enabled?"Schedule resumed":"Schedule paused",detail:Se.recurrence?Or(Se.recurrence,Se.timezone):rr(Se.preset??null,Se.cronExpr,Se.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(me){await de(me,"Failed to update schedule")}finally{q(!1)}},ye=async()=>{if(!n||!U)return;const ee=U.updatedAt;X(!0),K(null);try{await Vu(t,ee),T(null),o(!1),C(void 0),$e({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(me){await de(me,"Failed to remove schedule")}finally{X(!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&&!Y&&!V&&!r&&e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:I,children:U?Ea.edit:"+ Set schedule"})]}),Y&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),G&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:G}),!Y&&V&&e.jsxs(pe,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{z.refetch()},children:"Retry"})]}),!Y&&!V&&!r&&U===null&&e.jsx(pe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?Zs:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!Y&&!V&&!r&&U!==null&&e.jsx(pe,{className:"surface-card compact-card",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[s&&e.jsx("p",{className:"text-sm text-secondary",children:Zs}),e.jsx("p",{className:"text-sm font-medium text-strong",children:U.recurrence?Or(U.recurrence,U.timezone):rr(U.preset??null,U.cronExpr,U.timezone)}),!U.recurrence&&e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:U.cronExpr})]}),U.enabled&&U.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",hh(U.nextRunAt,U.timezone)]}),U.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(U.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(ce,{tone:U.enabled?"positive":"neutral",children:U.enabled?"Active":"Paused"}),n&&e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:L,onClick:He(ie),children:U.enabled?Ea.pause:Ea.resume}),n&&e.jsx(R,{type:"button",variant:"ghost",size:"sm",disabled:D,onClick:He(ye),children:D?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[F&&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(R,{type:"button",variant:"outline",size:"sm",onClick:Z,children:"Load latest schedule"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Frequency",value:i,onChange:ee=>d(ee.target.value),children:Vy.map(ee=>e.jsx("option",{value:ee.value,children:ee.label},ee.value))})]}),i!=="calendar"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:c,disabled:i==="twice-daily"||i==="custom",onChange:ee=>h(parseInt(ee.target.value)),children:Array.from({length:24},(ee,me)=>e.jsx("option",{value:me,children:Bu(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:m,onChange:ee=>u(ee.target.value)})]}),i==="calendar"&&e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Repeat every"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Repeat every days",type:"number",min:"1",max:"3650",value:y,onChange:ee=>p(Number(ee.target.value))}),e.jsx("p",{className:"text-xs text-muted",children:"days"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Start date"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Start date",type:"date",value:x,onChange:ee=>g(ee.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Recurrence time",type:"time",value:f,onChange:ee=>S(ee.target.value)})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Timezone",value:A?"Other":N,onChange:ee=>{ee.target.value==="Other"?(v(!0),E("Other")):(v(!1),E(ee.target.value))},children:[Jo.map(ee=>e.jsx("option",{value:ee,children:ee},ee)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),A&&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:w,onChange:ee=>j(ee.target.value)})]}),G&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:G}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{o(!1),C(void 0),K(null)},children:"Cancel"}),e.jsx(R,{type:"button",size:"sm",disabled:L||z.isFetching||V||F||i==="custom"&&!m.trim()||i==="calendar"&&(!Number.isInteger(y)||y<1||y>3650||!x||!f),onClick:He(J),children:L?"Saving...":Ea.save})]})]})]})}const zy=[{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 Wy({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[o,i]=l.useState(""),[d,c]=l.useState(["citation.lost","citation.gained"]),[h,m]=l.useState(!1),[u,y]=l.useState(null),[p,x]=l.useState({}),[g,f]=l.useState(new Set),S=!oe()&&!Ms();l.useEffect(()=>{Wu(t).then(n).catch(()=>n([]))},[t]);const N=w=>{c(j=>j.includes(w)?j.filter(L=>L!==w):[...j,w])},E=async()=>{if(!(!o.trim()||d.length===0)){m(!0),y(null);try{const w=await Hu(t,{channel:"webhook",url:o.trim(),events:d});n(j=>j==="loading"?[w]:[...j,w]),i(""),c(["citation.lost","citation.gained"]),r(!1),$e({title:"Webhook added",detail:`Notifications will be sent to ${w.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(w){y(w instanceof Error?w.message:"Failed to add webhook")}finally{m(!1)}}},A=async w=>{if(!g.has(w)){f(j=>new Set(j).add(w));try{await Ju(t,w),n(j=>j==="loading"?j:j.filter(L=>L.id!==w)),$e({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${w}`,dedupeMode:"drop"})}catch(j){y(j instanceof Error?j.message:"Failed to remove webhook")}finally{f(j=>{const L=new Set(j);return L.delete(w),L})}}},v=async w=>{x(j=>({...j,[w]:{state:"testing"}}));try{const j=await Yu(t,w);x(L=>({...L,[w]:{state:j.ok?"ok":"fail",status:j.status}})),j.ok&&$e({title:"Test notification sent",detail:`Webhook returned status ${j.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${w}`,dedupeMode:"replace"})}catch{x(j=>({...j,[w]:{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"})]}),S&&s!=="loading"&&e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),y(null)},children:a?"Cancel":"+ Add webhook"})]}),S&&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:o,onChange:w=>i(w.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:zy.map(w=>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:d.includes(w.value),onChange:()=>N(w.value)}),e.jsx("span",{className:"text-sm text-neutral",children:w.label})]},w.value))})]}),u&&e.jsx("p",{className:"text-negative-400 text-sm",children:u}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),y(null)},children:"Cancel"}),e.jsx(R,{type:"button",size:"sm",disabled:h||!o.trim()||d.length===0,onClick:He(E),children:h?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(pe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(w=>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:w.urlHost,children:w.urlDisplay??w.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:w.events.map(j=>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:j.replace("."," ")},j))})}),e.jsx("td",{children:e.jsx(ce,{tone:w.enabled?"positive":"neutral",children:w.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[p[w.id]&&(()=>{const j=p[w.id],L=j.state==="testing"?"Sending…":j.state==="ok"?`Delivered${j.status?` (${j.status})`:""}`:`Failed${j.status?` (${j.status})`:""}`;return e.jsx(ce,{tone:j.state==="ok"?"positive":j.state==="fail"?"negative":"neutral",children:L})})(),S&&e.jsx(R,{variant:"ghost",size:"sm",type:"button",disabled:p[w.id]?.state==="testing",onClick:()=>{v(w.id)},children:"Test"}),S&&e.jsx(R,{variant:"ghost",size:"sm",type:"button",disabled:g.has(w.id),onClick:()=>{A(w.id)},children:g.has(w.id)?"Removing…":"Remove"})]})})]},w.id))})]}),u&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:u})]})]})}function Hy({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:o}){return oe()||Kt()?null:e.jsx(Zu,{open:t,onOpenChange:n,children:e.jsxs(em,{onCloseAutoFocus:i=>{r&&(i.preventDefault(),r())},children:[e.jsxs(tm,{children:[e.jsx(sm,{children:"Run AI sweep for the whole project?"}),e.jsxs(nm,{children:["Runs all tracked queries for ",s,". Report filters do not limit the sweep. Provider charges apply."]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsx(R,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(Je,{disabled:o,onClick:a,children:"Run project-wide sweep"})]})]})})}const Xo=2e3,Zo=3e5;function Yy(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Jy(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 Xy({projectName:t,refreshNonce:s}){const n=xs(),[a,r]=l.useState(null),[o,i]=l.useState([]),[d,c]=l.useState(null),[h,m]=l.useState([]),[u,y]=l.useState([]),[p,x]=l.useState(null),[g,f]=l.useState(""),[S,N]=l.useState(""),[E,A]=l.useState(""),[v,w]=l.useState(!0),[j,L]=l.useState(!1),[q,D]=l.useState(null),[X,G]=l.useState("performance");l.useEffect(()=>{K()},[t,s]);async function K(){w(!0),D(null);try{const T=await n.fetchQuery({...bl({client:H,path:{name:t}}),staleTime:Ft});if(r(T),T.connected){const[ae,I,Z,se]=await Promise.all([n.fetchQuery({...Rm({client:H,path:{name:t}}),staleTime:Ft}).catch(()=>null),n.fetchQuery({...Im({client:H,path:{name:t}}),staleTime:Ft}).catch(()=>[]),n.fetchQuery({...Tm({client:H,path:{name:t}}),staleTime:Ft}).catch(()=>[]),T.siteUrl?Promise.resolve([]):n.fetchQuery({...$m({client:H,path:{name:t}}),staleTime:Ft}).then(de=>de.sites).catch(()=>[])]);c(ae),m(I),y(Z),i(se)}else c(null),m([]),y([]),i([])}catch(T){D(T instanceof Error?T.message:"Failed to load Bing data")}finally{w(!1)}}async function Q(){if(S.trim()){D(null);try{const T=await Mm(t,S.trim());await Ct(n,"bing"),N(""),T.availableSites.length>0&&i(T.availableSites),await K()}catch(T){D(T instanceof Error?T.message:"Failed to connect")}}}async function C(){try{await Lm(t),await Ct(n,"bing"),r(null),i([]),c(null),m([]),y([]),x(null),A(""),D(null)}catch(T){D(T instanceof Error?T.message:"Failed to disconnect")}}async function te(){if(E)try{await qm(t,E),await Ct(n,"bing"),await K()}catch(T){D(T instanceof Error?T.message:"Failed to set site")}}async function z(){if(g.trim())try{const T=await Em(t,g.trim());await Ct(n,"bing"),x(T),m(ae=>[T,...ae])}catch(T){D(T instanceof Error?T.message:"Inspection failed")}}async function Y(T){L(!0),D(null);try{const ae=await Ei(t,{urls:[T]}),{succeeded:I,failed:Z,total:se}=ae.summary;$e({title:"Bing submission requested",detail:Z===0?`${I} URL submitted to Bing.`:`${I}/${se} submitted successfully, ${Z} failed.`,tone:Z===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${T}`,dedupeMode:"replace"})}catch(ae){const I=ae instanceof Error?ae.message:"Submission failed";D(I),$e({title:"Bing submission failed",detail:I,tone:"negative",dedupeKey:`bing:indexing:${t}:${T}`,dedupeMode:"replace"})}finally{L(!1)}}async function V(){L(!0),D(null),$e({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const T=await Ei(t,{allUnindexed:!0}),{succeeded:ae,failed:I,total:Z}=T.summary;$e({title:"Bing submissions requested",detail:I===0?`${ae}/${Z} URL${Z!==1?"s":""} submitted to Bing.`:`${ae}/${Z} submitted successfully, ${I} failed.`,tone:I===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(T){const ae=T instanceof Error?T.message:"Batch submission failed";D(ae),$e({title:"Bing submissions failed",detail:ae,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{L(!1)}}if(v)return e.jsx(pe,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return oe()?e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ce,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ce,{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:S,onChange:T=>N(T.target.value),onKeyDown:T=>{T.key==="Enter"&&Q()}}),e.jsx(Je,{size:"sm",disabled:!S.trim(),onClick:He(Q),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"})]})]}),q&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:q})]});if(!a.siteUrl)return e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{tone:"positive",children:"Connected"}),!oe()&&e.jsx(Je,{size:"sm",variant:"ghost",onClick:He(C),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?Ht(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"}),o.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:E,onChange:T=>A(T.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),o.map(T=>e.jsxs("option",{value:T.url,children:[T.url,T.verified?" (verified)":""]},T.url))]}),!oe()&&e.jsx(Je,{size:"sm",disabled:!E,onClick:He(te),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-muted",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),q&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:q})]});const U=[{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"}],F=U.find(T=>T.key===X)??U[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{tone:"positive",children:"Connected"}),!oe()&&e.jsx(Je,{size:"sm",variant:"ghost",onClick:He(C),children:"Disconnect"})]})]}),q&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:q}),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?Ht(a.updatedAt):"—"})]})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:F.eyebrow}),e.jsx("h3",{children:F.title})]}),e.jsx("p",{className:"text-xs text-muted",children:d?.lastInspectedAt?`Last inspected ${Ht(d.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:U.map(T=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${X===T.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>G(T.key),children:T.label},T.key))}),X==="coverage"&&d&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Na,{label:"Indexed",value:d.summary.indexed,tone:"positive"}),e.jsx(Na,{label:"Not in index",value:d.summary.notIndexed+(d.summary.unknown??0),tone:"negative"}),e.jsx(Na,{label:"Status unknown",value:d.summary.unknown??0,tone:"neutral"}),e.jsx(Na,{label:"Coverage",value:`${d.summary.percentage}%`,tone:"neutral"})]}),d.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 (",d.notIndexed.length,")"]}),!oe()&&e.jsx(Je,{size:"sm",variant:"ghost",disabled:j,onClick:He(V),children:j?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!oe()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:d.notIndexed.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.httpCode??"—"}),!oe()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:j,onClick:()=>{Y(T.url)},children:"Submit"})})]},T.id))})]})})]}),(d.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 (",(d.unknown??[]).length,")"]}),!oe()&&e.jsx(Je,{size:"sm",variant:"ghost",disabled:j,onClick:He(V),children:j?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!oe()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(d.unknown??[]).map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.lastCrawledDate?Ht(T.lastCrawledDate):"—"}),!oe()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:j,onClick:()=>{Y(T.url)},children:"Submit"})})]},T.id))})]})})]}),d.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",d.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:d.indexed.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.lastCrawledDate?Ht(T.lastCrawledDate):"—"})]},T.id))})]})})]})]}),X==="coverage"&&!d&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),X==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!oe()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:g,onChange:T=>f(T.target.value),onKeyDown:T=>{T.key==="Enter"&&z()}}),e.jsx(Je,{size:"sm",disabled:!g.trim(),onClick:He(z),children:"Inspect"})]}),p&&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:p.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:p.inIndex?"text-positive-400":"text-negative-400",children:p.inIndex?"Yes":"No"})," · ","HTTP: ",p.httpCode??"—"," · ","Crawled: ",p.lastCrawledDate??"—"]})]}),h.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:h.map(T=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(ce,{tone:T.inIndex?"positive":"negative",children:T.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:T.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Ht(T.inspectedAt)})]},T.id))})]})})]}),X==="performance"&&e.jsx("div",{className:"mt-4",children:u.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:ja[fn.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:ja[fn.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:ja[fn.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:ja[fn.Position]})]})}),e.jsx("tbody",{children:u.map((T,ae)=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:T.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:T.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:T.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(T.ctr)?T.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:T.averagePosition.toFixed(1)})]},ae))})]})})})]})]})}function Zy({projectName:t}){const s=xs(),[n,a]=l.useState("google"),[r,o]=l.useState(!0),[i,d]=l.useState("idle"),[c,h]=l.useState(null),m=l.useRef(null),[u,y]=l.useState(null),[p,x]=l.useState(null),[g,f]=l.useState(0);async function S(E=!1){E||o(!0),h(null);try{const[A,v]=await Promise.all([s.fetchQuery({...ri({client:H,path:{name:t}}),staleTime:Ft}).catch(()=>[]),s.fetchQuery({...bl({client:H,path:{name:t}}),staleTime:Ft}).catch(()=>null)]),w=A.find(j=>j.connectionType==="gsc")??null;y(w),x(v)}catch(A){h(A instanceof Error?A.message:"Failed to load search engine connections")}finally{o(!1)}}async function N(){if(i!=="idle")return;m.current?.abort();const E=new AbortController;m.current=E;const A=E.signal;d("syncing"),h(null),$e({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const v=[],w=[];try{async function j(){if(!u)return;const D=await Am(t);if(!D?.id)return;const X=Date.now()+Zo;for(;Date.now()<X;){if(A.aborted||(await new Promise(K=>setTimeout(K,Xo)),A.aborted))return;const G=await Kr(D.id).catch(()=>null);if(!G)break;if(["completed","failed","cancelled"].includes(G.status)){G.status!=="completed"&&v.push(`Google sync ${G.status}`);return}}w.push("Google sync is still running — search data will appear shortly")}async function L(){if(!p?.connected)return;const D=await Pm(t).catch(()=>null);if(!D?.id){v.push("Bing sweep could not be started");return}const X=Date.now()+Zo;for(;Date.now()<X;){if(A.aborted||(await new Promise(K=>setTimeout(K,Xo)),A.aborted))return;const G=await Kr(D.id).catch(()=>null);if(!G)break;if(["completed","failed","cancelled","partial"].includes(G.status)){G.status==="failed"?v.push("Bing sweep failed"):G.status==="partial"&&w.push("Bing sweep finished with some pages unverified");return}}w.push("Bing sweep is still running — coverage will update shortly")}const q=await Promise.allSettled([j(),L()]);for(const D of q)D.status==="rejected"&&v.push(D.reason instanceof Error?D.reason.message:"Sync failed");if(await Promise.all([Ct(s,"gsc"),Ct(s,"bing")]),A.aborted)return;if(d("reloading"),await S(!0),f(D=>D+1),v.length>0){const D=`Partial refresh: ${[...v,...w].join("; ")}`;h(D),$e({title:"Search coverage partially refreshed",detail:D,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else w.length>0?$e({title:"Search coverage refresh incomplete",detail:w.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):$e({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(j){if(!A.aborted){const L=j instanceof Error?j.message:"Refresh failed";h(L),$e({title:"Search coverage refresh failed",detail:L,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{A.aborted||d("idle")}}return l.useEffect(()=>(S(),()=>{m.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(([E,A])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===E,className:`project-subnav-link ${n===E?"project-subnav-link-active":""}`,onClick:()=>a(E),children:A},E))}),!oe()&&e.jsxs(Je,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{N()},children:[e.jsx(ra,{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"]})]}),c&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:c}),n==="google"&&e.jsx(vx,{projectName:t,refreshNonce:g}),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(Xy,{projectName:t,refreshNonce:g})]})]})}function Ya({label:t,summary:s,displayValue:n,tooltip:a}){const r=s.value.trim()!==""&&Number.isFinite(Number(s.value)),o=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(Ve,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${tl[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[s.value,r?e.jsx("span",{className:"text-faint",children:"%"}):null]})}),e.jsx("div",{className:"aeo-hero-row-bar","aria-hidden":"true",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.tone}`,style:{width:`${o}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function eb({model:t,sweepRunning:s,hasVisibilityBaseline:n}){const a=t.citationMovement,r=t.mentionMovement,o=t.movementComparison,i=t.recentRuns.find(p=>p.kind===Xs["answer-visibility"]&&(p.status===_a.completed||p.status===_a.partial)),d=p=>p.tone==="positive"?"improved":p.tone==="negative"?"declined":p.gained>0||p.lost>0?"mixed":"steady",c=d(r),h=d(a),m=(()=>{if(s)return"A fresh sweep is running now";if(!n)return"No AI Visibility baseline yet";if(!o.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(o.querySetChanged)return"Tracking scope changed since the previous sweep";if(c===h)return c==="steady"?"Answer mentions and citation coverage held steady":c==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${c}`;const p=c==="mixed"?"Answer mention movement was mixed":c==="steady"?"Answer mentions held steady":`Answer mentions ${c}`,x=h==="mixed"?"citation movement was mixed":h==="steady"?"citation coverage held steady":`citation coverage ${h}`;return`${p}; ${x}`})(),u=[o.addedQueryCount>0&&`${o.addedQueryCount} ${o.addedQueryCount===1?"query":"queries"} added`,o.removedQueryCount>0&&`${o.removedQueryCount} ${o.removedQueryCount===1?"query":"queries"} removed`].filter(Boolean).join(", "),y=`${o.comparableQueryCount} comparable ${o.comparableQueryCount===1?"query":"queries"}`;return e.jsxs("section",{className:"overview-brief","aria-labelledby":"overview-brief-title",children:[e.jsxs("div",{className:"overview-brief-head",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft",children:["Visibility",e.jsx(Ve,{text:"Each sweep records two independent signals: answer mentions (your brand named in the answer text) and source citations (your domain in the engine's source list). They move separately."})]}),e.jsx("h2",{id:"overview-brief-title",className:"overview-brief-title",children:m})]}),i?e.jsxs("p",{className:"overview-brief-updated",children:["Updated ",i.startedAt]}):null]}),n?e.jsxs("div",{className:"overview-brief-grid",children:[e.jsxs("div",{className:"overview-brief-panel overview-brief-coverage",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage now"}),e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Ya,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(Ya,{label:"Cited",summary:t.visibilitySummary})]}),t.mentionSummary.providerCoverage&&e.jsxs("p",{className:"overview-brief-note",children:["Partial sweep: ",t.mentionSummary.providerCoverage]})]}),e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Since last sweep"}),o.hasPreviousRun?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"overview-signal-change-list",children:[e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Mentioned"}),r.gained===0&&r.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[r.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",r.gained]}),r.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",r.lost]})]})]}),e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Cited"}),a.gained===0&&a.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[a.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",a.gained]}),a.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",a.lost]})]})]})]}),e.jsx("p",{className:`overview-brief-panel-copy ${o.querySetChanged?"text-caution-400/80":""}`,children:o.querySetChanged?`${u||"Query set changed"} · ${y}.`:`${y}.`})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:"No comparison yet"}),e.jsx("p",{className:"overview-brief-panel-copy",children:Kt()?Zs:"Run another sweep to measure mention and citation movement."})]})]})]}):e.jsx("div",{className:"overview-brief-grid",children:e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage signals"}),e.jsxs("dl",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm font-medium text-heading",children:"Mentioned"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:"Your brand or domain appears in the answer text."})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm font-medium text-heading",children:"Cited"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:"Your domain appears in the engine's source list."})]})]}),e.jsx("p",{className:"mt-4 border-t border-subtle pt-4 text-sm font-medium text-strong",children:s?"Your first sweep is running. Results will appear when it completes.":Kt()?Zs:"Complete your first AI Visibility sweep to measure both signals."})]})})]})}function Fr({id:t,eyebrow:s,title:n,meta:a,defaultOpen:r=!1,children:o}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:r||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"eyebrow eyebrow-soft",children:s}),e.jsx("span",{className:"overview-disclosure-title",children:n})]}),e.jsxs("span",{className:"overview-disclosure-meta",children:[a&&e.jsx("span",{children:a}),e.jsx(vn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:o})]})}function tb({insights:t,suggestedQueries:s,onManageQueries:n}){const{openEvidence:a}=nl(),r=n?s.rows:[];if(t.length===0&&r.length===0)return null;const o=y=>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:y.title}),y.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:y.detail}):null]}),e.jsx(ce,{tone:y.tone,children:y.actionLabel})]}),y.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 · ",y.affectedPhrases.length," affected ",y.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:y.affectedPhrases.map((p,x)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(_r,{state:p.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:p.query}),p.provider?e.jsx(En,{provider:p.provider}):null,!oe()&&p.evidenceId?e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(p.evidenceId)},children:"View evidence"}):null]},p.evidenceId||`${y.id}-${x}`))})]}):null]},y.id),i=y=>e.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:y.query}),e.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:y.reason})]}),n?e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},y.query),d=t.slice(0,1),c=r.slice(0,1),h=t.slice(1),m=r.slice(1),u=h.length+m.length;return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[d.map(o),c.map(i)]}),u>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:[u," more ",u===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[h.map(o),m.map(i)]})]}):null]})}function yb(t){const{projectName:s}=gc({from:"/projects/$projectName"}),a=xl()?.dashboard.projects.find(w=>w.project.name===s||w.project.id===s)?.project.name??null,r=Te({...Xu({client:H}),enabled:!a}),o=a??r.data?.find(w=>w.name===s||w.id===s)?.name??null,i=pl(),d=gl(t.tab,fl(i)),[c,h]=l.useState(null),m=o!==null&&c===o,u=l.useCallback(()=>{o&&h(o)},[o]),{commandCenter:y,isLoading:p,overviewLoading:x,overviewError:g,isError:f,latestVisibilityRevision:S,competitorHistoryRevision:N,refetch:E}=yl(o,{overview:d==="overview"&&m}),A=!a&&r.isLoading||p;return!o&&!a&&r.isSuccess&&!p?e.jsx("div",{className:"page-container",children:e.jsxs(pe,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(R,{asChild:!0,children:e.jsx(As,{to:"/",children:"Return to overview"})})]})}):!y&&(f||r.isError)?e.jsxs("div",{className:"page-container",role:"alert",children:[e.jsx("p",{children:"Could not load this project."}),e.jsx(R,{type:"button",variant:"outline",onClick:()=>{Promise.all([r.refetch(),E()])},children:"Retry"})]}):!y||A?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(w=>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"})]},w))}),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(w=>e.jsx("div",{className:"skeleton-text-sm w-full"},w))})]})]}):e.jsx(ab,{model:y,refetch:E,latestVisibilityRevision:S,competitorHistoryRevision:N,overviewLoading:x,overviewError:g,overviewRequested:m,onRequestOverview:u,...t})}function sb({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=l.useRef(null),o=l.useRef(null),[i,d]=l.useState(null);l.useLayoutEffect(()=>{const m=r.current,u=o.current;if(!m||!u)return;const y=()=>{const x=m.getBoundingClientRect().width;if(!x)return;const g=Number.parseFloat(getComputedStyle(m).columnGap)||0,f=new Map([...u.querySelectorAll("[data-project-tab]")].map(w=>[w.dataset.projectTab,w.getBoundingClientRect().width])),S=w=>f.get(w)??0,N=w=>w.reduce((j,L)=>j+S(L),0)+Math.max(0,w.length-1)*g,E=[...t.map(w=>w.key),...s.length?["more"]:[],...n?[n.key]:[]];let A=t.map(w=>w.key),v=!1;if(N(E)>x){const w=t.find(q=>q.key===a),j=w?[w.key]:[];v=!!(n&&N([...j,"more",n.key])>x);const L=["more",...n&&!v?[n.key]:[]];for(const q of t)if(q.key!==w?.key){if(N([...j,q.key,...L])>x)break;j.push(q.key)}A=t.filter(q=>j.includes(q.key)).map(q=>q.key)}d(w=>w?.settingsInMore===v&&w.visibleKeys.join()===A.join()?w:{visibleKeys:A,settingsInMore:v})};if(y(),typeof ResizeObserver>"u")return window.addEventListener("resize",y),()=>window.removeEventListener("resize",y);const p=new ResizeObserver(y);return p.observe(m),p.observe(u),()=>p.disconnect()},[t,s,n,a]);const c=i?t.filter(m=>i.visibleKeys.includes(m.key)):t,h=[...t.filter(m=>!c.includes(m)),...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:o,children:[[...t,...n?[n]:[]].map(m=>e.jsx("span",{className:"project-subnav-link","data-project-tab":m.key,children:m.label},m.key)),e.jsxs("span",{className:"project-subnav-link project-subnav-more-trigger","data-project-tab":"more",children:["More",e.jsx(vn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),c.map(m=>e.jsx(As,{to:m.href,search:u=>({...u,onboarding:void 0}),className:`project-subnav-link ${m.key===a?"project-subnav-link-active project-subnav-current":""}`,"aria-current":m.key===a?"page":void 0,children:e.jsx("span",{className:"project-subnav-label",children:m.label})},m.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(nb,{items:h,activeTab:a}),n&&!i?.settingsInMore&&e.jsx(As,{to:n.href,search:m=>({...m,onboarding:void 0}),className:`project-subnav-link ${a==="settings"?"project-subnav-link-active":""}`,"aria-current":a==="settings"?"page":void 0,children:n.label})]})]})}function nb({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null),o=l.useRef(null),i=l.useRef("first"),d=l.useId(),c=t.map(m=>m.key).join();if(l.useEffect(()=>{a(!1)},[c]),l.useEffect(()=>{if(!n)return;const m=r.current?.querySelectorAll('[role="menuitem"]');(i.current==="last"?m?.[m.length-1]:m?.[0])?.focus()},[n]),l.useEffect(()=>{if(!n)return;const m=y=>{r.current&&!r.current.contains(y.target)&&a(!1)},u=y=>{y.key==="Escape"&&(a(!1),o.current?.focus())};return document.addEventListener("pointerdown",m),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",m),document.removeEventListener("keydown",u)}},[n]),t.length===0)return null;const h=t.some(m=>m.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",ref:o,className:`project-subnav-link project-subnav-more-trigger ${h?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?d:void 0,onClick:()=>{i.current="first",a(m=>!m)},onKeyDown:m=>{m.key!=="ArrowDown"&&m.key!=="ArrowUp"||(m.preventDefault(),i.current=m.key==="ArrowUp"?"last":"first",a(!0))},children:["More",e.jsx(vn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:d,"aria-label":"More project sections",onKeyDown:m=>{const u=[...m.currentTarget.querySelectorAll('[role="menuitem"]')],y=u.indexOf(document.activeElement),p=m.key==="Home"?0:m.key==="End"?u.length-1:m.key==="ArrowDown"?(y+1)%u.length:m.key==="ArrowUp"?(y-1+u.length)%u.length:null;p!==null&&(m.preventDefault(),u[p]?.focus())},onBlur:m=>{r.current?.contains(m.relatedTarget)||a(!1)},children:t.map(m=>e.jsx(As,{to:m.href,search:u=>({...u,onboarding:void 0}),role:"menuitem",tabIndex:-1,className:`project-subnav-menu-item ${m.key===s?"project-subnav-menu-item-active":""}`,"aria-current":m.key===s?"page":void 0,onClick:()=>a(!1),children:m.label},m.key))}):null]})}function ab({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r,overviewLoading:o,overviewError:i,overviewRequested:d,onRequestOverview:c}){const h=fc(),m=xs(),{canWrite:u}=wn(),[y,p]=l.useState(null),x=l.useRef(null),g=xl(),f=s.project.name,S=g?.dashboard.projects.some($=>$.project.name===f)??!1,N=Te({...am({client:H,path:{name:f}}),enabled:!oe()&&!!f&&(u||t==="portfolio"||t==="overview"||t==="settings"),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),E=g?g.dashboard.settings.providerStatuses.filter($=>$.state==="ready").map($=>Li($.name)):void 0,A=N.data?.answerVisibilityProviderReady,v=E,w=s.project.providers.map(Li),j=v?.some($=>w.length===0||w.includes($))===!0,L=w.length===0||w.includes(rm),q=Te({...im({client:H}),enabled:!oe()&&u&&A===void 0&&L&&!j,staleTime:6e4,retry:!1}),D=L?q.isSuccess?typeof q.data.browserVersion=="string":q.isError?!1:void 0:!1,X=A??om({projectProviders:w,configuredApiProviders:v,cdpConfigured:D}),G=l.useMemo(()=>fl(pl()),[]),K=gl(t,G),Q=l.useMemo(()=>s.competitors.map($=>$.domain),[s.competitors]),[C,te]=l.useState(!1),[z,Y]=l.useState(!1),V=lm(),U=yc({strict:!1}),F=Sh(U),T=l.useCallback($=>{h({to:".",search:fe=>Ch(fe,$)})},[h]),ae=U.manageQueries===!0,I=l.useCallback(()=>{h({to:".",replace:!0,search:$=>({...$,siteHealthRunId:void 0})})},[h]),[Z,se]=l.useState(ae),[de,J]=l.useState(""),[ie,ye]=l.useState(!1),[ee,me]=l.useState(null),[B,xe]=l.useState("30d"),[Se,Ce]=l.useState(void 0),[tt,Qe]=l.useState(!1),[Ge,st]=l.useState(null),[qe,O]=l.useState(!1),Le=Ml(U),[P,ge]=l.useState(void 0),[Oe,We]=l.useState(void 0),_e=l.useCallback($=>{ge($.search),$.sort&&We($.sort),h({to:".",search:fe=>({...fe,...Nh($)}),replace:!1})},[h]),[he,xt]=l.useState(!1),Ue=s?.project.displayName||s?.project.name||f,Fe=cm(),kt=Te({...qi({client:H,path:{name:f}}),enabled:K==="portfolio"&&!!f,staleTime:0,refetchOnMount:"always"}),Xe=Te({...dm({client:H,path:{name:f}}),enabled:!oe()&&!!f&&(u||K==="portfolio"||K==="overview"||K==="settings"),staleTime:0,refetchOnMount:"always"}),ke=Xe.data?.active??null,ot=Xe.data!==void 0,ft=new Set(ke&&Number(ke.plan.schemaVersion)===2?ke.plan.groups?.map($=>$.stableKey)??[]:[]),De={...Le.scope==="group"&&!!Le.groupKey&&ot&&!ft.has(Le.groupKey)?{scope:"all",queryClass:Le.queryClass}:Le,...P?{search:P}:{}},k=ke===null?null:Number(ke.plan.schemaVersion),Ie=ke?.revision??0,we=ot?`${f}:${Ie}`:null,ze=l.useRef(null);l.useEffect(()=>{const $=ze.current;we!==null&&(ze.current=we),jh($,we)&&(_e({scope:"all",queryClass:"all"}),xt(!1))},[we,_e]);const yt={client:H,path:{name:f},query:{scope:De.scope,...De.groupKey?{groupKey:De.groupKey}:{},queryClass:De.queryClass,...De.search?{search:De.search}:{},...Oe?{sort:Oe}:{},limit:50}},nt=el({...um(yt),enabled:!1,initialPageParam:yt,getNextPageParam:($,fe)=>{if(!$.properties.nextCursor)return;const Me=fe[0]?.measurement.displayedRunId;return{path:yt.path,query:{...yt.query,cursor:$.properties.nextCursor,...Me?{runId:Me}:{}}}},placeholderData:ai,staleTime:0,refetchOnMount:"always"}),Rt=nt.data?.pages[0]?.measurement.displayedRunId,Ye=Te({...mm({client:H,path:{name:f},query:{revision:Ie,...Rt?{runId:Rt}:{}}}),enabled:K==="overview"&&!!f&&ke!==null&&k===1,staleTime:0,refetchOnMount:"always"}),ne=Xe.data!==void 0,Ee=kt.data!==void 0,Pe=Xe.isPending&&!ne,Ae=Xe.isError&&!ne,Yt=kt.isPending&&!Ee,Jt=kt.isError&&!Ee,_t=Ye.data!==void 0,bt=my({activePlanSchemaVersion:N.data?.activeSchemaVersion??k,hasDraft:N.data?.draft!==null&&N.data?.draft!==void 0}),lt=bt.surface==="simple-overview",Ut=N.data===void 0&&Xe.data===void 0&&(Xe.isLoading||N.isLoading);l.useEffect(()=>{K==="overview"&<&&!Ut&&c()},[Ut,lt,c,K]);const as=K==="overview"&<&&!Ut,Bt=yl(f,{evidence:as}),Vt=Bt.commandCenter?.visibilityEvidence??s.visibilityEvidence,mt=u&&!oe()&&!Kt()&&K!=="overview",rs=Te({...qi({client:H,path:{name:f}}),enabled:mt,staleTime:ii,refetchOnWindowFocus:"always"}),Ze=k===2&&F.measurementScope==="group"?F.measurementScopeKey:void 0,Et=k===2&&F.measurementScope==="project",Qt=l.useMemo(()=>{if(!(ke?.plan.schemaVersion!==2||!Ze))return ke.plan.groups.find($=>$.stableKey===Ze)},[ke,Ze]),fs={client:H,path:{name:f},query:{window:B,queryClass:k===2&&F.queryClass!=="unknown"?F.queryClass:"non-brand",...Ze?{groupKey:Ze}:{},...Et?{scope:"all-markets"}:{}}},ps=K==="overview"&&!F.marketKey&&!!f&&(lt||ot)&&!Ut&&(lt||(F.measurementScope==="project"||k===2&&F.measurementScope==="group")&&F.queryClass!=="unknown"&&(k===2||F.queryClass!=="branded")),[zt,ys]=l.useState(null);l.useEffect(()=>{ps||ys(null)},[ps]),l.useEffect(()=>{ys(null)},[f]);const Xt=zt===f,Nt=ps&&Xt,Zt=Te({...hm(fs),enabled:Nt,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});xm(f,JSON.stringify([r,s.competitors.map($=>$.domain).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,Ie,N.data?.draft?.etag??null]),Nt);const vt=Zt.isError?Zt.data===void 0?"Could not load competitor history. Your pinned competitors remain available.":"Could not refresh competitor history. Showing the last available data.":void 0,es=l.useMemo(()=>s.competitors.map($=>({domain:$.domain,label:$.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:$.citationCount,answeredResults:$.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),bs=l.useMemo(()=>{if(ke?.plan.schemaVersion!==2)return es;const $=Ze?Qt?.competitors??[]:ke.plan.groups.flatMap(Me=>Me.competitors),fe=new Map;for(const Me of $){const ss=Me.domain.trim().toLowerCase();!ss||fe.has(ss)||fe.set(ss,{domain:Me.domain,label:Me.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const Me of es){const ss=Me.domain.trim().toLowerCase();!ss||fe.has(ss)||fe.set(ss,Me)}return[...fe.values()]},[ke,Ze,es,Qt]),_=k===2?bs:es,re=Pt({...pm({client:H}),meta:{skipGlobalErrorToast:!0}}),je=N.data!==void 0?"success":N.isError?"error":"pending",le=l.useMemo(()=>{const $=nt.data?.pages;return $?!ah($):!1},[nt.data]),Ne=l.useMemo(()=>{const $=nt.data?.pages,fe=$?.[0],Me=$?.at(-1);if(!(!fe||!Me||le))return{...fe,properties:{...fe.properties,items:$.flatMap(ss=>ss.properties.items),nextCursor:Me.properties.nextCursor}}},[le,nt.data]),Ke=l.useMemo(()=>{if(ke)return ke.plan.schemaVersion===1?Ye.data?vy(ke,Ye.data):void 0:Ne?rh({overview:Ne,activePlan:ke,sort:Oe,report:Ye.data,reportState:Ne.measurement.displayedRunId===void 0?"ready":Ye.isFetching&&Ye.data===void 0?"loading":Ye.isError&&Ye.data===void 0?"error":Ye.data?"ready":"loading"}):void 0},[ke,Ye.data,Ye.isError,Ye.isFetching,Ne]),ht=k===2?le?"error":nt.isPending?"loading":nt.isError&&Ke===void 0?"error":"ready":Ye.isPending&&!_t?"loading":Ye.isError&&!_t?"error":"ready",ct=(s?.recentRuns??[]).some($=>$.kind===Xs["answer-visibility"]&&($.status===_a.running||$.status===_a.queued)),vs=s.queryCounts.total>0,M=l.useMemo(()=>(s?.project.locations??[]).map($=>$.label),[s?.project.locations]),be=l.useMemo(()=>new Set(Vt.map($=>$.location??"")),[Vt]),rt=be.has(""),wt=l.useMemo(()=>[...new Set(Vt.map($=>$.query))].sort(($,fe)=>$.localeCompare(fe)),[Vt]),pt=wt.length>0||s.queryCounts.total>0||(rs.data?.length??0)>0||ke!==null,Ds=u&&!pt&&(Xe.data===void 0&&Xe.isPending||rs.isLoading||as&&Bt.evidenceLoading),rn=u&&(N.isError&&!N.isFetching||mt&&rs.isError&&!rs.isFetching),Wt=u&&!rn&&(Ds||X===void 0||N.isFetching),Fn=!Wt&&!rn&&pt&&X===!0,It=u&&!Wt&&!Fn,on=Te({...hl({client:H,path:{name:f}}),enabled:!oe()&&!Kt()&&!!f,retry:!1}).data?.find($=>$.kind===Xs["answer-visibility"]),Kn=on?.enabled&&on.nextRunAt?`Next AI sweep ${new Date(on.nextRunAt).toLocaleString()}`:null,Za=l.useMemo(()=>{const $=[...be].filter(Boolean);return $.length>1?$:M},[be,M]);l.useEffect(()=>{if(!as||Se===void 0||Se===""||!f){st(null),O(!1);return}O(!0),gm(f,Se,20).then($=>{st($),O(!1)}).catch(()=>{st(null),O(!1)})},[Se,f,as]);const Sn=l.useMemo(()=>{if(!Ge)return null;const $=new Map;for(const fe of Ge){for(const[Me,ss]of Object.entries(fe.providerRuns??{}))$.set(`${fe.query}::${Me}`,ss.map(js=>({runId:js.runId,citationState:js.citationState,createdAt:js.createdAt,answerMentioned:js.answerMentioned,visibilityState:js.visibilityState,visibilityTransition:js.visibilityTransition,mentionState:js.mentionState,mentionTransition:js.mentionTransition})));(!fe.providerRuns||Object.keys(fe.providerRuns).length===0)&&$.set(`${fe.query}::`,fe.runs.map(Me=>({runId:Me.runId,citationState:Me.citationState,createdAt:Me.createdAt,answerMentioned:Me.answerMentioned,visibilityState:Me.visibilityState,visibilityTransition:Me.visibilityTransition,mentionState:Me.mentionState,mentionTransition:Me.mentionTransition})))}return $},[Ge]),Gn=l.useMemo(()=>{const $=Se!==void 0?Vt.filter(fe=>Se===""?!fe.location:fe.location===Se):Vt;return Sn?$.map(fe=>{const Me=Sn.get(`${fe.query}::${fe.provider}`)??Sn.get(`${fe.query}::`);return Me?{...fe,runHistory:Me}:fe}):$},[Vt,Se,Sn]);async function _n(){if(!(y!==f||!u||oe()||Kt()||Fe.isPending||ct||!Fn))try{await Fe.mutateAsync({projectName:f,projectLabel:Ue,sourceAction:"project-run"}),p(null),n()}catch{}}function ma(){h({to:"/setup",search:{experience:"legacy",setupProject:f}})}async function ln(){Y(!0);try{await km(f),$e({title:"Project deleted",detail:`${Ue} was removed.`,tone:"positive",dedupeKey:`project:delete:${f}`,dedupeMode:"drop"}),h({to:"/"}),n()}catch($){console.error("Failed to delete project:",$)}finally{Y(!1)}}async function Un(){const $=de.split(`
|
|
7
|
-
`).map(fe=>fe.trim()).filter(Boolean);if($.length!==0){ye(!0);try{await bm(f,$),n(),J("")}finally{ye(!1)}}}async function Cn($){me($);try{await ym(f,[$]),n()}catch(fe){$e({title:"Could not remove query",detail:fe instanceof Error?fe.message:`Failed to remove "${$}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{me(null)}}async function Bn($){const fe=$.trim();if(!fe)return!1;try{return await vm(f,[fe]),n(),!0}catch(Me){return $e({title:"Could not add competitor",detail:Me instanceof Error?Me.message:`Failed to add ${fe}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function ha($){const fe=s.competitors.find(Me=>Me.domain===$);if(!fe)return $e({title:"Could not remove competitor",detail:`Could not find ${$} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await jm(f,fe.id),n(),!0}catch(Me){return $e({title:"Could not remove competitor",detail:Me instanceof Error?Me.message:`Failed to remove ${fe.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function xa($){const fe=$.trim();if(!fe||!Ze||k!==2||!u||oe()||re.isPending)return!1;try{const Me=await re.mutateAsync({client:H,path:{name:f},headers:{"Idempotency-Key":Yy()},body:{expectedActiveRevision:Ie,groupKey:Ze,domain:fe}});return Promise.allSettled([N.refetch()]),$e({title:Me.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:${Ze}:${fe}`,dedupeMode:"replace"}),!0}catch(Me){return $e({title:"Could not add market competitor",detail:Me instanceof Error?Me.message:`Failed to add ${fe} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function kn($,fe){const Me=await Nm($,fe);return await m.invalidateQueries({queryKey:wm({client:H})}),m.setQueryData(Sm({client:H,path:{name:$}}),Me),Jy(m,Me),fe.providers!==void 0&&await m.invalidateQueries({queryKey:Cm({client:H,path:{name:$}}),exact:!0}),Me}const ts=`/projects/${encodeURIComponent(s.project.name)}`,Fs=[{key:"overview",label:"AI Visibility",href:ts},{key:"search-console",label:"Search Engines",href:`${ts}/search-console`},{key:"activity",label:"Activity",href:`${ts}/activity`},{key:"technical-aeo",label:"Site Health",href:`${ts}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${ts}/conversions`},{key:"local",label:"Local Presence",href:`${ts}/local`},{key:"queries",label:"Queries",href:`${ts}/queries`},{key:"backlinks",label:"Backlinks",href:`${ts}/backlinks`}],er=[{key:"report",label:"Report",href:`${ts}/report`},{key:"history",label:"Change History",href:`${ts}/history`}],pa=Fs.filter($=>ir($.key,G)),ga=er.filter($=>ir($.key,G)),fa=ir("settings",G)?{key:"settings",label:"Settings",href:`${ts}/settings`}:null;function ya($){return lt?$:e.jsx(kp,{projectName:f,selection:F,showUnmeasuredFallback:!ke&&!vs&&F.measurementScope==="project"&&F.queryClass==="all"&&!F.provider&&!F.model&&!F.location&&!F.from&&!F.to&&!F.revision&&!F.measurementRunId&&!F.queryKey&&!F.marketKey,onSelectionChange:T,onManageQueries:oe()?void 0:()=>{h({to:"/projects/$projectName/queries",params:{projectName:f},search:fe=>({...fe,queryWorkspace:"tracked",trackingQueryId:void 0,measurementMarketKey:void 0})})},fallback:$},`${f}:${JSON.stringify({...F,queryKey:void 0,answer:void 0})}`)}return e.jsxs("div",{className:"page-container",children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain," · ",s.contextLabel]}),!oe()&&e.jsxs("div",{className:"tag-row",children:[e.jsx("span",{className:"tag",children:s.project.country}),e.jsx("span",{className:"tag",children:s.project.language.toUpperCase()}),s.project.tags.map($=>e.jsx("span",{className:"tag",children:$},$))]})]}),e.jsxs("div",{className:Kt()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:[K==="overview"&&(lt||F.from||F.to)?e.jsx("p",{className:"text-sm text-muted",children:lt?s.dateRangeLabel:`${F.from?.slice(0,10)??"First measurement"} to ${F.to?.slice(0,10)??"Latest measurement"}`}):null,!oe()&&(Kt()?e.jsx(fm,{projectName:f,running:ct,portfolio:!lt}):e.jsxs("div",{className:"flex items-center gap-3",children:[Kn?e.jsx("p",{className:"text-sm text-secondary",children:Kn}):null,e.jsx(Je,{type:"button",variant:"outline",disabled:Fe.isPending||ct||Wt,onClick:rn?()=>{Promise.all([N.refetch(),...mt?[rs.refetch()]:[]])}:It?ma:$=>{x.current=$.currentTarget,p(f)},children:Fe.isPending?"Starting…":ct?"AI sweep running…":Wt?"Checking AI readiness…":rn?"Retry AI readiness":It?"Set up AI Visibility":"Run AI sweep"})]}))]})]}),!oe()&&!Kt()&&e.jsx(Hy,{open:y===f,projectLabel:Ue,onOpenChange:$=>p($?f:null),onConfirm:He(_n),onClosed:()=>x.current?.focus(),disabled:Fe.isPending||ct||!Fn}),e.jsx(sb,{items:pa,overflowItems:ga,settingsItem:fa,activeTab:K}),K==="portfolio"&&!oe()?e.jsx(zf,{projectName:f,canEdit:u,queries:kt.data??[],isQueryLoading:Yt,isQueryError:Jt,onRetryQueries:()=>{kt.refetch()},publishedPlan:ke,onCreateQueries:async $=>(await V.mutateAsync({projectName:f,queries:[...$]}),(await kt.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{h({to:"/projects/$projectName",params:{projectName:f},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([N.refetch(),Xe.refetch()]).finally(()=>{h({to:"/projects/$projectName",params:{projectName:f}})})}},f):K==="overview"?Ut||lt&&!S&&(!d||o)?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"})]}):lt&&i?e.jsxs("div",{role:"alert",className:"page-section-divider",children:[e.jsx("p",{children:"Could not load AI visibility."}),e.jsx(R,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[Ae?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(R,{type:"button",size:"sm",variant:"outline",onClick:()=>{Xe.refetch()},children:"Retry setup check"})]}):null,ya(e.jsx(hy,{mode:bt,canEdit:u&&!oe()&&!Pe&&!Ae,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(Fp,{projectName:s.project.name,competitorDomains:Q,analyticsRevision:a})}),e.jsx(eb,{model:s,sweepRunning:ct,hasVisibilityBaseline:vs}),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:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"}),e.jsx("p",{className:"supporting-copy",children:"Latest measured results against pinned competitors."})]})}),vs?e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsx(Ih,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:Q},s.project.name),e.jsx("div",{className:"competitive-gaps",children:e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Ya,{label:"Mention gaps",summary:s.mentionGaps,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.mentionGaps.value}),e.jsxs("span",{className:"text-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was mentioned in the answer but your brand was not."}),e.jsx(Ya,{label:"Citation gaps",summary:s.gapQueries,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.gapQueries.value}),e.jsxs("span",{className:"text-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was cited as a source but you were not."})]})})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Competitive mention and citation gaps appear after the first AI Visibility sweep."})]}),e.jsxs(Fr,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[!oe()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(Je,{type:"button",variant:"outline",size:"sm",onClick:()=>se(!Z),children:Z?"Done":"Manage queries"})}),!oe()&&Z&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[wt.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:wt.map($=>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:$,children:$}),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 ${$}`,title:`Stop tracking "${$}"`,disabled:ee!==null,onClick:()=>{Cn($)},children:ee===$?"Removing…":"Remove"})]},$))}):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:de,onChange:$=>J($.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[de.split(`
|
|
8
|
-
`).filter($=>$.trim()).length," to add"]}),e.jsx(Je,{type:"button",size:"sm",disabled:!de.trim()||ie,onClick:He(Un),children:ie?"Adding...":"Add queries"})]})]}),s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${Se===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":Se===void 0,onClick:()=>{Ce(void 0)},children:"All locations"}),s.project.locations.map($=>e.jsx("button",{className:`filter-chip ${Se===$.label?"filter-chip-active":""}`,type:"button","aria-pressed":Se===$.label,onClick:()=>{Ce($.label),Qe(!1)},children:$.label},$.label)),rt&&e.jsx("button",{className:`filter-chip ${Se===""?"filter-chip-active":""}`,type:"button","aria-pressed":Se==="",onClick:()=>{Ce(""),Qe(!1)},children:"No location"}),Za.length>1&&Se===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${tt?"filter-chip-active":""}`,type:"button","aria-pressed":tt,onClick:()=>Qe($=>!$),title:"Side-by-side location comparison",children:"Compare"})]}),Bt.evidenceLoading?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading query evidence…"}):Bt.evidenceError?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load query evidence."}),e.jsx(R,{type:"button",variant:"outline",onClick:()=>{Bt.refetch()},children:"Retry"})]}):e.jsx(Uh,{evidence:Gn,compareLocations:tt})]}),e.jsxs(Fr,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:oe(),children:[e.jsx(zx,{projectName:s.project.name}),s.providerScores.length>1&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Model breakdown"}),e.jsxs("h2",{children:["Citation rate by model ",e.jsx(Ve,{text:"Per-model citation rate in the latest sweep. The same query set can perform differently across engines."})]})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Model"}),e.jsx("th",{scope:"col",children:"Citation rate"}),e.jsx("th",{scope:"col",children:"Cited queries"})]})}),e.jsx("tbody",{children:s.providerScores.map($=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(En,{provider:$.provider}),$.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:$.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[$.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[$.cited," of ",$.total]})]},`${$.provider}::${$.model??"unknown"}`))})]})})]})]}),!oe()&&e.jsx(Fr,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map($=>e.jsx(Wm,{run:$},$.id))})})]}),report:Ke,reportState:ht,onOpenSetup:oe()?void 0:()=>{h({to:"/projects/$projectName/portfolio",params:{projectName:f}})},onRetryReport:()=>{k===2?Promise.all([nt.refetch(),Ye.refetch()]):Ye.refetch()},onViewChange:$=>{_e({scope:$.scope,...$.groupKey?{groupKey:$.groupKey}:{},queryClass:$.queryClass,...$.search?.trim()?{search:$.search.trim()}:{}})},onLoadMore:$=>{$===Ne?.properties.nextCursor&&nt.fetchNextPage()},onPropertyExpand:()=>{he&&Ye.isError&&Ye.refetch(),xt(!0)},onRetryEvidence:()=>{Ye.refetch()},renderPropertyLink:k===2&&!oe()?({id:$,name:fe})=>e.jsx(As,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:f,targetKey:$},className:"text-link hover:underline",children:fe}):void 0,isViewLoading:nt.isPlaceholderData,isLoadingMore:nt.isFetchingNextPage,isLoadMoreError:nt.isFetchNextPageError,viewSearch:De.search??""},`${f}:${Ie}`)),!lt&&F.measurementScope==="project"?e.jsxs("details",{className:"page-section-divider",onToggle:$=>{$.currentTarget.open&&c()},children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm font-medium text-heading",children:"Project signals"}),!d||o?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(R,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsx(tb,{insights:s.insights,suggestedQueries:s.suggestedQueries,onManageQueries:oe()?void 0:()=>{h({to:"/projects/$projectName/queries",params:{projectName:f},search:$=>({...$,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]},f):null,ps?e.jsxs("details",{className:"page-section-divider",open:Xt,onToggle:$=>ys($.currentTarget.open?f:null),children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm font-medium text-heading",children:"Competitor history"}),e.jsx("p",{className:"pb-3 text-sm text-secondary",children:"History for this scope uses the time window below."}),e.jsx(Eh,{window:B,landscape:Zt.data,pinnedFallback:_,canWrite:u,isEmbed:oe(),onWindowChange:xe,onPin:Ze&&u&&!oe()?xa:!Et&&u&&!oe()?Bn:void 0,onUnpin:Ze||Et||!u||oe()?void 0:ha,onAddCompetitor:Ze&&u&&!oe()?xa:!Et&&u&&!oe()?Bn:void 0,error:vt,onRetry:Nt?()=>{Zt.refetch()}:void 0,isLoading:Nt&&Zt.isPending&&Zt.data===void 0,scopeLabel:Ze?`${Qt?.label??Ze} group`:Et?"All markets":"Project-wide"})]}):null]}):K==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(_y,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async($,fe)=>{await kn($,fe)},onRefresh:()=>{n()}}),e.jsx(By,{project:s.project,onSave:async $=>{await kn(s.project.name,$)}}),u&&!oe()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Advanced measurement"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Measure individual properties, locations, or site sections with separate query sets."}),je==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):je==="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(R,{type:"button",size:"sm",variant:"outline",onClick:()=>{N.refetch()},children:"Retry"})]}):e.jsx(R,{type:"button",variant:"outline",onClick:()=>{h({to:"/projects/$projectName/portfolio",params:{projectName:f}})},children:hc(bt.setupAction)})]}):null,e.jsx(Qy,{projectName:s.project.name}),e.jsx(Wy,{projectName:s.project.name}),u&&!oe()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-negative-400",children:"Delete project"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Permanently deletes this project and all its queries, competitors, runs, and snapshots."}),C?e.jsxs(pe,{className:"surface-card p-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(R,{type:"button",variant:"destructive",disabled:z,onClick:He(ln),children:z?"Deleting...":"Yes, delete project"}),e.jsx(R,{type:"button",variant:"outline",disabled:z,onClick:()=>te(!1),children:"Cancel"})]})]}):e.jsxs(Je,{type:"button",variant:"outline",onClick:()=>te(!0),children:[e.jsx(Nl,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):K==="report"?e.jsx(Cy,{projectName:s.project.name}):K==="queries"||K==="discovery"?e.jsx(Yp,{projectName:f,queryWorkspace:U.queryWorkspace==="research"||K==="discovery"&&U.queryWorkspace===void 0?"research":"tracked",onQueryWorkspaceChange:$=>T({queryWorkspace:$,trackingQueryId:void 0}),researchMode:U.researchMode==="test"?"test":"find",onResearchModeChange:$=>T({researchMode:$}),selection:F,onSelectionChange:T,trackingQueryId:typeof U.trackingQueryId=="string"?U.trackingQueryId:void 0,onTrackingQueryIdChange:$=>T({trackingQueryId:$})}):K==="technical-aeo"?e.jsx(Hm,{projectName:s.project.name,projectId:s.project.id,initialRunId:U.siteHealthRunId,onReleaseInitialRun:I}):K==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(cf,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(Wg,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):K==="history"?e.jsx(Sg,{projectName:s.project.name}):K==="activity"?e.jsx(rx,{projectName:s.project.name}):K==="backlinks"?e.jsx(Qx,{projectName:s.project.name}):K==="local"?e.jsx(Nx,{projectName:s.project.name,projectId:s.project.id}):K==="search-console"?e.jsx(Zy,{projectName:s.project.name}):null]})}export{yb as ProjectPage,sb as ProjectSubnav,Hy as ProjectSweepConfirmation,Jy as patchProjectDashboardCache};
|