@ainyc/canonry 4.192.1 → 4.192.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/agent-workspace/skills/canonry/SKILL.md +8 -1
- package/assets/assets/{AuditHistoryPanel-DvqnrQc_.js → AuditHistoryPanel-B5ujKofj.js} +1 -1
- package/assets/assets/{BacklinksPage-BCk2qBfC.js → BacklinksPage-DnJ7tbUQ.js} +1 -1
- package/assets/assets/{HistoryPage-IMlkx--Q.js → HistoryPage-uOpp9NS1.js} +1 -1
- package/assets/assets/MeasurementPropertyPage-R-EM27KG.js +1 -0
- package/assets/assets/ProjectPage-L4LCiofR.js +8 -0
- package/assets/assets/{RunRow-BherM7NU.js → RunRow-DzldP1Fv.js} +1 -1
- package/assets/assets/{RunsPage-B5G_OrmE.js → RunsPage-aAn7zPwn.js} +1 -1
- package/assets/assets/{SettingsPage-CMeCn5uk.js → SettingsPage-BdAhhAS6.js} +1 -1
- package/assets/assets/{SiteHealthSection-DZX1yv4k.js → SiteHealthSection-DOQWKbrE.js} +3 -3
- package/assets/assets/{TrafficPage-BV-HOztp.js → TrafficPage-BARq38mK.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-9IN0q7bd.js → TrafficSourceDetailPage-DRhuS7fH.js} +1 -1
- package/assets/assets/{extract-error-message-c7zJp5uX.js → extract-error-message-DX4eQGO9.js} +1 -1
- package/assets/assets/index-CjEprBri.css +1 -0
- package/assets/assets/{index-D3KGn0S0.js → index-zF9YNhaN.js} +25 -25
- package/assets/assets/{react-sigma_core.esm.min-DxHkjhKC.js → react-sigma_core.esm.min-CcZJvxeL.js} +1 -1
- package/assets/assets/v2-overview-adapter-Jh4TgRVR.js +1 -0
- package/assets/index.html +2 -2
- package/dist/{chunk-T6GRXUOE.js → chunk-7773NNZY.js} +23 -1
- package/dist/{chunk-T4OO575U.js → chunk-ISDE2PZC.js} +4 -4
- package/dist/{chunk-QRNKMGVD.js → chunk-JXMRYJR5.js} +19 -0
- package/dist/{chunk-S5QNBQ72.js → chunk-KWUKYRS5.js} +2 -2
- package/dist/{chunk-V4ZLHKOG.js → chunk-ZGAVPLNP.js} +5 -5
- package/dist/cli.js +5 -5
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-QYRQHSJH.js → intelligence-service-TJN37R37.js} +2 -2
- package/dist/mcp.js +3 -3
- package/package.json +10 -10
- package/assets/assets/MeasurementPropertyPage-1o1e5vmH.js +0 -1
- package/assets/assets/ProjectPage-BusVoYaC.js +0 -8
- package/assets/assets/index-BtTEcbcB.css +0 -1
- package/assets/assets/v2-overview-adapter-COMP5UGt.js +0 -1
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{j as e,r as l,u as $e,L as As,h as ms,o as $t,B as ni,C as Zo,D as hc,k as xc,l as pc}from"./vendor-tanstack-ZXXkndVj.js";import{T as ue,t as gc,a as fc,M as el,I as Ve,s as tl,B as P,b as yc,u as sl,C as bc,P as Ln,h as vc,c as jc,d as mn,g as nl,e as al,f as ye,i as W,j as re,k as Nt,l as Ye,m as Nc,n as wc,o as Sc,p as rl,q as Cc,r as kc,v as bn,S as hn,w as Ac,x as Pc,y as Ts,z as Wt,A as Rc,D as Si,E as il,G as Ut,F as ai,H as Ic,J as $c,K as Tc,L as Mc,N as Ci,O as Te,Q as Lc,R as qc,U as er,V as Ec,W as Dc,X as Oc,Y as Fc,Z as Kc,_ as Gc,$ as _c,a0 as Uc,a1 as Bc,a2 as Vc,a3 as zc,a4 as Qc,a5 as Hc,a6 as Wc,a7 as Yc,a8 as ol,a9 as Ys,aa as Jc,ab as ll,ac as Oa,ad as Xc,ae as Je,af as Zc,ag as ed,ah as td,ai as Fa,aj as sd,ak as nd,al as ad,am as pn,an as rd,ao as id,ap as od,aq as cl,ar as Fr,as as ld,at as ri,au as cd,av as ea,aw as Js,ax as Bt,ay as dd,az as ud,aA as md,aB as tr,aC as Et,aD as hd,aE as xd,aF as pd,aG as gd,aH as fd,aI as Xn,aJ as ki,aK as ya,aL as sr,aM as yd,aN as bd,aO as Ai,aP as nr,aQ as xn,aR as vd,aS as dl,aT as ul,aU as jd,aV as Nd,aW as Pi,aX as wd,aY as Sd,aZ as Cd,a_ as kd,a$ as Ad,b0 as Pd,b1 as Rd,b2 as Id,b3 as $d,b4 as Td,b5 as Md,b6 as Ld,b7 as qd,b8 as Ed,b9 as Dd,ba as Od,bb as Fd,bc as Kd,bd as Gd,be as _d,bf as Ud,bg as Bd,bh as Vd,bi as zd,bj as Qd,bk as Hd,bl as Wd,bm as Yd,bn as Ns,bo as Jd,bp as xt,bq as Xd,br as Zd,bs as eu,bt as tu,bu as su,bv as nu,bw as au,bx as ru,by as iu,bz as ou,bA as lu,bB as cu,bC as du,bD as uu,bE as mu,bF as hu,bG as xu,bH as pu,bI as gu,bJ as fu,bK as yu,bL as bu,bM as vu,bN as Ri,bO as Ii,bP as $i,bQ as ju,bR as Nu,bS as wu,bT as Su,bU as Cu,bV as ku,bW as Au,bX as Pu,bY as Ru,bZ as Iu,b_ as $u,b$ as Tu,c0 as Mu,c1 as Lu,c2 as qu,c3 as Eu,c4 as Du,c5 as Ou,c6 as Fu,c7 as Ku,c8 as ml,c9 as ar,ca as Gu,cb as Ti,cc as _u,cd as Uu,ce as Bu,cf as Vu,cg as zu,ch as Qu,ci as Hu,cj as hl,ck as Wu,cl as xl,cm as pl,cn as gl,co as fl,cp as Yu,cq as Ju,cr as Xu,cs as Zu,ct as em,cu as tm,cv as Mi,cw as sm,cx as nm,cy as am,cz as rm,cA as im,cB as Li,cC as om,cD as lm,cE as cm,cF as dm,cG as um,cH as mm,cI as Ka,cJ as hm,cK as rr,cL as xm,cM as pm,cN as gm,cO as fm,cP as ym,cQ as bm,cR as vm,cS as jm,cT as Nm,cU as wm,cV as yl,cW as Sm,cX as Cm,cY as km,cZ as Am,c_ as Pm,c$ as Rm,d0 as ba,d1 as Im,d2 as $m,d3 as Tm,d4 as qi,d5 as Mm}from"./index-D3KGn0S0.js";import{C as gn,e as Ga,q as ta,U as Lm,r as qm,L as Em,s as Dm,i as Om,P as _a,D as bl,t as Fm,u as vl,v as Km,d as Gm,E as _m,p as Um,w as Bm,x as jl}from"./vendor-lucide-CW2qe0uH.js";import{R as Vm}from"./RunRow-BherM7NU.js";import{u as fn,D as Qs,a as qs,b as Nl,M as qa,c as Rs,S as zm}from"./SiteHealthSection-DZX1yv4k.js";import{C as sa,f as yn,a as ds,b as Ft,c as Vt,d as ts,e as rt,g as us,h as Es,M as wl,i as Sl,o as Ds,j as Hs,p as Qm}from"./ChartPrimitives-Bxa_vFmq.js";import{u as Hm,a as Wm,b as Ym,t as Jm,e as Xm,c as ft}from"./extract-error-message-c7zJp5uX.js";import{R as Xs,C as Zs,a as na,X as en,Y as tn,T as sn,b as Kr,L as Ua,A as Bs,d as Ls,e as Zm}from"./vendor-recharts-D-cUuLZo.js";import{M as eh}from"./vendor-markdown-B-Oq2NYq.js";import{A as th}from"./AuditHistoryPanel-DvqnrQc_.js";import{a as sh,b as nh}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-yaml-GWJz5H2G.js";function Ws(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 ah(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=rh(r,1));return a}function rh(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 ih(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 oh(t,s){const n=ih(t,s);return n===null?null:Math.round(n*100)}function ir(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Ws(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Ws(t.prior)} ${s})`:`Flat ${n} (${Ws(t.prior)} ${s})`}const Cl=30;function Ei(t){return Math.round(t*10)/10}function lh(t){return t.prior>=Cl&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Ei(t.deltaAbs)} vs ${Ei(t.prior)}`}function ch(t,s,n){return t.prior>=Cl&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Ws(Math.round(t.deltaAbs))} ${s} ${n}`}function dh(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 uh=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function kl(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Al(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 Pl(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(kl).map(Al).filter(Boolean)):new Set}function Rl(t,s){const n=kl(t).map(Al).filter(Boolean).filter(a=>!uh.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function mh(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function hh(t,s){const n=Pl(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=Rl(mh(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function xh(t){const s=Pl(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=Rl(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const ph=1e6;function gh(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/ph)}const ii={queryClass:"all"},fh=["all","non-brand","branded"];function Il(t){return typeof t=="string"&&fh.includes(t)}function $l(t){const s=Il(t.class)?t.class:ii.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 yh(t,s){return s===null||t===null?!1:t!==s}function bh(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===ii.queryClass?void 0:t.queryClass}}function vh(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 jh(t){const s=h=>typeof t[h]=="string"&&t[h]!==""?t[h]:void 0,n=$l({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"||Il(o)?o:ii.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 c=Number(t.measurementRevision);Number.isSafeInteger(c)&&c>0&&(i.revision=c);const d=vh(t.measurementAnswer,i.queryKey);return d&&(i.answer=d),i}function Nh(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 Gr({state:t,label:s}){return e.jsx(ue,{tone:fc(t),children:s??gc(t)})}const an=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Di={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},wh={"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."},Sh="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Ch(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 kh({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,c)=>c.mentions-i.mentions||(i.label<c.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:Sh})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:o.map(i=>{const c=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:`${c>0?Math.max(c,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:i.mentions}),e.jsxs("td",{className:"mention-share-share",children:[c.toFixed(1),"%"]})]},i.label)})})]})}function Ah({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=l.useState("non-brand"),o=l.useId(),i=t.scope==="pooled",c=!i&&t.branded.snapshotsTotal>0,d=c?a:"non-brand",h=i?"pooled":d,m=d==="branded"?t.branded:t.breakdown,u=d==="branded"?t.breakdown:t.branded,b=Ch(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"?el[t.tone]:"text-secondary";function x(g){const f=an.findIndex(N=>N.value===d);let w=null;g.key==="ArrowRight"||g.key==="ArrowDown"?w=(f+1)%an.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?w=(f-1+an.length)%an.length:g.key==="Home"?w=0:g.key==="End"&&(w=an.length-1),w!==null&&(g.preventDefault(),r(an[w].value),g.currentTarget.querySelectorAll('[role="radio"]')[w]?.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:wh[h]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:x,children:an.map(g=>{const f=g.value===d;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:Di[h]})]}),b.numeric?e.jsxs("p",{className:`mention-share-value ${p}`,children:[b.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:b.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:Di[h]}),` · ${b.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),b.showRows&&e.jsx(kh,{breakdown:m,projectLabel:s,competitorDomains:n})]})}const rn=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Oi=5;function Ph(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 Rh(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function or(t){return t==="unavailable"?"Unavailable":"Not measured"}function Tl(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 Ih({value:t,onChange:s}){function n(a){const r=rn.findIndex(c=>c.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%rn.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+rn.length)%rn.length:a.key==="Home"?o=0:a.key==="End"&&(o=rn.length-1),o===null)return;a.preventDefault();const i=rn[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:rn.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 _r({row:t,isProject:s=!1,metricState:n="measured",shareContext:a,canManage:r,onPin:o,onUnpin:i}){const c=!s&&r&&!t.pinned&&!!o,d=!s&&r&&t.pinned&&!!i,h=n==="measured",m=h&&t.sampleUrls.length>0,[u,b]=l.useState(!1),[p,x]=l.useState(null);async function g(f,w){if(!(!w||u)){b(!0),x(null);try{await w(t.domain)===!1&&x(`Could not ${f} competitor. Try again.`)}catch{x(`Could not ${f} competitor. Try again.`)}finally{b(!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":Tl(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:h?yc(t.shareOfVoice,a):or(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.mentionCount:or(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.citationCount:or(n)}),e.jsx("td",{className:"text-right",children:c||d||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,d&&i?e.jsxs(P,{type:"button",size:"sm",variant:"outline",disabled:u,onClick:()=>{g("unpin",i)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,c&&o?e.jsxs(P,{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 Ur({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function $h({rows:t,shareContext:s,canManage:n,onPin:a}){const[r,o]=l.useState(!1),i=r?t:t.slice(0,Oi);return e.jsxs("tbody",{children:[e.jsx(Ur,{children:"Observed in this window"}),i.map(c=>e.jsx(_r,{row:{...c,pinned:!1},shareContext:s,canManage:n,onPin:a},c.domain)),t.length>Oi?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(P,{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(c=>!c),children:r?"Show fewer":`Show all ${t.length}`})]})})}):null]})}function Th({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,c]=l.useState(null);async function d(){const h=n.trim();if(!(!h||r)){o(!0),c(null);try{if(await t(h)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("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(),d()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange: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(P,{type:"submit",size:"sm",className:"min-h-10",disabled:r||!n.trim(),children:r?"Adding…":"Add competitor"}),i?e.jsx("p",{role:"alert",className:"w-full text-sm text-negative",children:i}):null]})]})}function Mh({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:c,onAddCompetitor:d,error:h,onRetry:m,isLoading:u=!1,scopeLabel:b}){const p=a&&!r,x=s?.pinned??n,g=s?.observed??[],f=s?.otherSources??[],w=s?.evidence,N=Rh(s),D=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"}),b?e.jsx("p",{className:"supporting-copy mt-1",children:b}):null,s?e.jsx("p",{className:"supporting-copy mt-1",children:Ph(s.filters?.queryClass)}):null,s?.reason?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:tl(s.reason)}):null]}),e.jsx(Ih,{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(P,{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(Ur,{children:"You"}),e.jsx(_r,{row:s.project,shareContext:s,isProject:!0,metricState:N,canManage:!1})]}):null,e.jsx(Ur,{children:"Pinned"}),x.length>0?x.map(A=>e.jsx(_r,{row:{...A,pinned:!0},shareContext:s,metricState:N,canManage:p,onUnpin:c},A.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s&&g.length>0?e.jsx($h,{shareContext:s,rows:g,canManage:p,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),w?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:[w.answeredResults," ",w.answeredResults===1?"answer":"answers"]}),w.missingAnswerTextResults>0?e.jsx("span",{className:"text-caution",children:"Answer data incomplete"}):null,w.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(gn,{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:[w.sourceResults," ",w.sourceResults===1?"result includes":"results include"," source URLs."]}),w.missingAnswerTextResults>0?e.jsxs("p",{children:[w.missingAnswerTextResults," ",w.missingAnswerTextResults===1?"result has":"results have"," no answer text and ",w.missingAnswerTextResults===1?"is":"are"," excluded from mention share."]}):null,w.incompleteSourceResults>0?e.jsxs("p",{children:[w.incompleteSourceResults," ",w.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,w.excludedProbeResults+w.excludedNonCompletedResults>0?e.jsxs("p",{children:[w.excludedProbeResults+w.excludedNonCompletedResults," test or unfinished ",w.excludedProbeResults+w.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,D>0?e.jsx("p",{className:"text-sm text-secondary",children:s?.scope.kind==="all-markets"?`${D} competitor${D===1?" is":"s are"} pending publication across markets.`:`${D} competitor${D===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," · ",Tl(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(y=>e.jsx("li",{className:"break-all",children:y},y))}):null]},A.domain))})]}):null]}),p&&d?e.jsx(Th,{onAddCompetitor:d}):null]})}function Fi({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"}),c=new Date(n[o].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),d=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. ${d}`,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),b=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":""} ${b?"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,b?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[c," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function Br(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 Lh=320;function qh(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function Eh(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function Ki(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 Gi(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 _i(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 c=t.length-1;c>=0&&t[c].citationState===r;c--)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 Dh(t,s){return t.map(n=>Ml(n,s))}function Ml(t,s){return s==="citations"?t:{...t,citationState:Ki(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Ki(n,s)}))}}function Ui(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",c=o==="cited"||o==="emerging";return r==="lost"||o!==null&&c&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||o!==null&&!c&&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 Oh(t){const s=Br(Dh(t,"mentions")),n=Br(t);return[Ui(s,"mentions"),Ui(n,"citations")]}function Fh({signal:t}){const s=t.tone==="positive"?"border-positive-500/25 bg-positive-500/10 text-positive":t.tone==="negative"?"border-negative-500/25 bg-negative-500/10 text-negative":t.tone==="pending"?"border-caution-500/20 bg-caution-500/10 text-caution":"border-mono-700/60 bg-bg-elevated/70 text-secondary";return e.jsx("span",{className:`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium leading-none ${s}`,children:t.label})}function Bi({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Oh(t).map(s=>e.jsx(Fh,{signal:s},s.key))})}function Kh({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=sl(),[r,o]=l.useState(new Set),[i,c]=l.useState("mentions"),[d,h]=l.useState(n),[m,u]=l.useState("all"),b=l.useMemo(()=>{const y=new Map;for(const j of t){const C=j.query,L=j.queryClass??null,E=s?j.location??null:null,F=JSON.stringify([C,L,E]),V=y.get(F)??{key:F,phrase:C,queryClass:L,location:E,items:[],rawItems:[]};V.items.push(Ml(j,i)),V.rawItems.push(j),y.set(F,V)}return[...y.values()]},[t,i,s]),p=l.useMemo(()=>b.filter(y=>m==="all"||(m==="unclassified"?y.queryClass===null:y.queryClass===m)),[b,m]),x=fn({rows:p,getSearchText:Eh}),g=x.rows.map(y=>y.key),f=g.length>0&&g.every(y=>r.has(y)),w=y=>{o(j=>{const C=new Set(j);return C.has(y)?C.delete(y):C.add(y),C})},N=i==="mentions"?"mentioned":"cited",D=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:()=>c("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:()=>c("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(y=>{const j=new Set(y);for(const C of g)f?j.delete(C):j.add(C);return j})},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":d==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="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":d==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),b.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(Qs,{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:y=>{u(y.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:D}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:x.rows.map(({key:y,phrase:j,queryClass:C,location:L,items:E,rawItems:F})=>{const V=r.has(y),K=E.map(O=>O.citationState),k=K.includes("cited")?"cited":K.includes("emerging")?"emerging":K.includes("lost")?"lost":K.every(O=>O==="pending")?"pending":"not-cited",q=Br(E),R=E.filter(O=>O.citationState===bc.cited||O.citationState==="emerging").length,ae=_i(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:()=>w(y),onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),w(y))},tabIndex:0,role:"button","aria-expanded":V,children:[e.jsx("td",{children:e.jsx(Ga,{size:14,className:`transition-transform duration-150 text-muted ${V?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:j}),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(ue,{tone:"neutral",className:"whitespace-nowrap",children:qh(C)}),E.map(O=>e.jsx(Ln,{provider:O.provider},O.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gr,{state:k,label:Gi(k,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${R} of ${E.length} engines ${A}`,children:[R,"/",E.length]})]})}),e.jsx("td",{children:e.jsx(Fi,{history:q})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ae}),e.jsx(Bi,{items:F})]}),e.jsx("td",{})]}),V&&E.map((O,X)=>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(Ln,{provider:O.provider})}),e.jsx("td",{children:e.jsx(Gr,{state:O.citationState,label:Gi(O.citationState,i)})}),e.jsx("td",{children:e.jsx(Fi,{history:O.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:_i(O.runHistory,i)}),e.jsx(Bi,{items:[F[X]??O]})]}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",size:"sm",type:"button",onClick:ce=>{ce.stopPropagation(),a(O.id)},children:"View"})})]}),d==="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(Uh,{item:O,onViewFull:()=>a(O.id)})})]})]},O.id))]},y)})})]})}),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(qs,{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 Gh(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=jc(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 Vi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function _h(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 Uh({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}=_h(t.answerSnippet,Lh),o=Gh(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:vc(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] ${Vi(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,Vi(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 va({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 Wa({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 lr=rt[0],cr=rt[1],zi=rt[2],Qi=rt[3],Bh=["both","server","ga4"],Hi={fontSize:11,paddingTop:6},Wi=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Yi=t=>typeof t=="number"?Ws(Math.round(t)):String(t),rs=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function dr(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 ur({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 Vh(t,s){return n=>{const{cx:a,cy:r,index:o,key:i}=n,c=o??-1;return!(t[c]!=null&&t[c-1]==null&&t[c+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function zh({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,c]=l.useState("both"),d=Hm(t,{sinceMinutes:s,granularity:"day",limit:1}),h=Wm(t),u=$e({...nl({client:W,path:{name:t}}),enabled:!!t,staleTime:mn}).data?.connected===!0,b=$e({...al({client:W,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&u,staleTime:mn}),p=l.useMemo(()=>d.data?.series?.points??[],[d.data]),x=l.useMemo(()=>{const L=b.data;return new Map((L?.days??[]).map(E=>[E.date,E.sessions]))},[b.data]),g=l.useMemo(()=>{const L=F=>F.measured!==!1;if(p.length===0||L(p[0]))return null;const E=p.findIndex(L)-1;return E<0?{from:p[0].bucket,to:p[p.length-1].bucket}:{from:p[0].bucket,to:p[E].bucket}},[p]),f=d.data?.series?.coverageStart??null,w=d.data?.series?.trends,N=l.useMemo(()=>{const L=dr(w?.crawlerContentHits,p.length),E=dr(w?.aiUserFetchHits,p.length),F=dr(w?.aiReferralLandedHits,p.length);return p.map((V,K)=>({...V,crawlerContentHits:V.measured!==!1?rs(V.crawlerContentHits):null,aiUserFetchHits:V.measured!==!1?rs(V.aiUserFetchHits):null,aiReferralLandedHits:V.measured!==!1?rs(V.aiReferralLandedHits):null,ga4Visits:x.get(V.bucket)??null,crawlTrend:L[K],fetchTrend:E[K],visitTrend:F[K]}))},[p,x,w]),D=d.data?.totals,A=D&&{crawlers:rs(D.crawlerContentHits),fetches:rs(D.aiUserFetchHits),visits:rs(D.aiReferralLandedHits)},y=l.useMemo(()=>p.reduce((L,E)=>({crawlers:L.crawlers+rs(E.crawlerContentHits),fetches:L.fetches+rs(E.aiUserFetchHits),visits:L.visits+rs(E.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[p]),j=A??y,C=j.crawlers>0||j.fetches>0||j.visits>0;if(d.isLoading)return e.jsx(ye,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(d.isError)return e.jsxs(ye,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!C){const L=h.data?.sources,E=L!==void 0&&L.length===0,F=!E&&f===null;return e.jsxs(ye,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:E?"No server-side traffic source connected yet.":F?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:E?"Connect a traffic source to see how AI engines read this site over time.":F?"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(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(ur,{label:"AI crawlers",value:Ws(j.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(ur,{label:"AI page fetches",value:Ws(j.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(ur,{label:"AI visitors",value:Ws(j.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:rs(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:rs(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:rs(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(Xs,{width:"100%",height:206,children:e.jsxs(Zs,{data:N,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Ft,stroke:ds,tickFormatter:yn,minTickGap:28}),e.jsx(tn,{tick:Ft,stroke:ds,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Vt,formatter:Yi}),g&&e.jsx(Kr,{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(Ua,{wrapperStyle:Hi,iconType:"plainline",iconSize:14,formatter:L=>Wi.has(L)?"":L}),e.jsx(Bs,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:lr,fill:lr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Bs,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:cr,fill:cr,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Ls,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:lr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Ls,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:cr,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(Wa,{windows:Bh,value:i,onChange:c,label:"Visit measurement source",formatOption:L=>L==="ga4"?"GA4":L==="both"?"Both":"Server"})]}),e.jsx(Xs,{width:"100%",height:176,children:e.jsxs(Zs,{data:N,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Ft,stroke:ds,tickFormatter:yn,minTickGap:28}),e.jsx(tn,{tick:Ft,stroke:ds,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Vt,formatter:Yi}),g&&e.jsx(Kr,{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(Ua,{wrapperStyle:Hi,iconType:"plainline",iconSize:14,formatter:L=>Wi.has(L)?"":L}),i!=="ga4"&&e.jsx(Ls,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:zi,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Ls,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Qi,strokeWidth:1.8,strokeDasharray:"5 3",dot:Vh(N.map(L=>L.ga4Visits),Qi)}),r&&i!=="ga4"&&e.jsx(Ls,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:zi,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const Qh=6,qn="__other__",Tn="_socialTotal";function Hh(t,s=Qh){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),c=new Map;for(const m of t){let u=c.get(m.date);u||(u={date:m.date,[Tn]:0},c.set(m.date,u));const b=o.has(m.source)?m.source:qn;u[b]=(u[b]??0)+m.sessions,u[Tn]=(u[Tn]??0)+m.sessions}const d=[...c.values()].sort((m,u)=>String(m.date).localeCompare(String(u.date))),h=r.map(([m])=>m);return i>0&&h.push(qn),{data:d,sources:h,otherCount:i}}function Mn(t){return t.replace(/\+/g," ")}function Ll(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Ji="_totalSessions",Xi="_organicSessions";function Wh(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Ji]:i.sessions,[Xi]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[Ji]:0,[Xi]:0},n.set(i.date,c));for(const d of i.bySource)c[d.source]=(c[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([i],[c])=>i.localeCompare(c)).map(([i,c])=>({date:i,...c})),r=a.map(i=>i.date),o=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:o}}const Yh=["7d","30d","90d"],Jh={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Us=rt,Vr=us.textDim,ql=us.textFaint,_n=25;function Xh(t){return Nl(t.landingPage)}const Zh=25,ex=10,mr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function ja(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function El(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 tx({projectName:t}){const{data:s,isLoading:n,isError:a}=Ym(t);if(n)return e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(ye,{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."," ",!re()&&e.jsx(As,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(ye,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!re()&&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(ye,{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(ue,{tone:Jm(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?El(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:re()?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 sx({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(tx,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Wa,{windows:Yh,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(nx,{projectName:t,window:s}),e.jsx(zh,{projectName:t,sinceMinutes:Jh[s]})]})}function nx({projectName:t,window:s}){const n=ms(),a=s??"30d",[r,o]=l.useState(null),[i,c]=l.useState(null),[d,h]=l.useState(!0),[m,u]=l.useState(!1),[b,p]=l.useState(!1),[x,g]=l.useState(null),[f,w]=l.useState(null),[N,D]=l.useState("sessions"),[A,y]=l.useState("desc"),[j,C]=l.useState("sessions"),[L,E]=l.useState("desc"),[F,V]=l.useState("sessions"),[K,k]=l.useState("desc"),[q,R]=l.useState("sessions"),[ae,O]=l.useState("desc"),[X,ce]=l.useState(mr),[Y,_]=l.useState([]),[I,le]=l.useState([]),[T,ee]=l.useState(!1);async function Z(te){h(!0),g(null);try{const qe=await n.fetchQuery({...nl({client:W,path:{name:t}}),staleTime:mn});if(te.current)return;if(o(qe),!qe.connected){c(null),ce(mr),_([]),le([]),h(!1);return}const Ce=a==="all"?void 0:a,Pe=await n.fetchQuery({...Nc({client:W,path:{name:t},query:Ce?{window:Ce}:void 0}),staleTime:mn}).then(mt=>mt),Yt=Pe.windowStart||Pe.windowEnd?{...Pe.windowStart?{startDate:Pe.windowStart}:{},...Pe.windowEnd?{endDate:Pe.windowEnd}:{}}:void 0,[Jt,yt,St]=await Promise.all([n.fetchQuery({...al({client:W,path:{name:t},query:Ce?{window:Ce}:void 0}),staleTime:mn}).catch(()=>mr),n.fetchQuery({...wc({client:W,path:{name:t},query:Ce?{window:Ce}:void 0}),staleTime:mn}).catch(()=>[]),n.fetchQuery({...Sc({client:W,path:{name:t},query:Yt}),staleTime:mn}).catch(()=>[])]);if(te.current)return;c(Pe),ce(Jt),_(yt),le(St),h(!1)}catch(qe){if(te.current)return;g(qe instanceof Error?qe.message:"Failed to load GA4 data"),h(!1)}}l.useEffect(()=>{const te={current:!1};return Z(te),()=>{te.current=!0}},[t,a,n]);async function ge(){u(!0),g(null),w(null);try{const te=await rl(t);w(`Synced ${te.rowCount.toLocaleString()} page rows, ${te.aiReferralCount.toLocaleString()} AI and ${te.socialReferralCount.toLocaleString()} social referral rows (${te.days} days)`),await Nt(n,"ga"),await Z({current:!1})}catch(te){g(te instanceof Error?te.message:"Sync failed")}finally{u(!1)}}async function J(){p(!0),g(null),w(null);try{await Cc(t),await Nt(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),w("GA4 disconnected")}catch(te){g(te instanceof Error?te.message:"Disconnect failed")}finally{p(!1)}}function de(te){ne.setPage(1),N===te?y(qe=>qe==="desc"?"asc":"desc"):(D(te),y("desc"))}function xe(te){j===te?E(qe=>qe==="desc"?"asc":"desc"):(C(te),E("desc"))}function se(te){F===te?k(qe=>qe==="desc"?"asc":"desc"):(V(te),k("desc"))}const z=l.useMemo(()=>i?.topPages?[...i.topPages].sort((te,qe)=>{const Ce=te[N],Pe=qe[N];return typeof Ce=="string"&&typeof Pe=="string"?A==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):A==="asc"?Ce-Pe:Pe-Ce}):[],[i?.topPages,N,A]),ne=fn({rows:z,getSearchText:te=>Nl(te.landingPage),pageSize:ex}),Ee=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((te,qe)=>{const Ce=te[j],Pe=qe[j];return typeof Ce=="string"&&typeof Pe=="string"?L==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):L==="asc"?Ce-Pe:Pe-Ce}):[],[i?.aiReferrals,j,L]),we=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((te,qe)=>{const Ce=te[q],Pe=qe[q];return typeof Ce=="string"&&typeof Pe=="string"?ae==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):ae==="asc"?Ce-Pe:Pe-Ce}):[],[i?.aiReferralLandingPages,q,ae]),Se=fn({rows:we,getSearchText:Xh,pageSize:Zh}),et=Se.totalRows>0?`${Se.totalRows.toLocaleString()} ${Se.hasQuery?Se.totalRows===1?"match":"matches":Se.totalRows===1?"row":"rows"}`:Se.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Ke(te){Se.setPage(1),q===te?O(qe=>qe==="desc"?"asc":"desc"):(R(te),O("desc"))}const ze=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((te,qe)=>{const Ce=te[F],Pe=qe[F];return typeof Ce=="string"&&typeof Pe=="string"?K==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):K==="asc"?Ce-Pe:Pe-Ce}):[],[i?.socialReferrals,F,K]),{socialChartData:He,socialChartSources:Ge,socialOtherCount:U}=l.useMemo(()=>{const te=Hh(I);return{socialChartData:te.data,socialChartSources:te.sources,socialOtherCount:te.otherCount}},[I]),{chartData:B,chartSources:H,dateRange:Re}=l.useMemo(()=>{const te=Wh(X,Y);return{chartData:te.data,chartSources:te.sources,dateRange:te.dateRange}},[X,Y]);if(d&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return re()?e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(ax,{projectName:t,onConnected:()=>{(async()=>(await Nt(n,"ga"),await Z({current:!1})))()}});const _e=i?.organicSharePctDisplay??"0%",Ue=i?.channelBreakdown?.organic.sharePctDisplay??_e,ie=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,pt=i?.aiSessionsDeduped??0,ut=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,Qe=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Fe=i?.paidAiSessionsBySession??0,wt=i?.paidAiSharePctBySessionDisplay??"0%",Be=i?new Set(i.aiReferrals.map(te=>te.source.toLowerCase())).size:0,Me=Ee[0]??null,tt=i?.totalDirectSessions??0,Tt=i?.directSharePctDisplay??"0%",Mt=i?.channelBreakdown?.direct.sessions??tt,De=i?.channelBreakdown?.direct.sharePctDisplay??Tt,S=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Ae=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",ve=i?.socialSessions??0,We=i?.socialSharePctDisplay??"0%",vt=i?.channelBreakdown?.social.sessions??ve,st=i?.channelBreakdown?.social.sharePctDisplay??We,Lt=i?new Set(i.socialReferrals.map(te=>te.source.toLowerCase())).size:0,Xe=ze[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})]})]})]}),!re()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:m,onClick:Ye(ge),children:[e.jsx(ta,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:b,onClick:Ye(J),children:[e.jsx(Lm,{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(hr,{value:ja(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(hr,{value:ja(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${_e} of total`,tone:"positive"}),e.jsx(hr,{value:i.totalUsers===null?"—":ja(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."}),!re()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:m,onClick:Ye(ge),children:[e.jsx(ta,{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."})]})]}),Re&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Re.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Re.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),B.length>0&&e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:H.length>0?"AI vs. total sessions":"All sessions (baseline)"}),H.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),H.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:B,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn}),e.jsx(tn,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ts,labelFormatter:Vt,formatter:(te,qe)=>{const Ce=typeof te=="number"?te.toLocaleString():String(te??0),Pe=String(qe??"");return Pe==="_totalSessions"?[Ce,"Total Sessions"]:Pe==="_organicSessions"?[Ce,"Organic Sessions"]:[Ce,Pe]}}),e.jsx(Ua,{wrapperStyle:{fontSize:11,color:us.text},formatter:te=>te==="_totalSessions"?"Total Sessions":te==="_organicSessions"?"Organic Sessions":te}),e.jsx(Bs,{type:"monotone",dataKey:"_totalSessions",stroke:us.textFaint,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),H.map((te,qe)=>e.jsx(Bs,{type:"monotone",dataKey:te,stackId:"ai",stroke:Us[qe%Us.length],fill:Us[qe%Us.length],fillOpacity:.4,strokeWidth:1.5},te))]})})})]}),e.jsxs(ye,{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:Ue,hint:`${ie.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:st,hint:`${vt.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:`${Mt.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:Qe,hint:Fe>0?`${ut.toLocaleString()} sessions · ${Fe.toLocaleString()} paid`:`${ut.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:Ae,hint:`${S.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."})]}),Me&&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:Me.source})," via ",Me.medium,", accounting for ",Me.sessions.toLocaleString()," sessions.",Fe>0&&e.jsxs("span",{children:[" Paid AI: ",Fe.toLocaleString()," sessions (",wt,")."]})]})]}),e.jsxs(ye,{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?`${Be} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(is,{label:"Source",sortKey:"source",current:j,dir:L,onSort:xe,align:"left"}),e.jsx(is,{label:"Medium",sortKey:"medium",current:j,dir:L,onSort:xe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:j,dir:L,onSort:xe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Ee.map(te=>e.jsx(ix,{referral:te,totalSessions:pt},`${te.source}:${te.medium}:${te.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(ye,{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:et})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Qs,{value:Se.query,onChange:Se.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Se.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(is,{label:"Landing Page",sortKey:"landingPage",current:q,dir:ae,onSort:Ke,align:"left"}),e.jsx(is,{label:"Source",sortKey:"source",current:q,dir:ae,onSort:Ke,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:q,dir:ae,onSort:Ke,align:"right"})]})}),e.jsx("tbody",{children:Se.rows.map(te=>e.jsx(ox,{row:te},`${te.landingPage}:${te.source}:${te.medium}:${te.sourceDimension}`))})]})}),e.jsx(qs,{page:Se.page,pageSize:Se.pageSize,visibleRows:Se.rows.length,totalRows:Se.totalRows,onPageChange:Se.setPage,itemLabel:Se.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:()=>Se.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(ye,{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:ja(ve),hint:`${ve.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:We,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(Lt),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."})]}),Xe&&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:`${Xe.source} via ${Xe.medium}`,children:Ll(Mn(Xe.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Xe.medium,children:["via ",Mn(Xe.medium)," · ",Xe.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."})]})]})]}),He.length>0&&e.jsxs(ye,{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"})]}),U>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ge.length-1," sources · ",U," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:He,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn}),e.jsx(tn,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ts,labelFormatter:Vt,formatter:(te,qe)=>{const Ce=typeof te=="number"?te.toLocaleString():String(te??0),Pe=String(qe??"");if(Pe===Tn)return[Ce,"Total Social"];if(Pe===qn){const Yt=`Other (${U} source${U===1?"":"s"})`;return[Ce,Yt]}return[Ce,Mn(Pe)]}}),e.jsx(Bs,{type:"monotone",dataKey:Tn,stroke:ql,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ge.map((te,qe)=>{const Pe=te===qn?Vr:Us[qe%Us.length];return e.jsx(Bs,{type:"monotone",dataKey:te,stackId:"social",stroke:Pe,fill:Pe,fillOpacity:.4,strokeWidth:1.5},te)})]})})}),e.jsx(cx,{sources:Ge,otherCount:U})]}),e.jsxs(ye,{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?ze.length>_n&&!T?`Top ${_n} of ${ze.length}`:`${ze.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(is,{label:"Source",sortKey:"source",current:F,dir:K,onSort:se,align:"left"}),e.jsx(is,{label:"Medium",sortKey:"medium",current:F,dir:K,onSort:se,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:F,dir:K,onSort:se,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(T?ze:ze.slice(0,_n)).map(te=>e.jsx(lx,{referral:te,totalSessions:ve},`${te.source}:${te.medium}:${te.channelGroup}`))})]})}),ze.length>_n&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>ee(te=>!te),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:T?`Show top ${_n}`:`Show all ${ze.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(Qs,{value:ne.query,onChange:ne.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(is,{label:"Landing Page",sortKey:"landingPage",current:N,dir:A,onSort:de,align:"left"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:N,dir:A,onSort:de,align:"right"}),e.jsx(is,{label:"Organic",sortKey:"organicSessions",current:N,dir:A,onSort:de,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:ne.rows.map(te=>e.jsx(rx,{page:te},te.landingPage))})]})}),ne.totalRows===0&&ne.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(qs,{page:ne.page,pageSize:ne.pageSize,visibleRows:ne.rows.length,totalRows:ne.totalRows,onPageChange:ne.setPage,itemLabel:ne.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 ${El(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function ax({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,c]=l.useState(null),[d,h]=l.useState(!1),[m,u]=l.useState(null),b=l.useRef(null),p=l.useCallback(g=>{const f=g.target.files?.[0];if(!f)return;u(null),o(f.name);const w=new FileReader;w.onload=()=>{const N=w.result;try{const D=JSON.parse(N);if(!D.client_email||!D.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)."),c(null);return}c(N)}catch{u("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},w.onerror=()=>{u("Failed to read file."),c(null)},w.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 kc(t,{propertyId:n.trim(),keyJson:i});try{await rl(t)}catch{}s()}catch(g){u(g instanceof Error?g.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(ye,{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:b,type:"file",accept:".json,application/json",onChange:p,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>b.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(qm,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(P,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:Ye(x),children:d?"Connecting & syncing…":"Connect GA4"})]})}function is({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 Dl={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function hr({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 ${Dl[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 ${Dl[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function rx({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 Ol={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Fl={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 ix({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Ol[t.sourceDimension]??t.sourceDimension,r=Fl[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 ox({row:t}){const s=Ol[t.sourceDimension]??t.sourceDimension,n=Fl[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(qa,{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 lx({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=Mn(t.source),o=Mn(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 cx({sources:t,otherCount:s}){const n=[{key:Tn,color:ql,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===qn)n.push({key:qn,color:Vr,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=Mn(r);n.push({key:r,color:Us[a%Us.length]??Vr,label:Ll(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 dx(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 ux="Search Console is not connected yet. Your Canonry team can set this up.",mx=["7d","30d","90d","all"],Na=500,Zi=[{key:"clicks",label:"Clicks",color:rt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:rt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Es.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:rt[2],inverted:!0,format:t=>t.toFixed(1)}],Gs=25,hx="canonry:google-oauth-complete",xx=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function px(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 d=t.prior[s],h=t.trailing[s];return d!==null&&h!==null&&d<=0&&h>0?`new in the last ${a}d`:d===null||d<=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%":`${xx.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function gx(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}`,c=`${r.startDate} to ${r.endDate}`,d=`Tile percentages compare these ${s} ${o} (${c}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?d:`${d} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function eo(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function to(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 so(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function fx({projectName:t,refreshNonce:s}){const n=ms(),{isAdmin:a}=bn(),[r,o]=l.useState(!1),[i,c]=l.useState([]),[d,h]=l.useState([]),[m,u]=l.useState([]),[b,p]=l.useState(null),[x,g]=l.useState([]),[f,w]=l.useState([]),[N,D]=l.useState(null),[A,y]=l.useState(""),[j,C]=l.useState(""),[L,E]=l.useState("30"),[F,V]=l.useState(!1),[K,k]=l.useState("30d"),[q,R]=l.useState(["clicks","impressions"]),[ae,O]=l.useState(!0),[X,ce]=l.useState(null),[Y,_]=l.useState(0),[I,le]=l.useState({startDate:"",endDate:"",query:"",page:""}),[T,ee]=l.useState(0),[Z,ge]=l.useState(!1),[J,de]=l.useState(0),[xe,se]=l.useState(!1),[z,ne]=l.useState(""),[Ee,we]=l.useState(!0),[Se,et]=l.useState(!1),[Ke,ze]=l.useState(!1),[He,Ge]=l.useState(!1),[U,B]=l.useState(!1),[H,Re]=l.useState(!1),[_e,Ue]=l.useState(!1),[ie,pt]=l.useState(null),[ut,Qe]=l.useState(!1),[Fe,wt]=l.useState(!1),[Be,Me]=l.useState(null),[tt,Tt]=l.useState(null),[Mt,De]=l.useState([]),[S,Ae]=l.useState(new Set),[ve,We]=l.useState({}),[vt,st]=l.useState(new Set),[Lt,Xe]=l.useState(""),[te,qe]=l.useState(null),[Ce,Pe]=l.useState(""),[Yt,Jt]=l.useState(!1),[yt,St]=l.useState(!1),[mt,Xt]=l.useState(!1),[zt,ss]=l.useState(!1),[at,fs]=l.useState("indexed"),[gt,dt]=l.useState(null),Ct=!!(I.query.trim()||I.page.trim()||gt),ns=gt!==null,hs=l.useMemo(()=>{if(!gt)return m;const{key:v,dir:Q}=gt;return[...m].sort((he,be)=>{const Ze=v===hn.CTR?Number.isFinite(he.ctr)?he.ctr:0:he[v],nt=v===hn.CTR?Number.isFinite(be.ctr)?be.ctr:0:be[v];return Q==="asc"?Ze-nt:nt-Ze})},[m,gt]),qt=fn({rows:hs,pageSize:Rs}),Ps=xe?qt.rows:hs,Qt=fn({rows:(Be??[]).filter(v=>v.path.toLowerCase().includes(Lt.trim().toLowerCase())),pageSize:Rs}),[kt,xs]=l.useState([]),[ht,Zt]=l.useState(null),[ys,ps]=l.useState(1),G=l.useMemo(()=>{if(kt.length<2)return null;const v=kt[kt.length-1],Q=kt[kt.length-2];return{indexed:v.indexed-Q.indexed,notIndexed:v.notIndexed-Q.notIndexed}},[kt]);l.useEffect(()=>{ps(1)},[ie,at,ht]);const oe=l.useMemo(()=>ht?(ie?.reasonGroups??[]).find(v=>v.reason===ht):void 0,[ie,ht]),Ne=l.useMemo(()=>ie?at==="indexed"?ie.indexed:at==="deindexed"?ie.deindexed:at==="notIndexed"?ht?oe?.urls??[]:(ie.reasonGroups??[]).length===0?ie.notIndexed:[]:[]:[],[ie,at,ht,oe]),me=Math.max(1,Math.ceil(Ne.length/Gs)),je=Math.min(Math.max(1,ys),me),Ie=(je-1)*Gs,as=l.useMemo(()=>ie?.indexed.slice(Ie,Ie+Gs)??[],[ie,Ie]),ot=l.useMemo(()=>ie?.notIndexed.slice(Ie,Ie+Gs)??[],[ie,Ie]),bs=l.useMemo(()=>ie?.deindexed.slice(Ie,Ie+Gs)??[],[ie,Ie]),M=l.useMemo(()=>(oe?.urls??[]).slice(Ie,Ie+Gs),[oe,Ie]),[pe,it]=l.useState(!1),[At,Oe]=l.useState(null),[Kt,Pt]=l.useState(null),[vn,Ht]=l.useState(null);function jn(v,Q){const he=Xm(v),be=dx(he);be?(Pt(be),Oe(null)):(Pt(null),Oe(he.message||Q))}const Rt=i.find(v=>v.connectionType==="gsc"),vs=(Rt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),la=Mt.length>0?Mt:(Be??[]).map(v=>v.path),Nn=la.filter(v=>Be?.some(Q=>Q.path===v&&Q.isSitemapsIndex)).length,ca=Nn===1?"Resubmit sitemap index":Nn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Ja=m.length>0||x.length>0||f.length>0,Os=Ac(),Dn=Pc();async function da(v,Q=!1){if(!v){h([]),y("");return}ze(!0);try{const{sites:he}=await n.fetchQuery({..._c({client:W,path:{name:t}}),staleTime:Q?0:Ut});h(he),y(v.propertyId??he[0]?.siteUrl??""),Pt(null)}catch(he){h([]),jn(he,"Failed to load Search Console properties")}finally{ze(!1)}}async function nn(v){B(!0);const Q=v??T;try{const he=Ct?Na:Rs,be=Ct?0:Q,Ze={limit:String(he)};I.startDate&&(Ze.startDate=I.startDate),I.endDate&&(Ze.endDate=I.endDate),I.query&&(Ze.query=I.query),I.page&&(Ze.page=I.page),be>0&&(Ze.offset=String(be)),K&&K!=="all"&&!I.startDate&&(Ze.window=K);const nt=await n.fetchQuery({...$c({client:W,path:{name:t},query:Ze}),staleTime:Ut}),lt=nt.rows;Ct?(ge(!1),u(lt),de(lt.length),se(!0)):(ge(be+lt.length<nt.totalMatching),u(lt),de(0),se(!1))}catch(he){u([]),ge(!1),de(0),Oe(he instanceof Error?he.message:"Failed to load GSC performance data")}finally{B(!1)}}async function On(){try{const v={};I.startDate&&(v.startDate=I.startDate),I.endDate&&(v.endDate=I.endDate),K&&K!=="all"&&!I.startDate&&(v.window=K);const Q=await n.fetchQuery({...Ic({client:W,path:{name:t},query:v}),staleTime:Ut});p(Q)}catch{p(null)}}async function wn(v=!1){Re(!0);try{const Q=z.trim()||void 0,he={limit:"20"};Q&&(he.url=Q);const[be,Ze]=await Promise.all([n.fetchQuery({...Kc({client:W,path:{name:t},query:he}),staleTime:v?0:Ut}),n.fetchQuery({...Gc({client:W,path:{name:t}}),staleTime:v?0:Ut})]);g(be),w(Ze)}catch(Q){g([]),w([]),Oe(Q instanceof Error?Q.message:"Failed to load GSC inspection history")}finally{Re(!1)}}async function ua(v=!1){Qe(!0);try{const[Q,he]=await Promise.all([n.fetchQuery({...Lc({client:W,path:{name:t}}),staleTime:v?0:Ut}),n.fetchQuery({...qc({client:W,path:{name:t}}),staleTime:v?0:Ut}).catch(()=>[])]);pt(Q),xs(he)}catch(Q){pt(null),xs([]),Oe(Q instanceof Error?Q.message:"Failed to load coverage data")}finally{Qe(!1)}}async function Fn(v){it(!0),Oe(null);try{const Q=await Ci(t,{urls:v}),{succeeded:he,failed:be,total:Ze}=Q.summary;Te({title:"Indexing requested",detail:be===0?`${he} URL${he!==1?"s":""} submitted for indexing.`:`${he}/${Ze} submitted successfully, ${be} failed.`,tone:be===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(Q){Oe(Q instanceof Error?Q.message:"Failed to request indexing")}finally{it(!1)}}async function Xa(){it(!0),Oe(null);try{const v=await Ci(t,{urls:[],allUnindexed:!0}),{succeeded:Q,failed:he,total:be}=v.summary;Te({title:"Indexing requested",detail:he===0?`${Q} unindexed URL${Q!==1?"s":""} submitted for indexing.`:`${Q}/${be} submitted successfully, ${he} failed.`,tone:he===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(v){Oe(v instanceof Error?v.message:"Failed to request indexing")}finally{it(!1)}}async function Sn(){wt(!0),Oe(null);try{const v=await er(t);n.setQueryData(Ec({client:W,path:{name:t}}),v),Me(v.sitemaps),Tt(v.summary),De(v.preferredSubmissionUrls),Ae(new Set),We({}),v.sitemaps.length===0&&Ht("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(v){Oe(v instanceof Error?v.message:"Failed to list sitemaps")}finally{wt(!1)}}async function ma(v){const Q=S.has(v);if(Ae(he=>{const be=new Set(he);return Q?be.delete(v):be.add(v),be}),!(Q||ve[v])){st(he=>new Set(he).add(v));try{const he=await er(t,v);We(be=>({...be,[v]:he.sitemaps}))}catch(he){Oe(he instanceof Error?he.message:"Failed to load sitemap files")}finally{st(he=>{const be=new Set(he);return be.delete(v),be})}}}async function jt(v){if(!vs||v.length===0)return;const Q=[...new Set(v)];St(!0),Oe(null),qe({completed:0,total:Q.length});let he=0,be=0,Ze=0,nt=null;try{for(let It=0;It<Q.length;It+=50){const ct=Q.slice(It,It+50);try{const ke=await Dc(t,ct);he+=ke.summary.accepted,be+=ke.summary.failed,Ze+=ct.length,qe({completed:Ze,total:Q.length})}catch(ke){Ze+=ct.length;const Fs=ct.length,Gn=Q.length-Ze,fa=ke instanceof Error?ke.message:"The batch request failed",Ks=`${he} accepted, ${be} failed, ${Fs} unconfirmed, ${Gn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;nt=`Sitemap submission stopped after a batch request failed. ${Ks} ${fa}`,Oe(nt),Te({title:"Sitemap resubmission partially completed",detail:Ks,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const lt=Q.length;Te({title:be===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:be===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${he}/${lt} sitemap submissions; ${be} failed. Indexing is not guaranteed.`,tone:be===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Pe("")}catch(lt){Oe(lt instanceof Error?lt.message:"Failed to submit sitemap to Google")}finally{St(!1),qe(null),await Sn(),nt&&Oe(nt)}}async function Za(){St(!0);const v=Be??[];try{const Q=v.filter(be=>be.isSitemapsIndex),he=[];for(let be=0;be<Q.length;be+=4)(await Promise.all(Q.slice(be,be+4).map(async nt=>{const lt=ve[nt.path];if(lt)return lt;const It=await er(t,nt.path);return We(ct=>({...ct,[nt.path]:It.sitemaps})),It.sitemaps}))).forEach((nt,lt)=>{he.push(...nt.length>0?nt.map(It=>It.path):[Q[be+lt].path])});await jt([...v.filter(be=>!be.isSitemapsIndex).map(be=>be.path),...he])}catch(Q){Oe(Q instanceof Error?Q.message:"Failed to load sitemap files"),St(!1)}}async function ha(v){Jt(!0),Oe(null);try{await Oc(t,"gsc",v),await Nt(n,"google"),c(Q=>Q.map(he=>he.connectionType==="gsc"?{...he,sitemapUrl:v}:he)),Te({title:"Default sitemap updated",detail:v,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(Q){Oe(Q instanceof Error?Q.message:"Failed to set the default sitemap")}finally{Jt(!1)}}async function xa(v){try{await Dn.mutateAsync({projectName:t,projectLabel:t,opts:v?{sitemapUrl:v}:void 0})}catch{}}async function pa(){we(!0),Oe(null);try{const[v,Q]=await Promise.all([a?il().catch(()=>null):Promise.resolve(null),n.fetchQuery({...ai({client:W,path:{name:t}}),staleTime:Ut}).catch(()=>[])]);o(!!v?.google?.configured),c(Q);const he=Q.find(be=>be.connectionType==="gsc");await Promise.all([da(he),nn(),On(),wn(),ua(),he?.propertyId?Sn():Promise.resolve()])}finally{we(!1)}}l.useEffect(()=>{pa()},[t,s,a]),l.useEffect(()=>{ee(0),ce(null),le(v=>v.startDate||v.endDate?{...v,startDate:"",endDate:""}:v),_(v=>v+1),On()},[K]);const ga=l.useRef(!1);l.useEffect(()=>{if(!ga.current){ga.current=!0;return}ee(0),qt.setPage(1),nn(0)},[Y]);function Kn(v){const Q=X===v?null:v;ce(Q),le(he=>({...he,startDate:Q??"",endDate:Q??""})),_(he=>he+1)}const $=l.useRef(!1);l.useEffect(()=>{if(!$.current){$.current=!0;return}ee(0),nn(0)},[ns]);async function fe(){if(!r){Oe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}et(!0),Oe(null),Ht(null);try{let v=function(ke){if(ke.source!==be||ke.origin!==Ze||!ke.data||typeof ke.data!="object")return;const Fs=ke.data;Fs.type!==hx||Fs.connectionType!=="gsc"||ct(!0)};const{authUrl:Q,redirectUri:he}=await Mc(t,"gsc");if(!Q.startsWith("https://accounts.google.com/")){Oe("Unexpected OAuth redirect URL. Please try again.");return}const be=window.open(Q,"_blank","width=600,height=700");if(!be){window.location.assign(Q);return}const Ze=he?new URL(he).origin:window.location.origin;let nt=!1,lt=null;const It=()=>{lt!==null&&window.clearInterval(lt),window.removeEventListener("message",v)},ct=async ke=>{if(!nt){nt=!0,It(),Ht(ke?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Nt(n,"google"),await pa()}finally{Ht(null)}}};window.addEventListener("message",v),Ht("Finish the Google consent flow in the popup. This page will refresh automatically."),lt=window.setInterval(()=>{be.closed&&ct(!1)},1e3)}catch(v){Oe(v instanceof Error?v.message:"Failed to start OAuth flow")}finally{et(!1)}}async function Le(){Oe(null),Ht(null);try{await Tc(t,"gsc"),await Nt(n,"google"),c(v=>v.filter(Q=>Q.connectionType!=="gsc")),h([]),y("")}catch(v){Oe(v instanceof Error?v.message:"Failed to disconnect")}}async function es(){if(A){Ge(!0),Oe(null);try{await Uc(t,"gsc",A),await Nt(n,"google"),c(v=>v.map(Q=>Q.connectionType==="gsc"?{...Q,propertyId:A}:Q)),Te({title:"GSC property updated",detail:`${t} is now linked to ${A}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(v){Oe(v instanceof Error?v.message:"Failed to save GSC property")}finally{Ge(!1)}}}async function js(){Oe(null),Ht(null);try{await Os.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(L,10)||void 0,full:F||void 0}}),await Nt(n,"gsc")}catch{}}async function wi(){if(j.trim()){Ue(!0),Oe(null),Ht(null);try{const v=await Fc(t,j.trim());await Nt(n,"gsc"),D(v),C(""),await wn()}catch(v){Oe(v instanceof Error?v.message:"Failed to inspect URL")}finally{Ue(!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"})]})}),Kt&&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:Kt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Kt.message}),(Ts(Kt.enableUrl)||Ts(Kt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ts(Kt.enableUrl)&&e.jsx("a",{href:Ts(Kt.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 ↗"}),Ts(Kt.indexingApiUrl)&&e.jsx("a",{href:Ts(Kt.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:()=>Pt(null),children:"×"})]})}),At&&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:[At,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Oe(null),children:"×"})]}),vn&&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:[vn,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Ht(null),children:"×"})]}),Ee?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Rt?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-neutral",children:"Authorized"})]}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsx("code",{className:"text-secondary",children:Rt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",ie?.lastInspectedAt?Wt(ie.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ye(Le),children:"Disconnect"})]}):a?e.jsxs(ye,{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(ue,{tone:r?"caution":"negative",children:r?"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:r?"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:[r?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Se,onClick:Ye(fe),children:Se?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(As,{to:"/settings",children:"Open Settings"})}),!r&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}):e.jsx(ye,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:ux})}),(Rt||Ja)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ye,{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:`${gx(b?.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 ${Na.toLocaleString()} matching rows while the table shows ${Rs} per page.`})]}),b?.window?.startDate&&b.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[b.window.startDate," to ",b.window.endDate,(b.window.daysSinceLatestData??0)>0&&` · latest data ${b.window.daysSinceLatestData} day${b.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wa,{windows:mx,value:K,onChange:v=>{k(v),ee(0),qt.setPage(1)},label:"Search Console time period",formatOption:v=>v==="all"?"All":v}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:U,onClick:()=>{ee(0),qt.setPage(1),nn(0),On()},children:U?"Loading…":"Apply filters"})]})]}),b&&b.daily.length>0&&(()=>{const{totals:v,daily:Q,trends:he,periodComparison:be}=b,nt=Zi.filter(ke=>q.includes(ke.key)).map(ke=>({dataKey:ke.key,label:ke.label,color:ke.color,axisId:ke.key,inverted:ke.inverted,formatValue:ke.format,trend:ae?he?.[ke.key]??null:null})),lt=ke=>v[ke]??null,It=new Map(Q.map(ke=>[ke.date,ke])),ct=Q.length===0?[]:ah(Q[0].date,Q[Q.length-1].date).map(ke=>It.get(ke)??{date:ke});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Zi.map(ke=>{const Fs=q.includes(ke.key),Gn=lt(ke.key),fa=Gn===null;return e.jsxs("button",{type:"button","aria-pressed":Fs,disabled:fa,className:`rounded-md border px-3 py-2 text-left transition-colors ${Fs?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${fa?"cursor-not-allowed opacity-50":""}`,onClick:()=>{R(Ks=>Ks.includes(ke.key)?Ks.length===1?Ks:Ks.filter(mc=>mc!==ke.key):[...Ks,ke.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:Fs?ke.color:"transparent",border:`1px solid ${ke.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ke.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Gn===null?"—":ke.format(Gn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:px(be,ke.key,ke.inverted)})]},ke.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:ae,onChange:ke=>O(ke.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(wl,{data:ct,xKey:"date",series:nt,xTickFormatter:yn,labelFormatter:Vt,onSelectX:Kn,selectedX:X})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:Q.map(ke=>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":X===ke.date,onClick:()=>Kn(ke.date),children:[Vt(ke.date),": ",ke.clicks," clicks, ",ke.impressions," impressions"]},ke.date))}),X&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Vt(X)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Kn(X),children:["Show all ",v.days," days"]})]}),v.position!==null&&(v.positionDays??v.days)<v.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",v.positionDays," of ",v.days," days. The rest have no property-level position recorded."]}),(v.position===null||v.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:I.startDate,onChange:v=>le(Q=>({...Q,startDate:v.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:I.endDate,onChange:v=>le(Q=>({...Q,endDate:v.target.value}))}),e.jsx(Qs,{value:I.query,onChange:v=>le(Q=>({...Q,query:v})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Qs,{value:I.page,onChange:v=>le(Q=>({...Q,page:v})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),m.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(hn).map(v=>e.jsx("th",{className:"text-right","aria-sort":gt?.key===v?gt.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{qt.setPage(1),dt(Q=>Q?.key===v?Q.dir==="desc"?{key:v,dir:"asc"}:null:{key:v,dir:"desc"})},children:[Rc[v],gt?.key===v?gt.dir==="desc"?" ↓":" ↑":""]})},v))]})}),e.jsx("tbody",{children:Ps.map((v,Q)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:v.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:v.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(qa,{value:v.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:v.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(v.ctr)?v.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.position.toFixed(1)})]},`${v.date}:${v.query}:${v.page}:${Q}`))})]})}),e.jsx(qs,{page:xe?qt.page:Math.floor(T/Rs)+1,pageSize:Rs,visibleRows:Ps.length,totalRows:xe?J:void 0,hasNextPage:xe?void 0:Z,disabled:U,itemLabel:xe?"matches":"rows",onPageChange:v=>{if(xe){qt.setPage(v);return}const Q=(v-1)*Rs;ee(Q),nn(Q)}}),xe&&J>=Na?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Na.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(ye,{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:[ie&&ie.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:pe,onClick:()=>{Xa()},children:pe?"Requesting…":`Request indexing (${ie.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ut,onClick:()=>{ua(!0)},children:ut?"Loading…":"Reload saved coverage"})]})]}),ie&&ie.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const v=ie.summary.indexed+ie.summary.notIndexed,Q=v>0?ie.summary.indexed/v:0,he=v>0?ie.summary.notIndexed/v:0,be=54,Ze=2*Math.PI*be,nt=Ze*(1-Q),lt=Ze*he,It=Ze*Q;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:be,fill:"none",stroke:us.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:be,fill:"none",stroke:Es.positiveDeep,strokeWidth:"14",strokeDasharray:Ze,strokeDashoffset:nt,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),ie.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:be,fill:"none",stroke:us.textFaint,strokeWidth:"14",strokeDasharray:`${lt} ${Ze-lt}`,strokeDashoffset:-It,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:[(Q*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:ie.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:ie.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(ie.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(ie.reasonGroups??[]).length," ",(ie.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),ie.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:ie.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(v=>{const Q=v==="indexed"?ie.indexed.length:v==="notIndexed"?ie.notIndexed.length:ie.deindexed.length,he=v==="indexed"?"Indexed":v==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":at===v,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${at===v?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{fs(v),Zt(null)},children:[he," (",Q,")"]},v)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[at==="indexed"&&ie.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:as.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.crawlTime?v.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:v.isMobileFriendly===!0?"Yes":v.isMobileFriendly===!1?"No":"—"})]},v.id))})]}),at==="notIndexed"&&!ht&&(ie.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:(ie.reasonGroups??[]).map(v=>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:()=>Zt(v.reason),onKeyDown:Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),Zt(v.reason))},tabIndex:0,role:"button","aria-label":`View ${v.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:v.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.count})]},v.reason))})]}),at==="notIndexed"&&!ht&&(ie.reasonGroups??[]).length===0&&ie.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:ot.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.coverageState??"Unknown"})]},v.id))})]}),at==="notIndexed"&&ht&&(()=>{const v=(ie.reasonGroups??[]).find(Q=>Q.reason===ht);return v?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:()=>Zt(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:v.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[v.count," affected page",v.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:pe,onClick:()=>{Fn(v.urls.map(Q=>Q.url))},children:pe?"Requesting…":`Request indexing (${v.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:M.map(Q=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:Q.url}),e.jsx("td",{className:"text-secondary",children:Q.crawlTime?Q.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:pe,onClick:()=>{Fn([Q.url])},title:"Request indexing",children:"Index"})})]},Q.id))})]})]}):null})(),at==="deindexed"&&ie.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:bs.map((v,Q)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.previousState}),e.jsx("td",{className:"text-secondary",children:v.currentState}),e.jsx("td",{className:"text-secondary",children:v.transitionDate.split("T")[0]})]},`${v.url}-${Q}`))})]}),(at==="indexed"&&ie.indexed.length===0||at==="notIndexed"&&!ht&&ie.notIndexed.length===0||at==="deindexed"&&ie.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(qs,{page:je,pageSize:Gs,visibleRows:Math.min(Gs,Ne.length-Ie),totalRows:Ne.length,onPageChange:ps,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":zt,onClick:()=>ss(v=>!v),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:zt?"Hide snapshots":kt.length>0?`View ${kt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",ie.summary.indexed.toLocaleString()," indexed, ",ie.summary.notIndexed.toLocaleString()," not indexed.",G&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",G.indexed>=0?"+":"",G.indexed.toLocaleString()," indexed, ",G.notIndexed>=0?"+":"",G.notIndexed.toLocaleString()," not indexed."]})]}),zt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:kt.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:kt.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:v.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:v.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.notIndexed.toLocaleString()})]},v.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:ut?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(ye,{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(P,{type:"button",variant:"outline",size:"sm",disabled:Fe||!Rt?.propertyId,onClick:()=>{Sn()},children:Fe?"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:Ce,onChange:v=>Pe(v.target.value),onKeyDown:v=>v.key==="Enter"&&void jt([Ce.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!vs||yt||!Ce.trim(),onClick:()=>{jt([Ce.trim()])},children:yt?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!vs||yt||la.length===0,onClick:()=>{jt(la)},children:yt?"Resubmitting…":ca}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!vs||yt||!Be?.length,onClick:()=>{Za()},children:"Resubmit all files"}),tt&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",tt.indexes," index",tt.indexes===1?"":"es",", ",tt.files," file",tt.files===1?"":"s"]}),te&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",te.completed,"/",te.total]})]}),!vs&&Rt&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:Ye(fe),children:"Reconnect"})]}),Be&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:Be.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Qs,{value:Lt,onChange:v=>{Xe(v),Qt.setPage(1)},label:"Filter sitemaps",placeholder:"Filter sitemaps…"}),e.jsxs("table",{className:"data-table mt-3 w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Sitemap"}),e.jsx("th",{className:"text-left",children:"Type"}),e.jsx("th",{className:"text-left",children:"Google status"}),e.jsx("th",{className:"text-left",children:"Last submitted"}),e.jsx("th",{className:"text-left",children:"Last read"}),e.jsx("th",{className:"text-right",children:"Discovered URLs"}),e.jsx("th",{className:"text-left",children:"Issues"}),e.jsx("th",{className:"text-left",children:"Actions"})]})}),e.jsx("tbody",{children:Qt.rows.flatMap(v=>{const Q=eo(v),he=to(v),be=so(v),Ze=ve[v.path]??[],nt=S.has(v.path),lt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(qa,{value:v.path})}),e.jsx("td",{className:"text-secondary",children:v.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":nt,"aria-label":`${nt?"Collapse":"Expand"} files in ${v.path}`,onClick:()=>{ma(v.path)},children:vt.has(v.path)?"Loading…":`${nt?"▾":"▸"} Index${ve[v.path]?` (${Ze.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:be}),e.jsx("td",{className:"text-secondary",children:v.lastSubmitted?v.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:v.lastDownloaded?v.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Q.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:he||"—"}),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:!vs||yt,onClick:()=>{jt([v.path])},children:v.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Rt?.sitemapUrl===v.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:Yt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ha(v.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Dn.isPending,onClick:()=>{xa(v.path)},children:"Inspect URLs"})]})})]},v.path),It=v.isSitemapsIndex&&nt?Ze.map(ct=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(qa,{value:ct.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:so(ct)}),e.jsx("td",{className:"text-secondary",children:ct.lastSubmitted?ct.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ct.lastDownloaded?ct.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:eo(ct).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:to(ct)||"—"}),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:!vs||yt,onClick:()=>{jt([ct.path])},children:"Resubmit"}),Rt?.sitemapUrl===ct.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:Yt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ha(ct.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Dn.isPending,onClick:()=>{xa(ct.path)},children:"Inspect URLs"})]})})]},`${v.path}:${ct.path}`)):[];return[lt,...It]})})]}),e.jsx(qs,{page:Qt.page,pageSize:Rs,visibleRows:Qt.rows.length,totalRows:Qt.totalRows,onPageChange:Qt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(ye,{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:v=>C(v.target.value),onKeyDown:v=>v.key==="Enter"&&void wi()}),e.jsx(P,{type:"button",size:"sm",disabled:_e||!Rt?.propertyId||!j.trim(),onClick:Ye(wi),children:_e?"Inspecting…":"Inspect URL"})]}),N&&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:N.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:N.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:Si(N.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Wt(N.crawlTime)})]})]})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:H,onClick:()=>{wn(!0)},children:H?"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:z,onChange:v=>ne(v.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:H,onClick:()=>{wn(!0)},children:"Apply filter"})]}),x.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:x.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-neutral",children:v.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Si(v.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Wt(v.inspectedAt)})]},v.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(ye,{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"})]})}),f.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:f.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:v.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Wt(v.transitionDate)})]},`${v.url}:${v.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Rt&&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:()=>Xt(v=>!v),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 ${mt?"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"})]})}),mt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(ye,{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:A,disabled:Ke||d.length===0,onChange:v=>y(v.target.value),children:d.length===0?e.jsx("option",{value:"",children:Ke?"Loading properties…":"No properties available"}):d.map(v=>e.jsxs("option",{value:v.siteUrl,children:[v.siteUrl," · ",v.permissionLevel]},v.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Ke,onClick:()=>{da(Rt,!0)},children:Ke?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!A||He,onClick:Ye(es),children:He?"Saving…":"Save property"})]})]})]}),e.jsxs(ye,{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:L,onChange:v=>E(v.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:F,onChange:v=>V(v.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:Os.isPending||!Rt.propertyId,onClick:Ye(js),children:Os.isPending?"Queueing…":"Queue sync"}),!Rt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const yx=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function bx({projectName:t,projectId:s}){const n=ms(),[a,r]=l.useState(null),[o,i]=l.useState(null),[c,d]=l.useState(!1),h=$e(ai({client:W,path:{name:t}})),m=h.data?.find(J=>J.connectionType==="gbp"),u=!!m,b=a?{locationName:a}:void 0,p=$e({...Bc({client:W,path:{name:t}}),enabled:u}),x=$e({...Vc({client:W,path:{name:t},query:b}),enabled:u}),g=$e({...zc({client:W,path:{name:t},query:b}),enabled:u}),f=$e({...Qc({client:W,path:{name:t},query:b}),enabled:u}),w=$e({...Hc({client:W,path:{name:t},query:b}),enabled:u}),N=$e({...Wc({client:W,path:{name:t},query:b}),enabled:u}),D=$e({queryKey:["gbp-section-insights",t],queryFn:()=>Yc(t),enabled:u});function A(){Nt(n,"gbp")}const y=$t({...Jc(),onSuccess:J=>{ol({id:J.runId,projectId:s,kind:Ys["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Te({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),j=l.useSyncExternalStore(ll,Oa,Oa),C=Object.values(j.runs).some(J=>J.kind===Ys["gbp-sync"]&&J.projectId===s),L=y.isPending||C,E=$t({...Xc(),onSuccess:()=>A()});if(l.useEffect(()=>{if(!a||!p.data)return;const J=p.data.locations.filter(de=>de.selected);(J.length<=1||!J.some(de=>de.locationName===a))&&r(null)},[a,p.data]),l.useEffect(()=>{if(!o||!p.data)return;(a?[a]:p.data.locations.filter(de=>de.selected).map(de=>de.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(ye,{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((de,xe)=>e.jsxs("li",{className:"grid grid-cols-[1.5rem_1fr] gap-x-3",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full bg-mono-800 text-xs font-medium tabular-nums text-neutral","aria-hidden":"true",children:xe+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:de.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:de.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:de.note})]})]},de.title))})]})})}const F=x.data,V=p.data?.locations??[],K=V.filter(J=>J.selected),k=g.data?.keywords??[],q=f.data?.lodging??[],R=w.data?.placeActions??[],ae=N.data?.places??[],O=V.length>0?V[0].accountName:m.domain,X=a?V.find(J=>J.locationName===a)?.displayName??null:null,ce=a?V.filter(J=>J.locationName===a):K,Y=new Set(ce.map(J=>J.locationName)),_=q.filter(J=>Y.has(J.locationName)),I=R.filter(J=>Y.has(J.locationName)),le=ae.filter(J=>Y.has(J.locationName)),T=new Set(K.map(J=>J.locationName)),ee=a?k:k.filter(J=>T.has(J.locationName)),Z=!a&&K.length>1,ge=(D.data??[]).filter(J=>!J.dismissed&&yx.has(J.type)&&(!X||J.query===X||J.query===a||J.title.startsWith(X)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(ye,{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(ue,{tone:"positive",children:"Connected"}),!re()&&e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:L,onClick:()=>y.mutate({client:W,path:{name:t},body:{}}),children:L?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[O?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:O})," · "]}):null,p.data?`${p.data.totalSelected} of ${p.data.totalDiscovered} locations tracked`:"Loading locations…"]}),K.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"}),K.map(J=>e.jsx("option",{value:J.locationName,children:J.displayName},J.id))]})]}),K.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:[ge.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),ge.map(J=>e.jsx("div",{className:["insight-card",Tx(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))]}),F&&e.jsx(Ex,{performance:F.performance,freshness:F.freshness,timeseries:F.timeseries}),F?.profileCompleteness&&e.jsx(vx,{summary:F.profileCompleteness}),ce.length>0&&e.jsx(jx,{locations:ce,lodging:_,places:le,placeActions:I,expandedLocation:o,onToggleExpanded:J=>{i(de=>de===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"]})]}),ee.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"}),Z&&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:ee.slice(0,25).map(J=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:J.keyword}),Z&&e.jsx("td",{className:"text-muted",children:V.find(de=>de.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:()=>d(J=>!J),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",V.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:V.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!re()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:V.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(ue,{tone:J.selected?"positive":"neutral",children:J.selected?"Tracked":"Not tracked"})}),!re()&&e.jsx("td",{className:"text-right",children:e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:E.isPending,onClick:()=>E.mutate({client:W,path:{name:t,locationName:J.locationName},body:{selected:!J.selected}}),children:J.selected?"Untrack":"Track"})})]},J.id))})]})})]})]})})}function vx({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Un(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Un(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Un(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Un(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Un(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 ${$x(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function jx({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:o}){const i=new Map(s.map(h=>[h.locationName,h])),c=new Map(n.map(h=>[h.locationName,h])),d=new Map;for(const h of a){const m=d.get(h.locationName)??[];m.push(h),d.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:re()?"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=c.get(h.locationName)??null,b=d.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(ue,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ue,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Kl(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(wx,{location:h})}),e.jsx("td",{children:e.jsx(Sx,{lodging:m})}),e.jsx("td",{children:e.jsx(kx,{place:u,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(Px,{actions:b})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{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(Ix,{location:h,lodging:m,place:u,placeActions:b})})})]},h.id)})})]})})]})}function Nx(t){return[{label:"Description",tone:un(t.description)?"positive":"neutral",value:un(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:un(t.primaryPhone)?"positive":"neutral",value:un(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:un(t.websiteUri)?"positive":"neutral",value:un(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 wx({location:t}){const s=Nx(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ue,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Sx({lodging:t}){return e.jsx(oi,{...Cx(t)})}function Cx(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 kx({place:t,mapsUri:s}){return e.jsx(oi,{...Ax(t,s)})}function Ax(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 Px({actions:t}){return e.jsx(oi,{...Rx(t)})}function Rx(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 oi({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ue,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Ix({location:t,lodging:s,place:n,placeActions:a}){const r=s?Lx(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(xr,{title:"Owner profile · Business Information",children:[e.jsx(Gt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Gt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Gt,{label:"Description",value:un(t.description)?t.description:"Not returned"}),e.jsx(Gt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Gt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Gt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Gt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Gt,{label:"Open status",value:Kl(t.openStatus)}),e.jsx(Gt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(xr,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{label:"Last checked",value:no(s.syncedAt)}),e.jsx(Gt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Gt,{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(xr,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{label:"Places tier",value:n.tier}),e.jsx(Gt,{label:"Last checked",value:no(n.syncedAt)}),e.jsx(Gt,{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:[Ba(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Ba(o.providerType),o.uri?` · ${Mx(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function xr({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 Gt({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 Un(t,s,n){return t===s?"positive":t===0?n:"caution"}function $x(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Tx(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function un(t){return typeof t=="string"&&t.trim().length>0}function Kl(t){return t?Ba(t):"Not returned"}function Ba(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Mx(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function no(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Lx(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&qx(n)).map(([s])=>Ba(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function qx(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Ex({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Zc.filter(x=>(a[x]??0)>0),o=ed.filter(x=>(a[x]??0)>0),i=Object.keys(a).filter(x=>(a[x]??0)>0&&td(x)==="other").sort((x,g)=>(a[g]??0)-(a[x]??0)),c=Object.keys(a).filter(x=>(a[x]??0)===0).sort(),d=n.map(x=>{const g={date:x.date};for(const[f,w]of Object.entries(x.metrics))g[f]=w;return g}),h=n.find(x=>x.pending)?.date,m=n.length>0?n[n.length-1].date:void 0,u=d.length>0,b=s.dataThroughDate?`Data through ${Vt(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"}),b&&e.jsx("span",{className:"text-[11px] text-muted",children:b})]}),!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(ao,{data:d,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:[Fa(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(ao,{data:d,metrics:o,kind:"area",firstPending:h,lastDate:m})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(x=>Fa(x)).join(", ")]})]})}function ao({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn,minTickGap:24}),e.jsx(tn,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ts,labelFormatter:Vt,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),Fa(String(i??""))]}),e.jsx(Ua,{wrapperStyle:{fontSize:11,color:us.text},formatter:o=>Fa(o)}),a&&r&&e.jsx(Kr,{x1:a,x2:r,fill:us.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:us.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(Ls,{type:"monotone",dataKey:o,stroke:rt[i%rt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Bs,{type:"monotone",dataKey:o,stackId:"reach",stroke:rt[i%rt.length],fill:rt[i%rt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function Dx(t){return Sl(Ds(String(t)))}function Ox(t){return Hs(Ds(String(t)))}function pr({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(Fm,{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 wa=Rs;function Cn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function gr(t){return t.toLocaleString()}function Fx(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Kx(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 Gx(t){const s=t.filter(n=>n.kind===Ys["backlink-extract"]&&!cl(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function _x(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 Ux({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[o,i]=l.useState([]),[c,d]=l.useState(null),[h,m]=l.useState(null),[u,b]=l.useState(null),[p,x]=l.useState(Date.now()),[g,f]=l.useState(0),[w,N]=l.useState(!0),[D,A]=l.useState(!1),[y,j]=l.useState(null),C=l.useCallback(async()=>{N(!0),j(null);try{const[O,X,ce,Y,_]=await Promise.all([sd().catch(()=>null),nd(t,{excludeCrawlers:!0}).catch(()=>null),ad(t,{limit:wa,offset:g,excludeCrawlers:!0}).catch(le=>{if(le instanceof pn&&le.code==="NOT_FOUND")return null;throw le}),rd(t).catch(()=>[]),id(t).catch(()=>[])]);d(O),n(X),r(ce),i(Y);const I=Gx(_);m(I)}catch(O){j(O instanceof Error?O.message:"Failed to load backlinks")}finally{N(!1)}},[t,g]);l.useEffect(()=>{C()},[C]),l.useEffect(()=>{if(!h)return;const O=h.id;let X=!1;const ce=async()=>{try{const _=await Fr(O);if(X)return;cl(_.status)?(m(null),b(_),await C()):m(I=>I?.id===_.id?{...I,..._}:I)}catch{}},Y=window.setInterval(()=>{ce()},3e3);return()=>{X=!0,window.clearInterval(Y)}},[h,C]),l.useEffect(()=>{if(!h)return;const O=window.setInterval(()=>x(Date.now()),1e3);return()=>window.clearInterval(O)},[h]),l.useEffect(()=>{if(!u||u.status==="failed")return;const O=window.setTimeout(()=>b(null),1e4);return()=>window.clearTimeout(O)},[u]);async function L(){A(!0),j(null);try{const O=await ld(t);m(O)}catch(O){O instanceof pn&&O.code==="MISSING_DEPENDENCY"?j("DuckDB is not installed. Visit the Backlinks admin page to install it."):j(O instanceof Error?O.message:"Failed to trigger extract")}finally{A(!1)}}const E=l.useMemo(()=>o.slice().sort((O,X)=>O.queriedAt.localeCompare(X.queriedAt)).map(O=>({date:O.queriedAt,linkingDomains:O.totalLinkingDomains})),[o]),F=a?.rows??[],V=a?.total??0,K=s?.excludedLinkingDomains??0,k=Math.floor(g/wa)+1;return l.useEffect(()=>{g>0&&g>=V&&f(0)},[g,V]),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"})]})}),y&&e.jsx(ye,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:y})}),h&&e.jsx(ye,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Em,{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(ue,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[_x(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",p]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),u&&!h&&e.jsx(ye,{className:`surface-card p-4 mb-4 ${u.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[u.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(Dm,{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 ${u.status==="failed"?"text-negative":"text-positive"}`,children:u.status==="failed"?"Extract failed":"Extract complete"}),u.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:od(u.error)}):u.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),q()]});function q(){return w?e.jsx(ye,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):R()}function R(){const O=s!==null&&s.totalLinkingDomains>0,X=u?.status==="failed",ce=s!==null&&s.totalLinkingDomains===0&&!X,Y=c?.status==="ready",_=c?.status==="failed",I=c&&(c.status==="downloading"||c.status==="querying"||c.status==="queued");return O?ae(e.jsxs(e.Fragment,{children:[!re()&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:D||h!==null,onClick:Ye(L),children:[e.jsx(bl,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":D?"Queuing…":"Re-run extract"]}),e.jsx(pr,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!re()&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Open admin"})})]})):e.jsx(ye,{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(Om,{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."}),!re()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Set up backlinks"})})})]}),I&&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."]}),!re()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"View sync status"})})})]}),_&&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."}),!re()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Go to Backlinks admin"})})})]}),Y&&!I&&!ce&&!X&&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."]}),!re()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(P,{type:"button",size:"sm",disabled:D||h!==null,onClick:Ye(L),children:[e.jsx(_a,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":D?"Queuing…":"Run extract"]}),e.jsx(pr,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),X&&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."}),!re()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Go to Backlinks admin"})})})]}),ce&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!re()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:D||h!==null,onClick:Ye(L),children:[e.jsx(_a,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":D?"Queuing…":"Re-run extract"]}),e.jsxs(pr,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:s.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function ae(O){if(!s)return null;const X="Linking hosts",ce="linking hosts",Y="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:gr(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",ce]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:gr(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",ce," 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:Fx(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",ce," 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"})," · ",Y," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",Kx(s.queriedAt),K>0&&e.jsxs(e.Fragment,{children:[" · ",K," excluded domain",K===1?"":"s"]})]}),E.length>=2&&e.jsxs(ye,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:E,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:rt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:rt[0],stopOpacity:0})]})}),e.jsx(en,{dataKey:"date",tick:Ft,stroke:ds,tickFormatter:Dx}),e.jsx(tn,{tick:Ft,stroke:ds,allowDecimals:!1}),e.jsx(sn,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Ox}),e.jsx(Bs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:rt[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(ye,{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:X})]})}),e.jsxs("tbody",{children:[F.map(_=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:_.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:gr(_.numHosts)})]},_.linkingDomain)),F.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:K>0&&V===0?`Every referring domain in this ${Y} was a crawler/proxy host (${K} hidden).`:`No referring domains in this ${Y}.`})})]})]})}),e.jsx(qs,{page:k,pageSize:wa,visibleRows:F.length,totalRows:V,onPageChange:_=>f((_-1)*wa)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:O})]})}}function Bx({projectName:t}){const s=$e({...cd({client:W,path:{name:t}}),staleTime:ri}),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:ea(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:Bt()?"text-sm text-secondary":"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":Bt()?Js:"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(Vx,{data:n}),e.jsx(zx,{data:n}),n.competitorGaps.length>0&&e.jsx(Yx,{data:n})]})}function Vx({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(Sa,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Sa,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Sa,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(Sa,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function Sa({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 zx({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(Qx,{}),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(Ln,{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(vl,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Hx,{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 Qx(){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(Rn,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rn,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rn,{active:!1,tone:"cited"}),e.jsx(Rn,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Hx({provider:t}){const s=Wx(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Rn,{active:t.cited,tone:"cited"}),e.jsx(Rn,{active:t.mentioned,tone:"mentioned"})]})}function Wx(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 Rn({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 Yx({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(Ln,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const ro="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",fr="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",Bn=t=>t.kind==="project"?"Whole site":t.label,Vn={allMarkets:"All markets",browse:t=>`Browse ${t}`,select:t=>`Select ${t}`,browseAll:"Browse all properties"},Jx=t=>t?.kind==="group"&&t.marketKeys?.length===1?t.marketKeys[0]:void 0,io=t=>`${t} ${t===1?"property":"properties"}`;function Gl({options:t,selected:s,onSelect:n,marketKey:a,label:r="Measurement scope",allowGroupSelect:o=!0}){const i=[...t].sort((T,ee)=>T.label.localeCompare(ee.label,void 0,{numeric:!0})||T.id.localeCompare(ee.id)),[c,d]=l.useState(""),[h,m]=l.useState([]),[u,b]=l.useState(!1),p=l.useRef(null),x=l.useRef(null),g=l.useId(),f=i.filter(T=>T.kind==="group"),w=new Map(f.map(T=>[T.id,T])),N=w.get(h.at(-1)??""),D=w.get(h.at(-2)??""),A=c.trim().toLocaleLowerCase(),y=f.filter(T=>!T.parentGroupIds?.some(ee=>w.has(ee))),j=i.filter(T=>T.kind==="property"),C=T=>(T.parentGroupIds??[]).map(ee=>w.get(ee)?.label).filter(Boolean).join(" · "),L=T=>`${Bn(T)} ${C(T)}`.toLocaleLowerCase().includes(A),E=T=>{const ee=[...T.parentGroupIds??[]],Z=new Set;for(;ee.length;){const ge=ee.pop();if(ge===N?.id)return!0;Z.has(ge)||(Z.add(ge),ee.push(...w.get(ge)?.parentGroupIds??[]))}return!1},F=(u?[]:N?f.filter(T=>A?E(T):T.parentGroupIds?.includes(N.id)):A?f:y).filter(L),V=i.find(T=>T.kind==="market"&&T.id===(a??(s.kind==="market"?s.id:void 0))),K=N&&V&&(N.marketKeys?.includes(V.id)||V.parentGroupIds?.includes(N.id))?V.id:void 0,k=o?K??Jx(N):void 0,q=(N?j.filter(T=>T.parentGroupIds?.includes(N.id)&&(!k||T.marketKeys?.includes(k))):A||u||f.length===0?j:[]).filter(L),R=i.filter(T=>T.kind!=="market"||u||!o&&!N&&!A&&f.length>0||o&&N?.marketKeys?.length===1&&!A?!1:(N?A?E(T):T.parentGroupIds?.includes(N.id):A||!T.parentGroupIds?.some(Z=>w.has(Z)))&&L(T)),ae=N||u?[]:i.filter(T=>T.kind==="project"&&L(T));l.useEffect(()=>{const T=ee=>{p.current?.open&&ee.target instanceof Node&&!p.current.contains(ee.target)&&(p.current.open=!1)};return document.addEventListener("pointerdown",T),()=>document.removeEventListener("pointerdown",T)},[]);const O=T=>{p.current&&(p.current.open=!1,p.current.querySelector("summary")?.focus());const ee=o?T.kind==="property"?k:T.kind==="group"&&T.id===N?.id?K:void 0:void 0;ee?n(T,ee):n(T)},X=T=>{const ee=[];let Z=w.get(T.parentGroupIds?.[0]??"");for(;Z&&!ee.includes(Z.id)&&Z.id!==T.id;)ee.unshift(Z.id),Z=w.get(Z.parentGroupIds?.[0]??"");return[...ee,T.id]},ce=()=>{const T=s.kind==="group"?w.get(s.id):void 0,ee=w.get(V?.parentGroupIds?.[0]??""),Z=(s.parentGroupIds??[]).flatMap(de=>{const xe=w.get(de);return xe?[X(xe)]:[]}),ge=Z.find(de=>de.at(-1)===N?.id)??Z.sort((de,xe)=>xe.length-de.length)[0]??[],J=ee?X(ee):s.marketKeys?.length?[]:ge;m(T?X(T):J),b(s.kind==="property"&&J.length===0&&f.length>0),d("")},Y=T=>{m(X(T)),b(!1),d(""),x.current?.focus()},_=(T,ee=Bn(T))=>e.jsxs("div",{className:"flex items-stretch",children:[e.jsxs("button",{type:"button",className:fr,"aria-label":T.kind==="group"&&!o?Vn.browse(Bn(T)):Vn.select(Bn(T)),"aria-current":s.kind===T.kind&&s.id===T.id?"true":void 0,onClick:()=>T.kind==="group"&&!o?Y(T):O(T),children:[e.jsxs("span",{className:"min-w-0 break-words",children:[ee,A&&C(T)?e.jsx("span",{className:"block text-[13px] text-secondary",children:C(T)}):null]}),e.jsx("span",{className:"shrink-0 text-right text-[13px] text-secondary",children:T.kind==="market"?o?"Query context":"Market":T.kind==="property"?"Property":io(T.targetCount)})]}),o&&T.kind==="group"&&T.id!==N?.id&&i.some(Z=>Z.parentGroupIds?.includes(T.id))?e.jsx("button",{type:"button","aria-label":Vn.browse(T.label),title:`Browse ${T.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:()=>Y(T),children:e.jsx(Ga,{size:18,"aria-hidden":"true"})}):null]},`${T.kind}:${T.id}`),I=(T,ee)=>ee.length>0?e.jsxs("section",{"aria-label":T,className:"mt-2",children:[e.jsx("h3",{className:"px-2 py-2 text-[13px] font-medium text-secondary",children:T}),ee.map(Z=>_(Z))]}):null,le=(T,ee,Z)=>ee.length>0?e.jsxs("details",{open:Z,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:[T," (",ee.length,")"]}),ee.map(ge=>_(ge))]},`${N?.id??"root"}:${T}`):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:T=>{T.target===T.currentTarget&&T.currentTarget.open&&x.current?.focus()},onKeyDown:T=>{T.key==="Escape"&&(T.preventDefault(),T.currentTarget.open=!1,T.currentTarget.querySelector("summary")?.focus())},children:[e.jsxs("summary",{id:`${g}-value`,"aria-labelledby":`${g}-label ${g}-value`,className:`${ro} visibility-scope-trigger`,onClick:()=>{p.current?.open||ce()},children:[`${Bn(s)}${s.kind==="group"?` · ${io(s.targetCount)}`:s.kind==="property"?` · ${i.find(T=>T.kind==="market"&&T.id===a)?.label??(s.marketKeys?.length?Vn.allMarkets:"Property")}`:s.kind==="market"?" · Market":""}`,e.jsx(gn,{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:fr,"aria-label":`Back to ${D?.label??"all groups"}`,onClick:()=>{m(h.slice(0,-1)),b(!1),d(""),x.current?.focus()},children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Km,{size:16,"aria-hidden":"true"}),D?.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:ro,placeholder:N?"Search within this group":u?"Search properties":"Search groups or properties",value:c,onChange:T=>d(T.target.value)}),e.jsxs("div",{className:"mt-2 max-h-80 overflow-y-auto",children:[o&&N&&!A?_(N,"All properties in this group"):null,ae.map(T=>_(T)),N&&!A?le("Subgroups",F,!0):I(N?"Subgroups":"Groups",F),A?I("Properties",q):le(N&&F.length>0?"All properties":"Properties",q,!N||F.length===0),I("Markets",R),!N&&!u&&!A&&f.length>0&&j.length>0?e.jsxs("button",{type:"button",className:`${fr} mt-2 border-t border-default`,"aria-label":Vn.browseAll,onClick:()=>{b(!0),x.current?.focus()},children:[e.jsx("span",{children:"All properties"}),e.jsx(Ga,{size:18,"aria-hidden":"true"})]}):null,A&&F.length+q.length+R.length+ae.length===0?e.jsx("p",{className:"py-3 text-sm text-secondary",children:"No matching scopes."}):null]})]})]})]})}const ia="__cited__",oa="__mentioned__",cs="__mentionShare__";function _l(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Ds(n),end:Ds(a),sweepCount:s.sweepCount??1}}function Va(t){const s=_l(t);if(!s)return"Sweep date unavailable";const n=Hs(s.start),a=Hs(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Xx(t){const s=_l(t);return s?Sl(s.start):""}function En(t){return t.trim().toLowerCase()}function zr(t){return Math.round(t*1e3)/10}function Qr(t){return t.byProvider??{}}function Zx(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?ia:oa,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(u=>({date:u.startDate,[d]:zr(u[h])})),series:[d],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys(Qr(d))))].sort();return{rows:t.buckets.map(d=>{const h={date:d.startDate},m=Qr(d);for(const u of i){const b=m[u];h[u]=b?zr(b[o]):null}return h}),series:i,hasData:a,singleBucket:r}}function Ul(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function ep(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function tp(t){return t.servedModelAttribution??{}}function sp(t){return t.modelServiceMismatch??{}}function np(t){return t.modelPointerChanges??{}}function ap(t){return t.length>0?t.join(", "):null}function oo(t,s){const n=En(s);return Object.entries(t).find(([a])=>En(a)===n)?.[1]}function Is(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 rp(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!oo(Qr(a),s))continue;const r=Ul(a);return r?oo(r,s)??null:null}return null}function ip(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 op(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:ip(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function lp(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 cp(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 dp(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[cs]:r?.rate==null?null:zr(r.rate)}}),n=s.map(a=>a[cs]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[cs],hasData:n.length>0,singleBucket:n.length===1}}function up(t,s,n){return s==="mentionShare"?dp(t):Zx(t,s,n)}function lo(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 co(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function uo(t){return t>0?`+${t}`:`${t}`}function mp(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${uo(n.delta)} on ${co(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${uo(s.delta)} on ${co(s.date)})`}const hp=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],mo="Measured answers",$s={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},In="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 xp(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"?Et.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 pp={otherQueries:"Other queries"};function gp(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(" · ")||pp.otherQueries}return a.sort((r,o)=>r.marketLabel.localeCompare(o.marketLabel)||r.query.localeCompare(o.query))}function ho({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(Gm,{size:16,"aria-hidden":"true"}):e.jsx(vl,{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 xo({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 fp({group:t,advanced:s,targetLabels:n,marketHeading:a,onViewAnswers:r}){const o=t.rows[0],i=m=>JSON.stringify([...m.targetKeys].sort()),c=t.rows.every(m=>i(m)===i(o)),d=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&&c?e.jsx(xo,{targetKeys:o.targetKeys,labels:n}):null,d?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&&!c?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(xo,{targetKeys:m.targetKeys,labels:n})}):null,d?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(ho,{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(ho,{value:m.citationCoverage,singleAnswer:m.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(P,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${m.query} · ${m.provider}`,onClick:()=>r(m),children:[m.answerCount===1?"View answer":"View answers",e.jsx(Ga,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([m.provider,m.model,m.location])))]})}function yp({population:t}){const s=l.useId();let n=0;const a=t.trend.map((d,h)=>(h>0&&d.continuity.state!=="comparable"&&(n+=1),{createdAt:Date.parse(d.createdAt),[`mentioned-${n}`]:d.mentionCoverage.rate,[`cited-${n}`]:d.citationCoverage.rate})),r=Array.from({length:n+1},(d,h)=>h),o=new Set(t.trend.slice(1).map(d=>d.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(d=>d.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 c=t.trend.some(d=>d.mentionCoverage.rate!==null||d.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[c?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:rt[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:Es.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":`${$s[t.queryClass]} mention and citation trend`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:a,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:d=>new Date(Number(d)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(tn,{domain:[0,1],tick:Ft,tickLine:!1,axisLine:!1,width:48,tickFormatter:d=>Hr.format(Number(d))}),e.jsx(sn,{...ts,formatter:d=>typeof d=="number"?Hr.format(d):"Not measured",labelFormatter:d=>new Date(Number(d)).toLocaleDateString()}),r.map(d=>e.jsxs(l.Fragment,{children:[e.jsx(Ls,{type:"linear",dataKey:`mentioned-${d}`,name:"Mentioned",stroke:rt[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}}),e.jsx(Ls,{type:"linear",dataKey:`cited-${d}`,name:"Cited",stroke:Es.positive,strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}})]},d))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:c?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${$s[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(d=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(d.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(Cs,{value:d.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:d.citationCoverage})}),e.jsx("td",{children:d.continuity.state.replaceAll("-"," ")})]},d.runId))})]})})]})}function Wr(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function li(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,o=t.populations.find(h=>h.queryClass===r);if(o)return o;const i=Wr(a,s)??Wr(t,s),c=t.populations.find(h=>h.queryClass===i?.queryClass);if(c)return c;const d=["non-brand","branded","unknown"].map(h=>t.populations.find(m=>m.queryClass===h));return d.find(h=>h&&(h.summary.queryCount>0||h.trend.some(m=>m.queryCount>0)))??d.find(h=>h!==void 0)??t.populations[0]}function bp({report:t,onSelectionChange:s,queryClass:n=li(t).queryClass}){const{selection:a,scopeOptions:r,filterOptions:o}=t,i=(c,d,h,m)=>e.jsxs("label",{className:"min-w-0",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:c}),e.jsx("select",{"aria-label":c,className:In,value:h,onChange:u=>s({[d]: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(Gl,{options:r,selected:a.scope,marketKey:a.market?.id,onSelect:(c,d)=>{s({measurementScope:c.kind,measurementScopeKey:c.kind==="project"?void 0:c.id,measurementMarketKey:d})}}):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(c=>({value:c,label:c}))]),i("Search location","measurementLocation",a.location.kind==="exact"?a.location.value:a.location.kind==="none"?"none":"",[{value:"",label:"All locations"},...o.locations.filter(c=>c.kind!=="all").map(c=>({value:c.kind==="exact"?c.value:"none",label:c.kind==="exact"?c.value:"No location"}))])]})})}function vp({report:t,isRefreshing:s=!1,onSelectionChange:n,onManageQueries:a,onPage:r,onSearch:o,search:i="",queryKey:c,answerSelection:d,evidenceReport:h,isEvidenceLoading:m=!1,evidenceError:u,onRetryEvidence:b,onEvidencePage:p}){const x=l.useRef(null),g=l.useRef(void 0),f=li(t,c,d,h),w=h??t,N=w.populations.filter(k=>[...k.queries.items,...k.evidence.items].some(q=>q.queryKey===c)),D=d?[d.queryClass]:(N.length?N:m?[]:[f]).map(k=>k.queryClass),A=c?JSON.stringify([d??c,D]):void 0,y=l.useId();l.useEffect(()=>{if(!A){s||(g.current=void 0);return}if(g.current===A)return;const k=x.current?.querySelectorAll(`[aria-label="${mo}"]`);if(k?.length){for(const q of k){const R=q.closest("details[data-query-results]");R&&(R.open=!0)}k[0].focus({preventScroll:!0}),k[0].scrollIntoView?.({block:"start"}),g.current=A}},[A,s]);const{selection:j,filterOptions:C}=t,L=j.measurement,E=xp(j.scope),F=new Map(t.scopeOptions.filter(k=>k.kind==="property").map(k=>[k.id,k.label])),V=k=>{const q=w.populations.find(R=>R.queryClass===k.queryClass)?.evidence;return{items:q?.items.filter(R=>R.queryKey===c&&(!d||R.provider===d.provider&&R.model===d.model&&R.location===d.location&&(d.runId===null||R.runId===d.runId)))??[],nextCursor:q?.nextCursor}},K=(k,q,R,ae,O)=>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:`${y}-${q}`,className:"text-sm font-medium text-heading",children:k}),e.jsx(Ve,{text:O})]}),e.jsx("select",{id:`${y}-${q}`,className:In,value:R,onChange:X=>n({[q]:X.target.value||void 0,measurementQueryKey:void 0}),children:ae.map(X=>e.jsx("option",{value:X.value,children:X.label},X.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(ue,{tone:L.state==="measured"?"positive":"neutral",children:L.state==="measured"?"Complete":L.state==="partial"?"Partial":"Not measured"}),L.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:new Date(L.completedAt).toLocaleDateString()}):null]}),a?e.jsx(P,{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(P,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,e.jsx(bp,{report:t,queryClass:f.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:In,value:j.time.from?.slice(0,10)??"",onChange:k=>n({measurementFrom:k.target.value?`${k.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:In,value:j.time.to?.slice(0,10)??"",onChange:k=>n({measurementTo:k.target.value?`${k.target.value}T23:59:59.999Z`:void 0})})]}),K("AI model","measurementModel",j.model??"",[{value:"",label:"All models"},...Array.from(new Set(C.models.filter(k=>!j.provider||k.provider===j.provider).map(k=>k.model))).map(k=>({value:k,label:k}))],"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),K("Results from","measurementRunId",j.run.explicit?j.run.id??"":"",[{value:"",label:"Latest saved sweep"},...[...f.trend].reverse().map(k=>({value:k.runId,label:new Date(k.createdAt).toLocaleString()}))],"Choose a saved AI sweep to view its results. No new sweep starts.")]})]}),[f].map(k=>{const q=gp(k.queries.items,j.scope.kind==="property"&&!j.market&&k.queryClass==="non-brand"?new Map(t.scopeOptions.filter(R=>R.kind==="market").map(R=>[R.id,R.label])):void 0);return e.jsxs("section",{"aria-label":$s[k.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h2",{children:$s[k.queryClass]}),e.jsx(Ve,{text:k.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":k.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:k.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:k.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:k.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:k.summary.queryCount})]})]}),e.jsx(yp,{population:k}),j.mode==="advanced"?e.jsxs("details",{className:"border-t border-default text-sm text-secondary","aria-label":`${$s[k.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(([R,ae])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:k.summary.outcomes[R]}),e.jsx("span",{className:"text-sm text-secondary",children:ae}),R==="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]},R))})]}):null,j.mode==="advanced"&&j.scope.kind!=="property"&&(k.breakdown.groups.length>0||k.breakdown.properties.length>0)?e.jsx(jp,{population:k,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":k.queryClass,"aria-label":`${$s[k.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:[k.queries.total," ",k.queries.total===1?"result":"results"," · ",E]})]}),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 ${$s[k.queryClass]}`,placeholder:"Search queries",className:`${In} max-w-sm`,value:i,onChange:R=>o(R.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":`${$s[k.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"})})]})}),q.map((R,ae)=>e.jsx(fp,{group:R,marketHeading:R.marketLabel!==q[ae-1]?.marketLabel?R.marketLabel:void 0,advanced:j.mode==="advanced",targetLabels:F,onViewAnswers:O=>n({measurementQueryKey:O.queryKey,measurementAnswer:JSON.stringify({queryKey:O.queryKey,queryClass:k.queryClass,provider:O.provider,model:O.model,location:O.location,runId:j.run.id,revision:j.revision})})},R.queryKey))]})}),k.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:[q.length," ",q.length===1?"query":"queries"," · ",k.queries.items.length," ",k.queries.items.length===1?"engine result":"engine results"," shown of ",k.queries.total," results"]}),k.queries.nextCursor&&r?e.jsx(P,{variant:"outline",onClick:()=>r(k.queries.nextCursor),children:"Next queries"}):null,c&&D.includes(k.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":mo,"aria-busy":m,children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h3",{children:"Answers"}),e.jsx(P,{variant:"ghost",onClick:R=>{g.current=void 0,R.currentTarget.closest("details[data-query-results]")?.querySelector("summary")?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})},children:"Close answers"})]}),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]}),b?e.jsx(P,{variant:"outline",onClick:b,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[V(k).items.map(R=>e.jsxs("article",{className:"border-b border-default py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("strong",{className:"text-sm text-heading",children:R.provider}),R.model?e.jsx("span",{className:"text-sm text-secondary",children:R.model}):null,e.jsx("span",{className:"text-sm text-secondary",children:R.location??"No location"}),e.jsx("span",{className:"text-sm text-secondary",children:new Date(R.createdAt).toLocaleString()}),e.jsx(ue,{tone:"neutral",children:R.mentioned===null?R.mentionUnavailableReason==="identity-ambiguous"?Et.ambiguous:"Mention not checked":R.mentioned?"Mentioned":"Not mentioned"}),e.jsx(ue,{tone:"neutral",children:R.cited===null?"Citation not checked":R.cited?"Cited":"Not cited"})]}),e.jsx("h4",{className:"mt-3 text-sm font-medium text-heading",children:R.query}),e.jsx("p",{className:"mt-3 max-w-prose whitespace-pre-wrap text-sm leading-6 text-primary",children:R.answerText??"Answer text unavailable."}),e.jsx("ul",{className:"mt-3 space-y-2",children:R.sources.map(ae=>{const O=Ts(ae);return e.jsx("li",{className:"break-all text-sm",children:O?e.jsx("a",{href:O,target:"_blank",rel:"noreferrer",className:"text-link hover:underline",children:ae}):e.jsx("span",{className:"text-secondary",children:ae})},ae)})})]},R.answerId)),V(k).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:V(k).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,V(k).nextCursor&&p?e.jsx(P,{variant:"outline",onClick:()=>p(V(k).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"border-t border-default","aria-label":`${$s[k.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:k.competitorAvailability.state==="unavailable"?"Not available":`${k.competitors.length} measured`})]}),e.jsxs("div",{className:"pb-5",children:[k.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):k.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:k.competitors.map(R=>e.jsxs("tr",{children:[e.jsx("td",{children:R.domain}),e.jsx("td",{children:e.jsx(Cs,{value:R.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:R.citationCoverage})})]},R.domain))})]})}),k.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:k.observedCompetitors.map(R=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:R.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[R.answerCount," ",R.answerCount===1?"answer":"answers"]})]},R.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},k.queryClass)})]})}function jp({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),c=t.breakdown.groups.filter(u=>{const b=o.get(u.id)?.parentGroupIds??[];return s.kind==="project"?b.length===0:s.kind==="group"&&i?b.includes(s.id):!0}),[d,h]=l.useState(()=>s.kind==="project"&&c.length>0?"groups":"properties"),m=fn({rows:d==="groups"?c: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(P,{variant:d===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:`${In} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:d==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children: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:d==="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 ",d," match this search."]}):null,e.jsx(qs,{page:m.page,pageSize:m.pageSize,visibleRows:m.rows.length,totalRows:m.totalRows,itemLabel:d,onPageChange:m.setPage})]})}function Np({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,fallback:r,showUnmeasuredFallback:o=!1}){const[i,c]=l.useState(),[d,h]=l.useState(""),[m,u]=l.useState(),b=ms(),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=$e({...tr({client:W,path:{name:t},query:{...p,limit:25,cursor:i,search:d||void 0}}),staleTime:md,retry:!1,placeholderData:ni}),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),w=$e({...tr({client:W,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&&!Wr(x.data,s.queryKey)&&!w.data)return;const N=li(x.data,s.queryKey,s.answer,w.data);if(!i&&!d){const{queryKey:D}=tr({client:W,path:{name:t},query:{...p,queryClass:N.queryClass,limit:25}});b.setQueryData(D,{...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,w.data,n,b,t,p,i,d]),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=ea(x.error),D=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:D?"This saved group or property filter is unavailable for this measurement. Show the whole site to choose another.":N}),D?e.jsx(P,{variant:"outline",onClick:()=>{c(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:"Show whole site"}):e.jsx(P,{variant:"outline",onClick:()=>{c(void 0),x.refetch()},children:"Retry"})]})}return x.data?e.jsx("div",{"aria-busy":x.isFetching,children:e.jsx(vp,{report:x.data,isRefreshing:x.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:w.data,isEvidenceLoading:w.isFetching||!!s.queryKey&&w.isPending,evidenceError:w.error?ea(w.error):void 0,onRetryEvidence:()=>{w.refetch()},onEvidencePage:w.isFetching?void 0:N=>u({selection:f,cursor:N}),search:d,onSearch:N=>{h(N),c(void 0)},onPage:x.isFetching?void 0:c,onSelectionChange:N=>{(!("measurementQueryKey"in N)||Object.keys(N).some(D=>D!=="measurementQueryKey"&&D!=="measurementAnswer"))&&c(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 wp=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Sp=[{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."}],ci=rt[2],Cp="var(--chart-tooltip-bg)",kp={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function ks(t){const s=En(t);return kp[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Vs(t){return Math.round(t*10)/10}function Ap(t){return t===ia||t===oa||t===cs}function Bl(t){return t===ia?"Cited":t===oa?"Mentioned":t===cs?"Mention share":ks(t)}function Hn(t,s){return t===ia?Es.positive:t===oa?rt[1]:t===cs?ci:Qm(En(t),s)}function Pp(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Rp(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
|
-
`)}function Ya(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function Ea(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${Ya(s)}`:"Mention share":"Mentioned"}function aa(t){return t==="cited"?"citationRate":"mentionRate"}function Vl(t,s){return s==="cited"?t.cited:t.mentionedCount}function zl(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 Ql(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Yr(t){const s=Ul(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>En(a).localeCompare(En(r))).map(([a,r])=>`${ks(a)}: ${Is(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function Ip(t){return t.some(({event:s})=>s.to.status==="mixed")?Es.caution:t.some(({event:s})=>s.to.status==="unknown")?Es.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?rt[4]:Es.positive}function $p(t,s,n){const a=Ql(t,s);return a?Va(a):Hs(Ds(n))}function Tp({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:o,mismatch:i,buckets:c}){const d=l.useId(),h=Object.entries(o).sort(([u],[b])=>u.localeCompare(b)),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":d,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:d,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:b})=>b.map(({provider:p,event:x})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:$p(c,u,x.observedAt)}),e.jsxs("span",{children:[ks(p),": ",Is(x.from)," → ",Is(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:b})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Hs(Ds(b.observedAt))]}),e.jsxs("span",{children:[ks(u),": ",Is(b.from)," → ",Is(b.to),b.anchorObservedAt?` (last seen ${Is(b.from)} on ${Hs(Ds(b.anchorObservedAt))})`:""]})]},`before-${u}-${b.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,b])=>{const p=ap(b.latestServedModelIds),x=i[u];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Hs(Ds(b.latestObservation.observedAt))}),e.jsxs("span",{children:[ks(u),": ",p??Is(b.latestObservation.state),x?` — not the ${Is(x.configured)} you selected`:""]})]},`served-${u}`)})})]})]})}function po(t){return t===null?"no data":`${t}%`}function yr(t){return t==null?"undefined":`${Vs(t*100)}%`}function Mp({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=Ql(o,s);if(!i)return null;if(a==="mentionShare"){const d=i.mentionShare.projectMentionSnapshots,h=i.mentionShare.competitorMentionSnapshots,m=d+h,u=i.mentionShare.rate==null?null:Vs(i.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Va(i)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:ci},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",Ya(i.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:po(u)})]}),m>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",d," / ",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:Yr(i)})]})}const c=r==="byProvider"?(n??[]).filter(d=>d.dataKey!==void 0):[{dataKey:a==="cited"?ia:oa,value:Vs(i[aa(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Va(i)}),c.map((d,h)=>{const m=String(d.dataKey??d.name??""),u=r==="byProvider"?zl(i,m,a):null,b=u?.count??Vl(i,a),p=u?.total??i.total,x=typeof d.value=="number"?d.value:Vs(u?u.rate*100:i[aa(a)]*100),g=d.color??Hn(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:Bl(m)}),e.jsx("span",{className:"trend-tooltip-value",children:po(x)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[b," / ",p," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${m}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:Yr(i)})]})}function Lp({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:[Ea(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 c=o.mentionShare.projectMentionSnapshots,d=o.mentionShare.competitorMentionSnapshots,h=c+d,m=Ya(o.mentionShare.scope);i=h>0?`${yr(o.mentionShare.rate)} mention share for ${m}, ${c} of ${h} brand mentions were you`:`mention share undefined for ${m}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(c=>{const d=zl(o,c,s);return d?`${ks(c)} ${yr(d.rate)} ${Ea(s).toLowerCase()}, ${d.count} of ${d.total} snapshots`:`${ks(c)} no data`}).join("; "):i=`${yr(o[aa(s)])} ${Ea(s).toLowerCase()}, ${Vl(o,s)} of ${o.total} snapshots`;return i+=`; ${Yr(o)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Va(o)}),e.jsx("td",{children:i})]},o.startDate)})})]})}function br({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 c=s===i.value,d=i.description?`${o}-${i.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":c,"aria-describedby":d,className:`segmented-option ${c?"segmented-option-active":""}`,onClick:()=>n(i.value),children:i.label}),i.description&&e.jsx("span",{id:d,className:"sr-only",children:i.description})]},i.value)})})}function qp({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[o,i]=l.useState("mentioned"),[c,d]=l.useState("byProvider"),h=l.useMemo(()=>Rp(s),[s]),m=$e({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>dd(t,a),staleTime:ri}),u=m.data??null,b=m.error,p=o==="mentionShare"?"overall":c,x=l.useMemo(()=>u?up(u,o,p):null,[u,o,p]),g=u?ep(u):null,f=l.useMemo(()=>op(g??{}),[g]),w=l.useMemo(()=>lp(g??{}),[g]),N=l.useMemo(()=>cp(g??{}),[g]),D=l.useMemo(()=>Object.entries(g??{}).filter(([,_])=>_.anchorUnavailable).map(([_])=>_).sort(),[g]),A=l.useMemo(()=>u?tp(u):{},[u]),y=l.useMemo(()=>u?sp(u):{},[u]),j=l.useMemo(()=>u?ud(np(u)):null,[u]),C=o!=="mentionShare"&&p==="byProvider",L=u?.buckets??[],E=L[L.length-1]?.mentionShare.scope??u?.mentionShareScope??"pooled",F=Ea(o,E),V=o==="cited"?Es.positive:o==="mentionShare"?ci:rt[1],K=C?us.textDim:V,k=l.useMemo(()=>{const _=new Map(L.map(I=>[I.startDate,Xx(I)]));return I=>_.get(String(I))??""},[L]),q=o==="mentionShare"?x?lo(x.rows,cs):null:L.length>0?Vs(L[L.length-1][aa(o)]*100):null,R=o==="mentionShare"?x?Pp(x.rows,cs):null:L.length>0?Vs(L[0][aa(o)]*100):null,ae=o==="mentionShare"?x?.rows.filter(_=>typeof _[cs]=="number").length??0:L.length,O=q!==null&&R!==null&&ae>1?Vs(q-R):null,X=s.length,ce=e.jsxs(e.Fragment,{children:[j?.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:j.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:K},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:F}),C&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[q,"%"]}),O!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${O>0?"text-positive-400":O<0?"text-negative-400":"text-muted"}`,children:[O>0?"+":"",O.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(br,{options:Sp,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(br,{options:wp,value:c,onChange:d,ariaLabel:"Series"}),e.jsx(br,{options:hp,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let Y;if(b)Y=e.jsx("p",{className:"text-sm text-negative-400",children:ea(b)});else if(m.isLoading&&!u)Y=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(o==="mentionShare"&&X===0)Y=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!u||!x)Y=null;else{const{rows:_,series:I,hasData:le}=x,T=mp(u.queryChanges);if(!le)Y=e.jsx("p",{className:"text-sm text-secondary",children:o==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${Ya(E)} in this window yet.`:Bt()?Js:"Run a sweep to start tracking citations and mentions over time."});else if(C&&I.length===0)Y=e.jsxs("p",{className:"text-sm text-secondary",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-strong",children:"All engines"})," to see the trend."]});else{const ee=`${F} rate across ${_.length} ${_.length===1?"sweep":"sweeps"}. Latest ${q}%${O!==null?`, ${O>=0?"up":"down"} ${Math.abs(O).toFixed(1)} points over the period`:""}.`;Y=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:ee}),e.jsx(Lp,{buckets:L,metric:o,mode:p,series:I}),C&&I.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:I.map((Z,ge)=>{const J=lo(_,Z),de=rp(L,Z),xe=g===null?"Attribution unavailable":de?Is(de):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:Hn(Z,ge)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:Bl(Z)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),xe]})]}),J!==null&&e.jsxs("span",{className:"trend-legend-value",children:[J,"%"]})]},Z)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${F} trend chart over ${_.length} ${_.length===1?"bucket":"buckets"}`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:_,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:k,minTickGap:24}),e.jsx(tn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:Z=>`${Z}%`,tick:Ft,tickLine:!1,axisLine:!1,width:40}),e.jsx(sn,{cursor:{stroke:ds,strokeWidth:1},content:e.jsx(Mp,{metric:o,mode:p,buckets:L})}),f.buckets.map(({bucketStartDate:Z,events:ge})=>e.jsx(Zm,{x:Z,stroke:Ip(ge),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${Z}`)),I.map((Z,ge)=>e.jsx(Ls,{type:"monotone",dataKey:Z,name:Z,stroke:Hn(Z,ge),strokeDasharray:Z===cs?"5 4":void 0,strokeWidth:Ap(Z)?2.5:2,dot:Z===cs?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:Hn(Z,ge),strokeWidth:1.5}:{r:2.5,fill:Hn(Z,ge),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Cp},connectNulls:Z!==cs,isAnimationActive:!1},Z))]})})}),e.jsx(Tp,{partition:f,available:g!==null,counts:w,truncated:N,incompleteHistory:D,served:A,mismatch:y,buckets:L}),T&&e.jsx("p",{className:"visibility-trend-note",children:T})]})}}return e.jsxs("section",{className:"visibility-trend",children:[ce,Y]})}const go=new Set([Xn.queued,Xn.running]),Ot={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 fo({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:o,scopeError:i,onRetryScope:c,templates:d=[],viewerResearchConfig:h=null}){const m=ms(),{account:u,canWrite:b}=bn(),p=u?.role==="viewer"&&h!==null,x=!b,[g,f]=l.useState(""),[w,N]=l.useState(""),[D,A]=l.useState(null),[y,j]=l.useState([]),C=l.useRef(null),L=l.useRef(!1),[E,F]=l.useState(0),V=$e({...hd({client:W,path:{name:t}}),staleTime:6e4}),K=$e({...xd({client:W}),enabled:!x,staleTime:6e4}),k={client:W,path:{name:t},query:{limit:20}},q=Zo({...pd(k),initialData:void 0,initialPageParam:k,getNextPageParam:z=>z.nextCursor?{path:k.path,query:{...k.query,cursor:z.nextCursor}}:void 0,refetchInterval:z=>z.state.data?.pages.some(ne=>ne.runs.some(Ee=>go.has(Ee.status)))?3e3:!1}),R=q.isError&&!q.isFetchNextPageError,ae=q.data?.pages.at(-1),O=R?[]:[...new Map((q.data?.pages.flatMap(z=>z.runs)??[]).map(z=>[z.id,z])).values()],X=ae?.access?.canRun??(b||p),ce=ae?.access?ae.access.dailyRunLimit:p?h.viewerDailyRunLimit:null;l.useEffect(()=>{!D&&O[0]&&A(O[0].id)},[O,D]);const Y=O.find(z=>z.id===D)??null,_=$e({...gd({client:W,path:{name:t,runId:D??""}}),enabled:!R&&!!D,refetchInterval:Y&&go.has(Y.status)?3e3:!1}),I=R||_.isError?null:_.data??null,le=V.data?.locations??[],T=l.useMemo(()=>{if(x)return(ae?.providers??[]).map(ne=>({...ne,catalog:ne}));const z=new Map((K.data?.providerCatalog??[]).map(ne=>[ne.name,ne]));return(K.data?.providers??[]).filter(ne=>ne.configured&&z.get(ne.name)?.mode==="api").map(ne=>({...ne,catalog:{...z.get(ne.name),defaultModel:ne.model||z.get(ne.name).defaultModel}}))},[x,ae?.providers,K.data]),ee=!(x?q.isPending:K.isPending)&&T.length===0,Z=T.find(z=>z.name===g)??null;l.useEffect(()=>{if(!g&&V.data&&!V.isError&&!K.isError){const z=V.data.providers.find(ne=>T.some(Ee=>Ee.name===ne));f(z??T[0]?.name??"")}},[g,T,V.data,V.isError,K.isError]);const ge=Z?.catalog.modelConfigurable??!1,J=x?Z?.catalog.defaultModel:(Z?V.data?.providerModels[Z.name]:"")||Z?.catalog.defaultModel,de=(ge?w.trim():"")||J,xe=Z?[...new Map([{id:Z.catalog.defaultModel,displayName:Z.catalog.defaultModel},...w.trim()?[{id:w.trim(),displayName:w.trim()}]:[],...Z.catalog.knownModels].map(z=>[z.id,z])).values()]:[],se=$t({...fd(),onSuccess:async z=>{C.current=null,F(ne=>ne+1),j(z.runs),A(z.runs[0]?.id??null),await Vp(m),Te({title:"Research batch saved",detail:`${z.runs.length} ${z.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${z.runs.map(ne=>ne.id).join(":")}`,dedupeMode:"replace"})},onError:z=>{Te({title:"Could not start research",detail:z instanceof Error?z.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{L.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ep,{projectName:t,canWrite:b,researchAllowed:X&&!R,limitedAccess:x,isEmbed:re(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:o,scopeError:i,onRetryScope:c,templates:d,locations:le,defaultLocation:V.data?.defaultLocation??null,providerOptions:T,provider:g,onProviderChange:z=>{f(z),N("")},resolvedModel:de,visibilityModel:J,configurableModel:ge,model:w,onModelChange:N,modelOptions:xe,settingsReady:x?!q.isPending&&!R:!K.isPending&&!K.isError&&!K.isFetching,projectReady:!V.isPending&&!V.isError&&!V.isFetching,isPending:se.isPending,errorMessage:se.isError?"The request could not be confirmed.":void 0,onSubmit:(z,ne)=>{!X||R||re()||L.current||(C.current?.fingerprint!==ne&&(C.current={fingerprint:ne,key:crypto.randomUUID()}),L.current=!0,se.mutate({client:W,path:{name:t},body:{...z,idempotencyKey:C.current.key}}))}},`${t}:${E}`),ce!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",ce," 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(P,{variant:"outline",onClick:()=>{K.refetch()},children:"Retry providers"})]}):null,V.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(P,{variant:"outline",onClick:()=>{V.refetch()},children:"Retry locations"})]}):null,!(x?R:K.isError)&&ee&&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."}),y.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",y.map((z,ne)=>e.jsxs("span",{children:[ne>0?", ":"",e.jsxs("a",{href:`#research-run-${z.id}`,className:"text-link underline",onClick:()=>A(z.id),children:[z.scope?.label??"Whole site",z.location?`, ${z.location.label}`:", No location"]})]},z.id))]}),e.jsxs(ye,{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:Ot.historyTitle})}),q.isFetching&&e.jsx(ue,{tone:"neutral",children:"Loading"})]}),R?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(P,{variant:"outline",onClick:()=>{q.refetch()},children:"Retry history"})]}):q.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):O.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:Ot.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:O.map(z=>e.jsxs("tr",{className:D===z.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>A(z.id),children:_p(z.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:z.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:z.requestedModel??z.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:z.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:z.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[z.completedQueries+z.failedQueries,"/",z.totalQueries]}),e.jsx("td",{children:e.jsx(ue,{tone:Hl(z.status),children:z.status})})]},z.id))})]})}),q.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:Ot.historyMoreError}),q.hasNextPage&&e.jsx(P,{className:"mt-3",variant:"outline",disabled:q.isFetching,onClick:()=>{q.fetchNextPage()},children:q.isFetchingNextPage?Ot.historyLoading:Ot.historyMore})]})]}),!R&&_.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(P,{variant:"outline",onClick:()=>{_.refetch()},children:"Retry results"})]}):R?null:e.jsx(Kp,{detail:I,isLoading:_.isFetching,onReviewForTracking: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",$n="__none__";function Ep(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:o}=t,i=ms(),[c,d]=l.useState("once"),[h,m]=l.useState(""),[u,b]=l.useState(""),[p,x]=l.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[g,f]=l.useState(null),[w,N]=l.useState([]),[D,A]=l.useState(""),[y,j]=l.useState({}),[C,L]=l.useState(null),[E,F]=l.useState([]),[V,K]=l.useState(null),[k,q]=l.useState(!1),[R,ae]=l.useState(!1),[O,X]=l.useState(""),[ce,Y]=l.useState(""),_=l.useRef(null),I=l.useRef(!1),le=l.useRef(null),T=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";l.useEffect(()=>{x(T),L(null)},[T]);const ee=t.scopeOptions.filter(S=>S.kind==="market"||S.kind==="property"),Z=c==="markets"?"market":"property",ge=ee.filter(S=>S.kind===Z),J=S=>({kind:S.kind,key:S.id,label:S.label,planRevision:o??t.initialScope?.planRevision??0}),de=S=>S===$n?null:n.find(Ae=>Ae.label===S),xe=g??t.defaultLocation??$n,se=ee.find(S=>`${S.kind}:${S.id}`===p),z=se?J(se):null,ne=c==="once"?[{scope:z,location:de(xe)}]:c==="locations"?w.map(S=>({scope:null,location:de(S)})):w.map(S=>ge.find(Ae=>`${Ae.kind}:${Ae.id}`===S)).map(S=>S?{scope:J(S),location:de(y[`${S.kind}:${S.id}`]??$n)}:null),Ee=[...new Map([...E,...t.templates].map(S=>[S.id,S])).values()],we=C?Ee.find(S=>S.id===C.id):null,Se=C!==null&&we?.version!==C.version,et=c==="once"?h:u,Ke=et.split(/\r?\n/).filter(S=>S.trim()),ze=ki(Ke),He=[...new Set([...u.matchAll(/\{([^{}]+)\}/g)].map(S=>S[1]))],Ge=/[{}]/.test(u.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),U=[];Ke.length||U.push(c==="once"?"Enter at least one query.":"Enter at least one query pattern."),Ke.some(S=>S.length>4e3)&&U.push("Keep each query under 4,001 characters."),c!=="once"&&Ge&&U.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),ne.length||U.push(c==="locations"?"Select at least one location.":"Select at least one destination."),ne.some(S=>!S||S.location===void 0)&&U.push("A selected destination or location is no longer available. Update your selection.");const B=c==="once"&&p!=="project"||c==="markets"||c==="properties";B&&(t.scopePending||t.scopeError||!o||ne.some(S=>!S?.scope))&&U.push("Load the current published markets and properties before running scoped research.");const H=(c==="once"?ze.length:Ke.length)*ne.length;if(ne.length>ya&&U.push(`Select at most ${ya} destinations.`),H>nr&&U.push(`${H} queries selected. Reduce the selection to ${nr} or fewer.`),Se&&U.push("This saved pattern changed. Select its current version from Saved patterns."),c!=="once"&&!Ge){for(const S of ne)if(!(!S||S.location===void 0))try{sr(C??{pattern:u,variables:He},S.scope,S.location)}catch{U.push(`Choose a location for {location}, or use only variables available for ${c==="markets"?"markets":c==="properties"?"properties":"locations"}.`);break}}const Re=JSON.stringify({mode:c,source:et,contexts:ne,provider:a,resolvedModel:r,template:C,...B?{planRevision:o}:{}}),_e=V!==null&&V.signature!==Re,Ue=c==="once"?ze.map((S,Ae)=>({id:String(Ae),query:S,scope:z,location:ne[0]?.location??null})):V?.rows??[],ie=Fp(Ue),pt=[];c!=="once"&&V&&(_e&&pt.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),Ue.some(S=>!S.query.trim()||S.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(S.query))&&pt.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),Ue.some(S=>S.location&&!n.some(Ae=>JSON.stringify(Ae)===JSON.stringify(S.location)))&&pt.push("A preview location changed. Regenerate the preview."),ie.some(S=>ki(S.queries).length!==S.queries.length)&&pt.push("Remove duplicate queries within each destination and location."),ie.length>ya&&pt.push(`The preview exceeds ${ya} runs.`));const ut=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!U.length&&!pt.length&&(c==="once"||V!==null),Qe=()=>({runs:ie.map(S=>({queries:S.queries,provider:a,model:r,location:S.location,...S.scope?{scope:{kind:S.scope.kind,key:S.scope.key,expectedPlanRevision:S.scope.planRevision}}:{},...S.template?{template:S.template}:{}}))}),Fe=()=>{if(q(!0),U.length)return;const S=ne.flatMap((Ae,ve)=>Ke.map((We,vt)=>({id:`${ve}:${vt}`,scope:Ae.scope,location:Ae.location,...C?{template:{templateId:C.id,templateVersion:C.version,bindingLocation:Ae.location}}:{},query:sr({pattern:We,variables:[...new Set([...We.matchAll(/\{([^{}]+)\}/g)].map(st=>st[1]))]},Ae.scope,Ae.location).output})));K({signature:Re,rows:S})},wt=S=>{d(S),N([]),L(null),A(""),q(!1)},Be=S=>{if(Y(""),c==="once")try{m(sr(S,z,de(xe)).output)}catch{Y("Select a matching market, property, or location before using this pattern.");return}else b(S.pattern);L(S)},Me=S=>{const Ae=le.current,ve=Ae?.selectionStart??u.length,We=Ae?.selectionEnd??ve;b(`${u.slice(0,ve)}{${S}}${u.slice(We)}`),L(null),requestAnimationFrame(()=>{Ae?.focus(),Ae?.setSelectionRange(ve+S.length+2,ve+S.length+2)})},tt=$t({...bd(),onSuccess:async S=>{const Ae={id:S.id,version:S.updatedAt,label:S.name,pattern:S.pattern,variables:S.variables};F(ve=>[...ve.filter(We=>We.id!==S.id),Ae]),L(Ae),ae(!1),X(""),Y(""),_.current=null,await i.invalidateQueries({queryKey:yd({client:W,path:{name:s}})}),Te({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>Y("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{I.current=!1}}),Tt=()=>{if(!t.canWrite||t.isEmbed||I.current)return;const S=c==="once"?h:u,Ae=c==="once"?[]:He;if(!O.trim()||!S.trim()||S.length>4e3||c!=="once"&&Ge){Y("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const ve={name:O.trim(),pattern:S,variables:Ae},We=JSON.stringify(ve);_.current?.fingerprint!==We&&(_.current={fingerprint:We,id:crypto.randomUUID()}),I.current=!0,tt.mutate({client:W,path:{name:s,templateId:_.current.id},body:ve})},Mt=[...new Set([...k||et.trim()?U:[],...pt])],De=Ee.filter(S=>{const Ae=c==="once"?Ai(z,de(xe)):Ai(c==="markets"?{kind:"market",label:"Market"}:c==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return S.variables.every(ve=>Ae[ve]!==void 0)});return e.jsxs(ye,{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||tt.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:c,disabled:t.isPending,onChange:S=>wt(S.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!ee.some(S=>S.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!ee.some(S=>S.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),c==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(ee.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:S=>{x(S.target.value),L(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),p!=="project"&&!se&&e.jsx("option",{value:p,disabled:!0,children:"Selected destination unavailable"}),ee.map(S=>e.jsxs("option",{value:`${S.kind}:${S.id}`,children:[S.label," (",S.kind,")"]},`${S.kind}:${S.id}`))]})]}),e.jsx(Jr,{label:"Answer engine location",value:xe,locations:n,onChange:S=>{f(S),L(null)}})]}),c!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:c==="locations"?"Select locations":`Select ${c}`}),e.jsx("p",{className:"text-sm text-secondary",children:"Choose each destination explicitly. Each selected destination gets its own saved research run."}),e.jsx("input",{type:"search","aria-label":"Search destinations",className:Ss,placeholder:`Search ${c}`,value:D,onChange:S=>A(S.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(c==="locations"?n.map(S=>({key:S.label,label:S.label})):ge.map(S=>({key:`${S.kind}:${S.id}`,label:S.label}))).filter(S=>S.label.toLocaleLowerCase().includes(D.toLocaleLowerCase())).map(S=>{const Ae=w.includes(S.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:Ae,onChange:()=>N(ve=>Ae?ve.filter(We=>We!==S.key):[...ve,S.key])}),S.label]}),Ae&&c!=="locations"&&e.jsx(Jr,{label:`Answer engine location for ${S.label}`,value:y[S.key]??$n,locations:n,onChange:ve=>j(We=>({...We,[S.key]:ve}))})]},S.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[w.length," selected. A market or property name changes query text, not the answer engine's location."]})]}),t.scopeError&&e.jsxs("p",{className:"text-sm text-caution",children:["Markets and properties could not load. Whole-site and location research remain available. ",e.jsx(P,{variant:"outline",onClick:t.onRetryScope,children:"Retry destinations"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block",htmlFor:"research-query-editor",children:e.jsx("span",{className:"text-sm font-medium text-heading",children:c==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:c==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${c==="markets"?"market":c==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:le,className:`${Ss} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:et,placeholder:c==="once"?Ot.queryPlaceholder:c==="markets"?"Best apartments in {market}":c==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:S=>{c==="once"?m(S.target.value):(b(S.target.value),L(null))}}),c!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(P,{size:"sm",variant:"outline",onClick:()=>Me(c==="markets"?"market":c==="properties"?"property":"location"),children:["Insert ",c==="markets"?"market":c==="properties"?"property":"location"," name"]}),e.jsx("span",{className:"self-center text-sm text-secondary",children:"One pattern per line."})]}),e.jsxs("p",{id:"research-query-count",className:"mt-2 text-sm text-secondary",children:[H," / ",nr," queries",c==="once"?"":` across ${ne.length} destinations`]})]}),c!=="once"&&e.jsxs("details",{className:"border-t border-default pt-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading focus-visible:outline focus-visible:outline-2",children:["Saved patterns ",e.jsx("span",{className:"font-normal text-secondary",children:"(optional)"})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries."}),De.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:De.map(S=>e.jsx(P,{size:"sm",variant:"outline",onClick:()=>Be(S),children:S.label},S.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),C&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",C.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(P,{size:"sm",variant:"outline",onClick:()=>ae(!R),children:R?"Cancel save":"Save as a pattern"}),R&&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:O,maxLength:120,onChange:S=>X(S.target.value)})]}),e.jsx(P,{size:"sm",disabled:tt.isPending||!O.trim()||!et.trim(),onClick:Tt,children:tt.isPending?"Saving…":"Save pattern"})]})]}),ce&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:ce})]})]}),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:S=>t.onProviderChange(S.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose an answer engine"}),t.providerOptions.map(S=>e.jsx("option",{value:S.name,children:S.displayName??S.name},S.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:S=>t.onModelChange(S.target.value),children:[e.jsxs("option",{value:"",children:["Use AI Visibility model · ",t.visibilityModel]}),t.modelOptions.map(S=>e.jsx("option",{value:S.id,children:S.displayName},S.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:S=>t.onModelChange(S.target.value)}),e.jsx("datalist",{id:"research-known-models",children:t.modelOptions.map(S=>e.jsx("option",{value:S.id,children:S.displayName},S.id))})]})]})]}),Mt.length>0&&e.jsx(Op,{errors:Mt}),c!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:Fe,children:[e.jsx(ta,{size:14}),V?Ot.refreshPreview:"Preview queries"]}),V&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Queries to run"}),e.jsxs("p",{className:"text-sm text-secondary",children:[Ue.length," query executions in ",ie.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(Dp,{rows:Ue,locations:n,onChange:(S,Ae)=>K(ve=>ve&&{...ve,rows:ve.rows.map(We=>We.id===S?{...We,...Ae}:We)})})]})]}),t.errorMessage&&e.jsxs("p",{role:"alert",className:"text-sm text-negative",children:[t.errorMessage," Your entries are preserved. Retry unchanged entries to avoid duplicate work."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!t.isEmbed&&e.jsxs(P,{size:"sm",disabled:!ut,onClick:()=>{if(ut){const S=Qe();t.onSubmit(S,JSON.stringify({projectName:s,...S}))}},children:[e.jsx(_a,{size:14}),t.isPending?"Starting…":Ot.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[c==="once"?`${ze.length} queries`:`${Ue.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function Jr({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:$n,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function Dp({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(Jr,{label:`Location for query ${r+1}`,value:a.location?.label??$n,locations:s,onChange:o=>n(a.id,{location:s.find(i=>i.label===o)??null})})]},a.id))})}function Op({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 Fp(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 Kp({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(ye,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":Ot.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 ${Up(t.id)}`:Ot.resultsEmpty})]}),t&&e.jsx(ue,{tone:Hl(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:Ot.templateProvenance}),e.jsxs("dl",{className:"mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Saved pattern"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.template})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Names used"}),e.jsx("dd",{children:Object.entries(t.template.bindings).map(([i,c])=>`${i}: ${c}`).join(" · ")||"No variables"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Original resolved text"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.output})]})]}),e.jsx("p",{className:"mt-2",children:"The queries below are the final text sent to the answer engine, including any edits."}),e.jsxs("p",{className:"mt-2 font-mono text-xs",children:[t.template.templateId," · ",t.template.templateVersion]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:Ot.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:Ot.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(ue,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?Ot.brandedQuery:i.queryClass==="non-brand"?Ot.discoveryQuery:Ot.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(ue,{tone:Bp(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(ue,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===xn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===xn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(ue,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===xn.failed?"negative":"caution",children:i.citationState===null?i.status===xn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(Gp,{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 Gp({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})]}),!re()&&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 max-w-prose text-sm leading-6 text-secondary [&_h1]:text-base [&_h2]:text-base [&_h3]:text-sm",children:e.jsx(eh,{components:{p:({children:r})=>e.jsx("p",{className:"mb-3 whitespace-pre-wrap last:mb-0",children:r}),ul:({children:r})=>e.jsx("ul",{className:"mb-3 ml-5 list-disc space-y-1",children:r}),ol:({children:r})=>e.jsx("ol",{className:"mb-3 ml-5 list-decimal space-y-1",children:r}),pre:({children:r})=>e.jsx("pre",{className:"mb-3 overflow-x-auto whitespace-pre-wrap",children:r}),a:({children:r,href:o})=>{const i=Ts(o);return i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"text-link underline",children:r}):e.jsx("span",{children:r})},img:({alt:r})=>e.jsx("span",{children:r})},children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===xn.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=Ts(r.uri),c=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:c}):e.jsx("span",{className:"truncate text-secondary",children:c}),i&&e.jsx(_m,{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 _p(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 Up(t){return t.length>8?t.slice(0,8):t}function Hl(t){return t===Xn.completed?"positive":t===Xn.partial?"caution":t===Xn.failed?"negative":"neutral"}function Bp(t){return t===xn.completed?"positive":t===xn.failed?"negative":"neutral"}async function Vp(t){await Nt(t,"researchRuns")}const Xr=new Set(["queued","seeding","probing"]);function zp({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:o={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d}){const{account:h}=bn(),[m,u]=l.useState("tracked"),[b,p]=l.useState("find"),[x,g]=l.useState(null),f=h?.role==="viewer"?vd():null,w=h?.role!=="viewer"||f!==null,N=s??m,D=N==="research"&&!w?"tracked":N,A=a??b,y=L=>{s===void 0&&u(L),n?.(L)},j=L=>{a===void 0&&p(L),r?.(L)},C=(L,E)=>{const F=E===void 0?{...o}:{...o,measurementScope:E?.kind??"project",measurementScopeKey:E?.key};g({...L,trackingSelection:F}),E!==void 0&&i?.({measurementScope:F.measurementScope,measurementScopeKey:F.measurementScopeKey}),y("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(za,{active:D==="tracked",label:"Tracked",onClick:()=>y("tracked")}),w?e.jsx(za,{active:D==="research",label:"Research",onClick:()=>y("research")}):null]}),e.jsx("div",{className:"mt-4",children:D==="tracked"?e.jsx(xg,{projectName:t,selection:o,onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d,pendingTrackingSource:x,onPendingTrackingSourceHandled:()=>g(null)}):e.jsx(Qp,{projectName:t,selection:o,mode:A,onModeChange:j,onReviewSavedSource:C,onSelectionChange:i,viewerResearchConfig:f})})]})}function za({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 Qp({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:o}){const{canWrite:i}=bn(),c=!i||n==="test",d=$e({...dl({client:W,path:{name:t}}),enabled:c,staleTime:6e4}),h=$e({...ul({client:W,path:{name:t}}),enabled:c,staleTime:6e4}),m=l.useMemo(()=>{const p=d.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 w of f.targetKeys)x.get(w)?.push(f.stableKey);const g=new Map(p.markets.map(f=>[f.stableKey,new Set]));for(const f of p.markets)for(const w of f.usageEdges)for(const N of x.get(w.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 w=[...g.get(f.stableKey)??[]];return{id:f.stableKey,label:f.label,kind:"market",targetCount:0,...w.length?{parentGroupIds:w}:{}}}),...p.targets.map(f=>({id:f.stableKey,label:f.label,kind:"property",targetCount:1,...x.get(f.stableKey)?.length?{parentGroupIds:x.get(f.stableKey)}:{}}))]},[d.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]),b={projectName:t,scopeOptions:m,planRevision:d.data?.active?.revision??null,selectedScope:(()=>{const p=m.find(g=>g.kind===s.measurementScope&&g.id===s.measurementScopeKey),x=d.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:d.isPending||d.isFetching,scopeError:d.isError,onRetryScope:()=>{d.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(za,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(za,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(pg,{projectName:t,onReviewDiscoveryProbe:p=>r({source:"discovery",discoveryProbeId:p})}):e.jsx(fo,{...b,onReviewForTracking:({researchRunQueryId:p,scope:x})=>r({source:"research",researchRunQueryId:p},x??null)})})]}):e.jsx(fo,{...b,viewerResearchConfig:o})}function Hp({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:c,preview:d,isPreviewing:h,isCommitting:m,onPreview:u,onCommit:b}){const[p,x]=l.useState(null),[g,f]=l.useState(()=>Da(s)),[w,N]=l.useState(null),D=l.useRef(null),A=l.useRef(null),y=Xp(t,s),j=l.useMemo(()=>Zp(t.tracked,s,t.mode),[s,t.mode,t.tracked]),C=fn({rows:j,getSearchText:R=>`${R.queryText} ${R.provenance?.source??"legacy"} ${R.assignments.map(ae=>ae.queryClass??"unknown").join(" ")}`});l.useEffect(()=>{if(y)return;if(!a){A.current=null;return}const R=`${a}:${Nr(s)}`;if(A.current===R)return;const ae=t.tracked.find(O=>O.queryId===a);ae&&(A.current=R,x({kind:"edit",row:ae,audience:t.mode==="advanced"?vr(s):void 0,scopeLabel:jr(s,t)}),f(yo(ae,s)),N(null))},[s,a,y,t]),l.useEffect(()=>{if(y||!o)return;const R=Da(o.trackingSelection??s);x({kind:"add"}),f(o.source==="research"?{...R,source:"research",researchRunQueryId:o.researchRunQueryId}:{...R,source:"discovery",discoveryProbeId:o.discoveryProbeId}),N(null),i()},[i,o,s,y]),l.useEffect(()=>{y&&(x(null),N(null),a!==void 0&&r?.(void 0))},[r,a,y]),l.useEffect(()=>{if(!p||p.kind==="remove")return;const R=D.current;R&&(R.scrollIntoView?.({block:"start"}),R.focus({preventScroll:!0}))},[p]);function L(R="manual"){x({kind:"add"}),f({...Da(s),source:R}),N(null),r?.(void 0)}function E(R){A.current=`${R.queryId}:${Nr(s)}`,x({kind:"edit",row:R,audience:t.mode==="advanced"?vr(s):void 0,scopeLabel:jr(s,t)}),f(yo(R,s)),N(null),r?.(R.queryId)}function F(R){A.current=`${R.queryId}:${Nr(s)}`,x({kind:"remove",row:R,audience:t.mode==="advanced"?vr(s):void 0,scopeLabel:jr(s,t)}),N(null),r?.(R.queryId)}function V(){x(null),N(null),r?.(void 0)}const K=p?Wp(p,g,t.mode):null,k=p!==null&&p.kind==="add"&&t.mode==="advanced"&&!di(g),q=K!==null&&(!k||g.contexts.length>0)&&!h;return y?e.jsx("div",{className:"query-tracking-workspace space-y-4",children:e.jsxs("section",{"aria-label":"Tracked queries",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["This saved ",s.measurementScope," filter is unavailable in the current measurement."]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>n?.({measurementScope:"project",measurementScopeKey:void 0}),children:"Show whole site"})]})}):e.jsxs("div",{className:"query-tracking-workspace space-y-4",children:[e.jsxs("section",{"aria-label":"Tracked queries",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsx(tg,{workspace:t,selection:s,onSelectionChange:n}),t.mode==="advanced"?e.jsx(eg,{selection:s,onSelectionChange:n}):null,e.jsx(Qs,{value:C.query,onChange:C.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!re()&&e.jsxs(Je,{type:"button",size:"sm",onClick:()=>L(),children:[e.jsx(Um,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[C.totalRows.toLocaleString("en-US")," saved query ",C.totalRows===1?"record":"records"," in this view. Each record can have more than one property, group, or market assignment."]}),s.measurementScope==="group"?e.jsx("p",{className:"mt-1 text-xs leading-5 text-secondary",children:"Queries belong to properties, so a shared query can also cover other groups."}):null,t.active?null:e.jsx("p",{className:"mt-3 text-sm text-caution",children:"No published measurement yet."}),C.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:C.hasQuery?"No tracked queries match that search.":"No tracked queries in this scope yet."}):e.jsx("div",{className:"mt-5 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table min-w-[760px] table-auto",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Scope"}),t.mode==="advanced"?e.jsx("th",{children:"Class"}):null,e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Measurement"}),e.jsx("th",{className:"measurement-table-actions",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:C.rows.map(R=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:R.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(ng,{row:R,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(rg,{row:R})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:sg(R)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(ig,{row:R,outsidePlan:t.mode==="advanced"&&R.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!re()&&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 ${R.queryText}`,onClick:()=>E(R),children:[e.jsx(Bm,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(Je,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${R.queryText}`,onClick:()=>F(R),children:[e.jsx(jl,{"aria-hidden":"true",size:13})," Remove"]})]})})]},R.queryId))})]})}),e.jsx(qs,{page:C.page,pageSize:C.pageSize,visibleRows:C.rows.length,totalRows:C.totalRows,itemLabel:"queries",onPageChange:C.setPage})]}),p&&!re()&&e.jsx(og,{workspace:t,templates:c,action:p,draft:g,onDraftChange:R=>{f(R),N(null)},onClose:V,canReview:q,isPreviewing:h,editorHeadingRef:D,onReview:()=>{K&&(N(K),u(K))}}),d&&w&&p&&e.jsx(ug,{preview:d,workspace:t,isCommitting:m,onConfirm:()=>{b({...w,expectedWorkspaceVersion:d.workspaceVersion,previewToken:d.previewToken,reviewedAt:d.reviewedAt})}})]})}function Da(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 yo(t,s){return{...Da(s),text:t.queryText,queryClass:"keep"}}function Wp(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=Yp(s);if(!a||Zr(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=Jp(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!di(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function Yp(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 Jp(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 di(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function Zr(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function vr(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 Xp(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 jr(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 ui(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 Zp(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=>ui(r,s)))}function eg({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 Nr(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function tg({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 c of i.targetKeys)o.get(c)?.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(c=>c.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(Gl,{options:a,selected:r,onSelect:o=>{n?.({measurementScope:o.kind,measurementScopeKey:o.kind==="project"?void 0:o.id})}})}function sg(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 Wl(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 c=n?t.assignments.filter(g=>ui(g,n)):t.assignments,d=new Set(c.map(g=>g.targetKey));if(n?.measurementScope==="group"){const g=d.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 c)g.groupKeys.forEach(f=>h.add(f)),g.marketKeys.forEach(f=>m.add(f));const b=n?.measurementScope==="property"&&i.has(n.measurementScopeKey??"")?i.size===1?["This property only"]:["This property",`Shared with ${i.size-1} other ${i.size===2?"property":"properties"}`]:d.size===1?[a.get([...d][0])??[...d][0]]:[`${d.size} properties`],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?b.push(`${p} (group and market)`):(p?b.push(`Group: ${p}`):h.size>1&&b.push(`${h.size} groups`),x?b.push(`Market: ${x}`):m.size>1&&b.push(`${m.size} markets`)),b.join(" · ")}function ng({row:t,workspace:s,selection:n}){const a=ag(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:Wl(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 ag(t,s,n){const a=new Map(s.targets.map(d=>[d.stableKey,d.label])),r=new Map(s.groups.map(d=>[d.stableKey,d.label])),o=new Map(s.markets.map(d=>[d.stableKey,d.label])),c=t.assignments.filter(d=>ui(d,n)).map(d=>{const h=a.get(d.targetKey)??d.targetKey??"Whole site",m=n.measurementScope==="group"&&n.measurementScopeKey?d.groupKeys.filter(b=>b===n.measurementScopeKey).map(b=>r.get(b)??b):d.groupKeys.map(b=>r.get(b)??b),u=n.measurementScope==="market"&&n.measurementScopeKey?d.marketKeys.filter(b=>b===n.measurementScopeKey).map(b=>o.get(b)??b):d.marketKeys.map(b=>o.get(b)??b);return[h,m.length?`Groups: ${m.join(", ")}`:null,u.length?`Markets: ${u.join(", ")}`:null].filter(b=>b!==null).join(" · ")});return[...new Set(c)].length?[...new Set(c)]:["Whole site"]}function rg({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(ue,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function ig({row:t,outsidePlan:s=!1}){return s?e.jsx(ue,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(ue,{tone:"positive",children:"Measured"}):e.jsx(ue,{tone:"caution",children:"Awaiting sweep"})}function og({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:o,canReview:i,isPreviewing:c,editorHeadingRef:d,onReview:h}){const m=s.length>0;return n.kind==="remove"?e.jsxs(ye,{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(wr,{canReview:i,isPreviewing:c,onCancel:o,onReview:h})]}):n.kind==="edit"?e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Edit query"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick: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(wr,{canReview:i,isPreviewing:c,onCancel:o,onReview:h})]}):e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Add query"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick: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(lg,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(bo,{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(bo,{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(dg,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!di(a)?e.jsx("div",{className:"mt-4",children:e.jsx(cg,{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(wr,{canReview:i,isPreviewing:c,onCancel:o,onReview:h})]})}function lg({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":Zr(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]}),Zr(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 bo({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 mi(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function Wn(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 Yl(t){return[...new Map(t.map(s=>[Wn(s),s])).values()]}function hi(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 cg({workspace:t,draft:s,onDraftChange:n}){const a=l.useMemo(()=>Yl([...t.defaultContexts.map(mi),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?Wn(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(d=>Wn(d)===o.target.value),c=o.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:c})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(o=>e.jsx("option",{value:Wn(o),children:hi(o)},Wn(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 dg({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),c=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]),d=a.trim().toLocaleLowerCase(),h=d?c.filter(p=>`${p.label} ${p.detail}`.toLocaleLowerCase().includes(d)):c,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",w=s[f];n({...s,wholeSite:!1,[f]:g?[...w,x]:w.filter(N=>N!==x)})}function b(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(P,{type:"button",variant:"ghost",size:"sm","aria-label":"Change tracking destination",onClick:()=>i(!0),children:"Change"})]})]})}return e.jsxs("fieldset",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Choose where this question should be tracked."}),e.jsxs("label",{className:"mt-3 flex min-h-9 items-center gap-2 rounded px-1 text-sm text-strong",children:[e.jsx("input",{type:"checkbox",checked:s.wholeSite,onChange: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(Qs,{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:b(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 wr({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(P,{type:"button",variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),e.jsx("p",{className:"text-sm leading-5 text-secondary",children:"Publishing does not run a sweep."})]})}function ug({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=l.useRef(null);l.useEffect(()=>{const c=r.current;c&&(typeof c.scrollIntoView=="function"&&c.scrollIntoView({block:"start"}),c.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(c=>c.rows.length>0);return e.jsxs(ye,{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(ue,{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(c=>e.jsx(vo,{label:c.label,rows:c.rows,workspace:s,tracked:t.tracked},c.label))}):null,t.diff.unchanged.length>0?e.jsxs("details",{className:"mt-4 border-t border-default pt-2 text-sm text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3",children:[t.diff.unchanged.length," unchanged ",t.diff.unchanged.length===1?"query":"queries"]}),e.jsx(vo,{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 vo({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`:hg(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(mg,{row:a.find(o=>o.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function mg({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(d=>d.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",c=a.contexts.map(d=>hi(mi(d))).join("; ");return e.jsx("li",{children:[o,i,c].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function hg(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=Yl(a.assignments.flatMap(i=>i.contexts).map(mi)),o=r.length===1?hi(r[0]):r.length>1?`${r.length} contexts`:null;return[Wl(a,n),o].filter(i=>i!==null).join(" · ")}function xg({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i}){const c=ms(),[d,h]=l.useState(null),m=$e({...dl({client:W,path:{name:t}})}),u=$e({...ul({client:W,path:{name:t}}),staleTime:6e4}),b=$t({...Nd(),onSuccess:x=>h(x),onError:async x=>{h(null),await c.invalidateQueries({queryKey:jd({client:W,path:{name:t}})}),Te({title:"Could not review tracking changes",detail:x instanceof Error?x.message:"Update the draft and review it again.",tone:"negative"})}}),p=$t({...wd(),onSuccess:async x=>{h(null),r?.(void 0),await Pi(c,t),Te({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 Pi(c,t),Te({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(ye,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):m.isError||!m.data?e.jsxs(ye,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{m.refetch()},children:"Try again"})]}):e.jsx(Hp,{workspace:m.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:u.data?.templates??[],preview:d,isPreviewing:b.isPending,isCommitting:p.isPending,onPreview:x=>{h(null),b.mutate({client:W,path:{name:t},body:{...x,expectedWorkspaceVersion:m.data.workspaceVersion}})},onCommit:x=>p.mutate({client:W,path:{name:t},body:x})})}function pg({projectName:t,onReviewDiscoveryProbe:s}){const n=ms(),[a,r]=l.useState(null),[o,i]=l.useState(""),[c,d]=l.useState("100"),h=$e({...Sd({client:W,path:{name:t},query:{limit:"10"}}),refetchInterval:N=>N.state.data?.some(A=>Xr.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,b=$e({...Cd({client:W,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:u&&Xr.has(u.status)?3e3:!1}),p=b.data??null,x=$t({mutationFn:()=>{const N={},D=o.trim();D&&(N.icpDescription=D);const A=Number.parseInt(c,10);return Number.isFinite(A)&&A>0&&(N.maxProbes=A),kd(t,N)},onSuccess:async N=>{r(N.sessionId),i(""),await bg(n,t,N.sessionId),Te({title:"Discovery started",detail:`Run ${Sr(N.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${N.sessionId}`,dedupeMode:"replace"})},onError:N=>{Te({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 w(){try{const N=await h.refetch();if(N.error)throw N.error;const D=N.data?.length??0;Te({title:"Discovery sessions refreshed",detail:`${D} recent session${D===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(N){Te({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:re()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:h.isFetching,onClick:()=>{w()},children:[e.jsx(ta,{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(ye,{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(ue,{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:c,onChange:N=>d(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."})]}),!re()&&e.jsxs(Je,{type:"button",size:"sm",disabled:x.isPending,onClick:()=>x.mutate(),children:[e.jsx(_a,{size:14}),x.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(ye,{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(ue,{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:Sr(N.id)}),e.jsx(ue,{tone:jo(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(ye,{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?Sr(g.id):"No run selected"})]}),g&&e.jsx(ue,{tone:jo(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(Ca,{label:"Questions tested",value:g.probeCount??0}),e.jsx(Ca,{label:"Cited queries",value:g.citedCount??0,tone:"positive"}),e.jsx(Ca,{label:"Worth tracking",value:g.aspirationalCount??0,tone:"caution"}),e.jsx(Ca,{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(ye,{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(ye,{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"})]}),b.isFetching&&e.jsx(ue,{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(ue,{tone:gg(N.bucket),children:yg(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:!re()&&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 Ca({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 jo(t){return t==="completed"?"positive":t==="failed"?"negative":Xr.has(t)?"caution":"neutral"}function gg(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const fg={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function yg(t){return t?fg[t]:"Not classified"}function Sr(t){return t.length>8?t.slice(0,8):t}async function bg(t,s,n){await Promise.all([Nt(t,"discovery"),t.invalidateQueries({queryKey:Ad({client:W})})])}function No(t){return`${(t*100).toFixed(1)}%`}function vg({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),c=$e({...Pd({client:W,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=$e({...Rd({client:W,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(d.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??"",b=!!(u&&m&&u!==m),p=$e({...Id({client:W,path:{name:t},query:{run1:u,run2:m}}),enabled:s==="compare"&&b}),x=c.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,w])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===f,className:`filter-chip ${s===f?"filter-chip-active":""}`,onClick:()=>n(f),children:w},f))}),s==="changes"?e.jsx(th,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),c.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!c.isLoading&&x.length===0?e.jsxs(ye,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:Bt()?Js:"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:No(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:No(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))})]})]}),d.isLoading||p.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!d.isLoading&&h.length<2?e.jsxs(ye,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:Bt()?Js:"Run another answer visibility sweep before comparing historical evidence."})]}):null,p.data&&g.length===0?e.jsxs(ye,{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(ue,{tone:f.changed?"caution":"neutral",children:[f.run1State??"none"," → ",f.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(ue,{tone:f.visibilityChanged?"caution":"neutral",children:[f.run1MentionState??"none"," → ",f.run2MentionState??"none"]})})]},f.queryId??f.query??"unknown"))})]})}):null]}):null]})}const wo={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},jg={contract:null,assessment:null,googleAds:wo,gtm:wo,snapshots:[]};function Ng(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":kg(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function wg(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 Sg(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 Cg(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 Jl(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"&&Ag(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 kg(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Ag(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Xl(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 Pg(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 Rg(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 on(t){return t.length<=12?t:`…${t.slice(-10)}`}function Ig(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 $g(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 Cr={"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 So(t){return t.outcome==="pass"?{label:Cr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Cr[t.code],tone:"negative",outcome:"Fail"}:{label:Cr[t.code],tone:"caution",outcome:"Unknown"}}function Tg(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Mg(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 Lg(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function Co({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=Xl(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(ue,{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 ${Wt(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(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 qg="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.",Eg="Available once Google Ads and Tag Manager are connected.",Dg="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 Og({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:o}){const i=t.googleAds.state==="connected",c=t.gtm.state==="connected",d=t.googleAds.state==="unavailable",h=t.gtm.state==="unavailable",m=d||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."},b=!i&&!c,p=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:d?u:Sg(t)},{title:"Tag Manager",state:t.gtm.state,ready:c,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?u:Cg(t)}],x=i&&c&&!m?Jl(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."})]}),b?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:Dg}):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:qg})]}),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:Eg})]}),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"}:Xl(g.state),w=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(ue,{tone:f.tone,children:f.label}),g.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:g.summary}):null,w&&s?w.id==="retry-connection-status"?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(w.id),children:r?"Working…":w.label}):e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(w.id),children:r?"Working…":w.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 Fg({workspace:t=jg,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:o=null,onSelectContract:i,contractError:c=null,onRetryContracts:d,onRetryEvidence:h,onChangeGoogleAdsSelection:m,onChangeGtmSelection:u,onAddContract:b}){const p=Ng(t),x=wg(p),g=Jl(t),f=t.assessment?.findings??[],w=f.filter(y=>y.outcome!=="pass"),N=f.filter(y=>y.outcome==="pass"),D=w.some(y=>y.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&c===null?e.jsx(Og,{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(ue,{tone:x.tone,children:x.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Wt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children: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(y=>e.jsxs("li",{className:"break-words",children:[Lg(y)," ",y.kind,", captured ",Wt(y.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",y.id,")"]})]},y.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?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(P,{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(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):p==="runtime-unverified"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children: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&&b?e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:b,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:y=>i?.(y.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(y=>e.jsx("option",{value:y.id,children:y.name},y.id))]})]}):null,t.contract?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Website event"}),e.jsx("dd",{className:"mt-1 text-sm font-medium text-heading",children:t.contract.eventName})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Google Ads goal"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:Ig(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:$g(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:on(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:on(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:on(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:on(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),c?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:c}),d?e.jsx(P,{type:"button",variant:"outline",onClick:d,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),w.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(ue,{tone:D,children:[w.length," ",w.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:w.map(y=>{const j=So(y);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:j.label}),e.jsx(ue,{tone:j.tone,children:j.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",y.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",y.code]}),y.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",y.evidenceIds.join(", ")]}):null]},`${y.code}:${y.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(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(y=>{const j=Pg(y.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 ${j==="positive"?"bg-positive-fill":j==="caution"?"bg-caution-fill":j==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:y.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:y.detail}),e.jsx(ue,{tone:j,children:Rg(y.key,p)})]},y.key)})})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-connections-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection evidence"}),e.jsx("h3",{id:"conversion-integrity-connections-title",className:"text-base font-semibold text-heading",children:"Google Ads and Tag Manager"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads and Tag Manager connection and stored evidence state"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Connection"}),e.jsx("th",{scope:"col",children:"Selection"}),e.jsx("th",{scope:"col",children:"Stored evidence"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsxs("tbody",{children:[Co({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:m}:{},actionPending:n}),Co({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(P,{type:"button",variant:"outline",className:"mt-3",onClick:h,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:y.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:y.kind}),e.jsx("td",{className:"text-secondary",children:Wt(y.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:on(y.id)})]},y.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(y=>{const j=So(y);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:j.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",y.code]}),y.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",y.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(ue,{tone:j.tone,children:j.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:y.subject})]},`${y.code}:${y.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 ",Tg(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:on(t.contract.gtm.tagId)})," fires with ",Mg(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:on(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const ln=3e4,ko={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Dt="mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",ls="text-sm font-medium text-secondary";function Ao(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:ft(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function ka(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function Kg(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 Gg(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function _g(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:Gg(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 Ug(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:ka(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:ka(t.triggerIds),variableIds:ka(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:ka(t.productionHosts)}}}function Po(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 Aa(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 Pa(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Ra({id:t,label:s,value:n,onChange:a,children:r,disabled:o=!1}){return e.jsxs("label",{htmlFor:t,className:ls,children:[s,e.jsx("select",{id:t,className:Dt,value:n,onChange:i=>a(i.target.value),disabled:o,children:r})]})}function kn({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 Ro({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=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 b(){d(null),r(!0)}function p(){d(null),r(!1)}async function x(){i(!0),d(null);try{await n()}catch(g){d(ft(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(P,{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}`})]}),c?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:c}):null]}):e.jsxs(Je,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:b,children:["Disconnect ",t]})})}function Io({id:t,label:s,options:n,synced:a,loading:r,failed:o,onRetry:i,emptyHint:c,value:d,onChange:h}){const m=n.some(g=>g.id===d),[u,b]=l.useState(!1),p=u||d!==""&&!m&&n.length>0,x=e.jsx("label",{htmlFor:t,className:ls,children:s});return r?e.jsxs("div",{children:[x,e.jsx("select",{id:t,className:Dt,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):o?e.jsxs("div",{children:[x,e.jsx("input",{id:t,required:!0,className:Dt,value:d,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:Dt,value:d,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.":c})]}):e.jsxs("div",{children:[x,p?e.jsx("input",{id:t,required:!0,className:Dt,value:d,onChange:g=>h(g.target.value)}):e.jsxs("select",{id:t,required:!0,className:Dt,value:d,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:()=>{b(!p),h("")},children:p?"Choose from synced list":"Enter an ID manually"})]})}function Bg({projectId:t,projectName:s}){const n=bn(),[a,r]=l.useState(null),[o,i]=l.useState(null),[c,d]=l.useState(!1),[h,m]=l.useState(""),[u,b]=l.useState(null),[p,x]=l.useState(!1),[g,f]=l.useState(!1),[w,N]=l.useState(""),[D,A]=l.useState(""),[y,j]=l.useState(""),[C,L]=l.useState(""),[E,F]=l.useState(""),[V,K]=l.useState(!1),[k,q]=l.useState(ko),[R,ae]=l.useState(null),O=l.useRef(null),X=$e({...$d({client:W,path:{name:s}}),staleTime:ln}),ce=$e({...Td({client:W,path:{name:s}}),staleTime:ln}),Y=$e({...Md({client:W,path:{name:s}}),staleTime:ln}),_=$e({...Ld({client:W,path:{name:s}}),staleTime:ln}),I=_.data,le=$e({...qd({client:W,path:{name:s},query:{limit:5}}),staleTime:ln}),T=$e({...Ed({client:W,path:{name:s},query:{limit:5}}),staleTime:ln}),ee=Y.data??[],ge=(R?ee.find(M=>M.id===R)??null:null)??(ee.length===1?ee[0]??null:null),J=ee.length>1&&!ge,de=$e({...Dd({client:W,path:{name:s,contractId:ge?.id??""}}),enabled:!!ge,staleTime:ln}),xe=$e({...Od({client:W,path:{name:s}}),enabled:u==="google-ads"&&X.data?.connected===!0,staleTime:0}),se=$e({...Fd({client:W,path:{name:s}}),enabled:u==="gtm"&&ce.data?.connected===!0,staleTime:0}),z=$e({...Kd({client:W,path:{name:s,accountId:y}}),enabled:u==="gtm"&&!!y,staleTime:0}),ne=$e({...Gd({client:W,path:{name:s,accountId:y,containerId:C}}),enabled:u==="gtm"&&!!y&&!!C,staleTime:0}),Ee=$t(_d({client:W})),we=$t(Ud({client:W})),Se=$t(Bd({client:W})),et=$t(Vd({client:W})),Ke=$t(zd({client:W})),ze=$t(Qd({client:W})),He=$t(Hd({client:W})),Ge=$t(Wd({client:W})),U=$t(Yd({client:W}));l.useEffect(()=>{if(u!=="google-ads"||p||!X.isSuccess)return;const M=X.data.connection?.selection;N(M?.customerId??""),A(M?.loginCustomerId??""),x(!0)},[p,X.data,X.isSuccess,u]),l.useEffect(()=>{if(u!=="gtm"||g||!ce.isSuccess)return;const M=ce.data.selection;j(M?.accountId??""),L(M?.containerId??""),F(M?.workspaceId??""),f(!0)},[g,ce.data,ce.isSuccess,u]),l.useEffect(()=>{!R||!Y.data||Y.data.some(M=>M.id===R)||ae(null)},[Y.data,R]);const B=l.useMemo(()=>{const M=le.data?.snapshots??[],pe=T.data?.snapshots??[],it=[...M.map(Pt=>({id:Pt.id,provider:"google-ads",kind:Pt.kind,capturedAt:Pt.capturedAt})),...pe.map(Pt=>({id:Pt.id,provider:"gtm",kind:Pt.kind,capturedAt:Pt.capturedAt}))].sort((Pt,vn)=>vn.capturedAt.localeCompare(Pt.capturedAt)).slice(0,5),At=[],Oe=de.data?.googleAdsSnapshot,Kt=de.data?.gtmSnapshot;return Oe&&At.push({id:Oe.id,provider:"google-ads",kind:Oe.kind,capturedAt:Oe.capturedAt}),Kt&&At.push({id:Kt.id,provider:"gtm",kind:Kt.kind,capturedAt:Kt.capturedAt}),{contract:de.data?.assessment.contract??ge,assessment:de.data?.assessment??null,contractSelectionRequired:J,assessmentState:ge?de.isError?"unavailable":de.isLoading?"loading":void 0:void 0,assessmentError:de.isError?ft(de.error):null,googleAds:Kg(X.data,Ao(le.data?.total??0,le.isLoading,le.isError,le.error),X.isError),gtm:_g(ce.data,Ao(T.data?.total??0,T.isLoading,T.isError,T.error),ce.isError),snapshots:it,assessmentEvidenceSnapshots:At}},[ge,J,le.data,le.error,le.isError,le.isLoading,X.data,X.isError,T.data,T.error,T.isError,T.isLoading,ce.data,ce.isError,de.data,de.error,de.isError,de.isLoading]),H=l.useSyncExternalStore(ll,Oa,Oa),Re=Object.values(H.runs).some(M=>M.projectId===t&&(M.kind===Ys["google-ads-sync"]||M.kind===Ys["gtm-sync"])),_e=Ee.isPending||we.isPending||Se.isPending||et.isPending||Ke.isPending||ze.isPending||He.isPending||Ge.isPending||U.isPending||Re;async function Ue(){await Promise.all([X.refetch(),ce.refetch(),Y.refetch(),le.refetch(),T.refetch(),_.refetch(),ge?de.refetch():Promise.resolve()])}async function ie(M){await Ue();for(let pe=0;pe<10&&!M();pe+=1)await new Promise(it=>setTimeout(it,1500)),await Ue()}function pt(){const M=document.activeElement;O.current=M instanceof HTMLElement?M:null}function ut(M){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(M);return}globalThis.setTimeout(M,0)}function Qe(){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 wt(M,pe=M){const it=document.getElementById(M);it instanceof HTMLDetailsElement&&(it.open=!0);const At=it?.scrollIntoView;typeof At=="function"&&At.call(it,{behavior:Qe()?"auto":"smooth",block:"start"}),Fe(document.getElementById(pe)??it)}function Be(M,pe){pt(),ut(()=>wt(M,pe))}function Me(){const M=O.current;O.current=null,M&&ut(()=>{M.isConnected&&M.focus({preventScroll:!0})})}function tt(){r(null),d(!1),Me()}function Tt(){r(null),b(null),Me()}function Mt(){r(null),K(!1),Me()}function De(){r(null),b(null),d(!0),Be("google-ads-connect-panel","google-ads-connect-title")}function S(){r(null),N(""),A(""),x(!1),b("google-ads"),d(!1),Be("google-ads-selection-panel","google-ads-selection-title")}function Ae(){r(null),j(""),L(""),F(""),f(!1),b("gtm"),d(!1),Be("gtm-selection-panel","gtm-selection-title")}function ve(){r(null),K(!0),Be("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function We(M,pe){ol({id:M.id,projectId:M.projectId,kind:M.kind,projectLabel:s,sourceAction:pe}),Te({title:pe==="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 vt(){Ns(n),r(null);try{const M=await Ee.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});m(""),d(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Po(M.authorizationUrl,()=>{Ue(),i(null),Me()})}catch(M){r(ft(M))}}async function st(){Ns(n),r(null);try{const M=await we.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."),Po(M.authorizationUrl,()=>{Ue(),i(null),Me()})}catch(M){r(ft(M))}}async function Lt(){if(Ns(n),!w){r("Select a Google Ads customer before saving.");return}r(null);try{await Se.mutateAsync({path:{name:s},body:{customerId:w,...D.trim()?{loginCustomerId:D.trim()}:{}}}),b(null),Me(),await ie(()=>X.data?.selectedCustomer!=null)}catch(M){r(ft(M))}}async function Xe(){if(Ns(n),!y||!C){r("Select a Tag Manager account and container before saving.");return}r(null);try{await et.mutateAsync({path:{name:s},body:{accountId:y,containerId:C,...E?{workspaceId:E}:{}}}),b(null),Me(),await ie(()=>ce.data?.status==="connected")}catch(M){r(ft(M))}}async function te(){Ns(n),r(null),await He.mutateAsync({path:{name:s}}),b(null),d(!1),N(""),A(""),x(!1),i(null),await Ue(),Te({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),O.current=null,ut(()=>Fe(document.getElementById("conversion-integrity-title")))}async function qe(){Ns(n),r(null),await Ge.mutateAsync({path:{name:s}}),b(null),j(""),L(""),F(""),f(!1),i(null),await Ue(),Te({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),O.current=null,ut(()=>Fe(document.getElementById("conversion-integrity-title")))}async function Ce(){Ns(n),r(null);try{const M=await Ke.mutateAsync({path:{name:s}});We(M,"google-ads-sync")}catch(M){r(ft(M))}}async function Pe(){Ns(n),r(null);try{const M=await ze.mutateAsync({path:{name:s}});We(M,"gtm-sync")}catch(M){r(ft(M))}}async function Yt(){Ns(n),r(null);try{const M=await Promise.allSettled([Ke.mutateAsync({path:{name:s}}),ze.mutateAsync({path:{name:s}})]),[pe,it]=M;pe.status==="fulfilled"&&We(pe.value,"google-ads-sync"),it.status==="fulfilled"&&We(it.value,"gtm-sync");const At=M.find(Oe=>Oe.status==="rejected");if(At?.status==="rejected")throw At.reason}catch(M){r(ft(M))}}async function Jt(){Ns(n);const M=X.data?.connection?.selection.customerId,pe=ce.data?.selection;if(!M||!pe?.accountId||!pe.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const it=await U.mutateAsync({path:{name:s},body:Ug(k,M,{accountId:pe.accountId,containerId:pe.containerId})});q(ko),K(!1),Me(),(await Y.refetch()).data?.some(Oe=>Oe.id===it.id)&&ae(it.id)}catch(it){r(ft(it))}}function yt(M){switch(M){case"connect-google-ads":De();return;case"connect-gtm":pt(),st();return;case"select-google-ads":S();return;case"select-gtm":Ae();return;case"sync-google-ads":Ce();return;case"sync-gtm":Pe();return;case"sync-static-evidence":Yt();return;case"declare-contract":ve();return;case"review-findings":Be("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":Be("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Ue();return;case"select-contract":Be("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":de.refetch();return;case"waiting-for-integrity":return}}const St=xe.data?.customers??[],mt=se.data?.accounts??[],Xt=z.data?.containers??[],zt=ne.data?.workspaces??[],ss=!!w&&!St.some(M=>M.customerId===w),at=!!y&&!mt.some(M=>M.id===y),fs=!!C&&!Xt.some(M=>M.id===C),gt=!!E&&!zt.some(M=>M.id===E),dt=ss&&xe.isSuccess&&xe.data.truncated===!1,Ct=at&&se.isSuccess&&se.data.truncated===!1,ns=fs&&z.isSuccess&&z.data.truncated===!1,hs=gt&&ne.isSuccess&&ne.data.truncated===!1,qt=Ct||ns||hs,Ps=Ct?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":ns?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":hs?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,Qt=Pa(dt,xe.data,xe.isError),kt=Pa(Ct,se.data,se.isError),xs=Pa(ns,z.data,z.isError),ht=Pa(hs,ne.data,ne.isError),Zt=xe.isError?ft(xe.error):null,ys=se.isError?ft(se.error):z.isError?ft(z.error):ne.isError?ft(ne.error):null,ps=u==="google-ads"?Zt:u==="gtm"?ys:null,G=Aa("customer",xe.data,St.length),oe=Aa("account",se.data,mt.length),Ne=Aa("container",z.data,Xt.length),me=Aa("draft workspace",ne.data,zt.length),je=se.isError||z.isError||ne.isError&&!!E,Ie=c||u!==null||V;function as(){xe.refetch()}function ot(){if(se.isError){se.refetch();return}if(z.isError){z.refetch();return}ne.isError&&ne.refetch()}return X.isLoading||ce.isLoading||Y.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…"})]}):Y.isError&&!Y.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: ",ft(Y.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{Y.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Fg,{workspace:B,onPrimaryAction:yt,actionPending:_e,actionError:Ie?null:a,contracts:ee,selectedContractId:ge?.id??null,onSelectContract:M=>ae(M||null),contractError:Y.isError?ft(Y.error):null,onRetryContracts:()=>{Y.refetch()},onRetryEvidence:()=>{Promise.all([le.refetch(),T.refetch()])},onChangeGoogleAdsSelection:S,onChangeGtmSelection:Ae,onAddContract:()=>yt("declare-contract")}),o?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:o}):null,c?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:Ye(async M=>{M.preventDefault(),await vt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:ls,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:M=>m(M.target.value),className:Dt,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:Ee.isPending,children:Ee.isPending?"Starting…":"Continue to Google"}),e.jsx(P,{type:"button",variant:"outline",onClick:tt,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"})]})}),ps?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ps}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:as,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,dt?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(Ra,{id:"google-ads-customer",label:"Customer account",value:w,onChange:M=>{x(!0),N(M);const pe=St.find(it=>it.customerId===M);A(pe?.parentCustomerId??"")},disabled:xe.isLoading,children:[e.jsx("option",{value:"",children:xe.isLoading?"Loading accessible customers…":"Select a customer"}),ss?e.jsxs("option",{value:w,disabled:dt,children:["Saved customer ",w," (",Qt,")"]}):null,St.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:ls,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Dt,value:D,onChange:M=>{x(!0),A(M.target.value)},placeholder:"Use only when a manager context is required"})]})]}),G?e.jsx("p",{role:"status",className:`mt-3 text-sm ${xe.data?.truncated?"text-caution":"text-secondary"}`,children:G}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Je,{type:"button",disabled:Se.isPending||xe.isLoading||xe.isError||dt||!w,onClick:Ye(Lt),children:Se.isPending?"Saving…":"Save customer selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:Tt,children:"Cancel"})]}),X.data?.connected?e.jsx(Ro,{providerLabel:"Google Ads",disabled:_e,onDisconnect:te}):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"})]})}),ps?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ps}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:ot,children:se.isError?"Retry account list":z.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Ps?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Ps}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Ra,{id:"gtm-account",label:"Account",value:y,onChange:M=>{f(!0),M!==y&&(L(""),F("")),j(M)},disabled:se.isLoading,children:[e.jsx("option",{value:"",children:se.isLoading?"Loading accounts…":"Select an account"}),at?e.jsxs("option",{value:y,disabled:Ct,children:["Saved account ",y," (",kt,")"]}):null,mt.map(M=>e.jsx("option",{value:M.id,children:M.name},M.id))]}),e.jsxs(Ra,{id:"gtm-container",label:"Container",value:C,onChange:M=>{f(!0),M!==C&&F(""),L(M)},disabled:!y||z.isLoading,children:[e.jsx("option",{value:"",children:z.isLoading?"Loading containers…":"Select a container"}),fs?e.jsxs("option",{value:C,disabled:ns,children:["Saved container ",C," (",xs,")"]}):null,Xt.map(M=>e.jsx("option",{value:M.id,children:M.name},M.id))]}),e.jsxs(Ra,{id:"gtm-workspace",label:"Draft workspace (optional)",value:E,onChange:M=>{f(!0),F(M)},disabled:!C||ne.isLoading,children:[e.jsx("option",{value:"",children:ne.isLoading?"Loading workspaces…":"No draft workspace"}),gt?e.jsxs("option",{value:E,disabled:hs,children:["Saved draft workspace ",E," (",ht,")"]}):null,zt.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:[oe?e.jsx("p",{role:"status",className:se.data?.truncated?"text-caution":"text-secondary",children:oe}):null,Ne?e.jsx("p",{role:"status",className:z.data?.truncated?"text-caution":"text-secondary",children:Ne}):null,me?e.jsx("p",{role:"status",className:ne.data?.truncated?"text-caution":"text-secondary",children:me}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Je,{type:"button",disabled:et.isPending||se.isLoading||z.isLoading||ne.isLoading&&!!E||je||qt||!y||!C,onClick:Ye(Xe),children:et.isPending?"Saving…":"Save container selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:Tt,children:"Cancel"})]}),ce.data?.connected?e.jsx(Ro,{providerLabel:"Tag Manager",disabled:_e,onDisconnect:qe}):null]}):null,V?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:Ye(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:ls,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Dt,value:k.name,onChange:M=>q(pe=>({...pe,name:M.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:ls,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Dt,value:k.eventName,onChange:M=>q(pe=>({...pe,eventName:M.target.value})),placeholder:"booking_complete"})]}),e.jsx(Io,{id:"contract-conversion-action",label:"Google Ads conversion action",options:I?.googleAds.conversionActions??[],synced:I?.googleAds.syncedAt!=null,loading:_.isLoading,failed:_.isError,onRetry:()=>{_.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:k.conversionActionId,onChange:M=>q(pe=>({...pe,conversionActionId:M}))}),e.jsx(Io,{id:"contract-gtm-tag",label:"Tag Manager tag",options:I?.gtm.tags??[],synced:I?.gtm.syncedAt!=null,loading:_.isLoading,failed:_.isError,onRetry:()=>{_.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:k.tagId,onChange:M=>q(pe=>({...pe,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:ls,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Dt,value:k.conversionId,onChange:M=>q(pe=>({...pe,conversionId:M.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:ls,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Dt,value:k.conversionLabel,onChange:M=>q(pe=>({...pe,conversionLabel:M.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:ls,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Dt,value:k.triggerIds,onChange:M=>q(pe=>({...pe,triggerIds:M.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:ls,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Dt,value:k.variableIds,onChange:M=>q(pe=>({...pe,variableIds:M.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:ls,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Dt,value:k.campaignIds,onChange:M=>q(pe=>({...pe,campaignIds:M.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:ls,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Dt,value:k.productionHosts,onChange:M=>q(pe=>({...pe,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(kn,{id:"contract-primary-action",checked:k.requirePrimaryAction,onChange:M=>q(pe=>({...pe,requirePrimaryAction:M})),children:"Google Ads action is primary"}),e.jsx(kn,{id:"contract-biddable-goal",checked:k.requireBiddableGoal,onChange:M=>q(pe=>({...pe,requireBiddableGoal:M})),children:"Google Ads goal is biddable"}),e.jsx(kn,{id:"contract-runtime-verification",checked:k.verificationRequired,onChange:M=>q(pe=>({...pe,verificationRequired:M})),children:"Runtime proof is required"}),e.jsx(kn,{id:"contract-transaction-id",checked:k.requireTransactionId,onChange:M=>q(pe=>({...pe,requireTransactionId:M})),children:"Transaction ID is required"}),e.jsx(kn,{id:"contract-value",checked:k.requireValue,onChange:M=>q(pe=>({...pe,requireValue:M})),children:"Conversion value is required"}),e.jsx(kn,{id:"contract-currency",checked:k.requireCurrency,onChange:M=>q(pe=>({...pe,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:U.isPending,children:U.isPending?"Saving…":"Save conversion contract"}),e.jsx(P,{type:"button",variant:"outline",onClick:Mt,children:"Cancel"})]})]})]}):null]})}const Vg=6e4,zg=["7d","14d","30d"],xi="not available",Qg='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%.',Hg="No Google Ads snapshot stored yet",Wg="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.",Yg="No closed days yet",Jg="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.",Xg={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},_s=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),kr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Zl=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),Zg=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function An(t,s){return t===null||!Number.isFinite(t)?xi:s===null?Zg.format(t/1e6):gh(t,s)}function Ar(t){if(t===null||!Number.isFinite(t))return xi;const s=t*100;return s>0&&s<.1?"<0.1%":`${Zl.format(s)}%`}function ef(t,s){if(t===null||!Number.isFinite(t))return`${xi} 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%":`${Zl.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function tf(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function sf(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function nf(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 af({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=$e({...Jd({client:W,path:{name:t},query:{window:s}}),staleTime:Vg}),i=o.data,c=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Ve,{text:Qg})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Vt(i.startDate)," to ",Vt(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(Wa,{windows:zg,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:[c,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(y=>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"})]},y))}),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:[c,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",ft(o.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{o.refetch()},children:"Retry performance"})]});const{totals:d,daily:h,campaigns:m,comparison:u,comparisonUnavailableReason:b,source:p}=i;if(!p){const y=b==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:y?Yg:Hg}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:y?Jg:Wg})]})]})}const x=p.currencyCode,g=p.campaignsInInventory>0&&p.campaignsQueried<p.campaignsInInventory?{queried:p.campaignsQueried,inInventory:p.campaignsInInventory}:null,f=d.costMicros>0&&d.conversions===0,w=[{key:"spend",comparable:!0,label:"Spend",value:An(d.costMicros,x),change:u?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:kr.format(d.conversions),change:u?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:f?"no conversions":An(d.costPerConversionMicros,x),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Ar(d.conversionRate),change:u?.change.conversionRate??null,direction:"up-good",seriesKey:null}],N=[{key:"clicks",label:"Clicks",value:_s.format(d.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:_s.format(d.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Ar(d.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:An(d.cpcMicros,x),seriesKey:null}],D={costMicros:{label:"Spend",color:rt[1],axisId:"spend",formatValue:y=>An(y,x)},conversions:{label:"Conversions",color:rt[0],axisId:"conversions",formatValue:y=>kr.format(y)},clicks:{label:"Clicks",color:rt[2],axisId:"clicks",formatValue:y=>_s.format(y)},impressions:{label:"Impressions",color:rt[3],axisId:"impressions",formatValue:y=>_s.format(y)}},A=[...a].map(y=>({dataKey:y,...D[y]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,g!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",_s.format(g.queried)," of"," ",_s.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&&b==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:Xg["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:w.map(y=>{const j=y.seriesKey!==null&&a.has(y.seriesKey),C=j&&a.size===1,L=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[y.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:j?D[y.seriesKey].color:"var(--color-mono-600)"}}):null,y.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:y.value}),u&&y.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${nf(y.change,y.direction)}`,children:ef(y.change,u.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:y.comparable?`no prior ${s} period stored`:" "})]});return y.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:L},y.key):e.jsx("button",{type:"button","aria-pressed":j,disabled:C,onClick:()=>r(E=>{const F=new Set(E);return F.has(y.seriesKey)?F.delete(y.seriesKey):F.add(y.seriesKey),F.size===0?E:F}),className:`rounded-md border px-3 py-2 text-left transition-colors ${j?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${C?"cursor-default":""}`,children:L},y.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(y=>{const j=y.seriesKey!==null&&a.has(y.seriesKey),C=j&&a.size===1,L=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[y.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:j?D[y.seriesKey].color:"var(--color-mono-600)"}}):null,y.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:y.value})]});return y.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:L},y.key):e.jsx("button",{type:"button","aria-pressed":j,disabled:C,onClick:()=>r(E=>{const F=new Set(E);return F.has(y.seriesKey)?F.delete(y.seriesKey):F.add(y.seriesKey),F.size===0?E:F}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${C?"cursor-default":"hover:bg-surface-hover"}`,children:L},y.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(wl,{data:h,xKey:"date",series:A,xTickFormatter:yn,labelFormatter:Vt}),e.jsx("ul",{className:"sr-only",children:h.map(y=>e.jsxs("li",{children:[Vt(y.date),":"," ",A.map(j=>`${j.label} ${D[j.dataKey].formatValue(y[j.dataKey])}`).join(", "),y.origin==="filled"?", no delivery reported":""]},y.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(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:y.name??y.campaignId,children:y.name??e.jsx("span",{className:"font-mono text-secondary",children:y.campaignId})}),e.jsx("td",{children:e.jsx(ue,{tone:tf(y.status),children:sf(y.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:_s.format(y.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:_s.format(y.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:An(y.totals.costMicros,x)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:kr.format(y.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ar(y.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:y.totals.costMicros>0&&y.totals.conversions===0?e.jsx(ue,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:An(y.totals.costPerConversionMicros,x)})})]},y.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Hs(Ds(p.capturedAt))," · ","customer ",p.customerId," · ","latest closed day ",Vt(p.asOfDate),p.openDate?e.jsxs(e.Fragment,{children:[" · ",Vt(p.openDate)," still open, excluded"]}):null,p.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",p.timeZone]}):null]})]})]})}const Pr=20,Ms=50,rf=50,of=50;function pi(t){return t==="viewer"}function gi(t){return t?.status==="unavailable"}function ec(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function tc(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 Ia(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 lf(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 Rr(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 To(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 $a(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 ei(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Ir(t){return ei(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ti({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[o,i]=l.useState(""),[c,d]=l.useState(!1),h=o.trim().toLocaleLowerCase(),m=h?t.filter(x=>x.label.toLocaleLowerCase().includes(h)):t,u=c?m:m.slice(0,rf),b=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(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:u.length===0,onClick:p,children:"Select all shown"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),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(ec(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)})}),b?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function fi(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(ue,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function yi({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(ue,{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 cf({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,i]=l.useState(null),c=t.preview,d=c?.counts.needsAttention??0,h=c?.rows.filter(C=>C.status==="matched")??[],m=c?.rows??[],u=m.filter(C=>C.status!=="matched"),b=Math.max(1,Math.ceil(m.length/Ms)),p=Math.min(s,b-1),x=m.slice(p*Ms,(p+1)*Ms),g=Math.max(1,Math.ceil(u.length/Ms)),f=Math.min(a,g-1),w=u.slice(f*Ms,(f+1)*Ms),N=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,D=h.length>0&&!t.isApplying,A=c!==null&&o===c.previewChecksum,y=u.length>0&&f===g-1;l.useEffect(()=>{n(0),r(0),i(null)},[c?.previewChecksum]);async function j(C){if(C)try{t.onCsvChange(await C.text())}catch{}}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-group-import-title",className:"border-y border-default py-4",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h4",{id:"advanced-measurement-group-import-title",className:"text-sm font-medium text-heading",children:"Import groups from CSV"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Import market membership once instead of selecting the same Properties for every group."})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"CSV file"}),e.jsx("input",{"aria-label":"Group membership CSV file",type:"file",accept:".csv,text/csv",disabled:t.isReviewing||t.isApplying,onChange:C=>{j(C.currentTarget.files?.[0])},className:"mt-1 block min-h-11 w-full text-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary"})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Or paste CSV"}),e.jsx("textarea",{"aria-label":"Group membership CSV",rows:5,value:t.csv,disabled:t.isReviewing||t.isApplying,onChange:C=>t.onCsvChange(C.currentTarget.value),placeholder:`property,group,url
|
|
3
|
-
Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!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]}),c?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[c.counts.matchedRows," matched · ",c.counts.groupsReady," group",c.counts.groupsReady===1?"":"s"," ready",d>0?` · ${d} need${d===1?"s":""} attention`:""]}),c.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:c.groupChanges.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:C.label}),e.jsx("td",{className:"text-secondary",children:C.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:C.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[C.addedTargetKeys.length,C.unchangedTargetKeys.length>0?` · ${C.unchangedTargetKeys.length} already members`:""]})]},C.groupKey))})]})}):null,c.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",c.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:x.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(ue,{tone:$o(C.status),children:To(C.status)}),$a(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:$a(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",p+1," of ",b," · ",c.rows.length," rows"]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===0,onClick:()=>n(C=>Math.max(0,C-1)),children:"Previous 50 rows"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===b-1,onClick:()=>n(C=>Math.min(b-1,C+1)),children:"Next 50 rows"})]})]}):null,d>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",d," row",d===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:w.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(ue,{tone:$o(C.status),children:To(C.status)}),$a(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:$a(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",f+1," of ",g]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===0,onClick:()=>r(C=>Math.max(0,C-1)),children:"Previous 50 exceptions"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===g-1,onClick:()=>r(C=>Math.min(g-1,C+1)),children:"Review next 50 exceptions"})]}),e.jsxs("label",{className:"mt-3 flex min-h-11 max-w-xl items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:A,disabled:t.isApplying||!y,onChange:C=>i(C.currentTarget.checked?c.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",d," row",d===1?"":"s"," will be skipped."]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!D||!A,onClick:()=>{t.onApply(h.map(C=>C.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(P,{type:"button",className:"mt-3 min-h-11",disabled:!D,onClick:()=>{t.onApply(h.map(C=>C.dataRow))},children:t.isApplying?"Creating groups…":`Create ${c.counts.groupsReady} group${c.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const df="—";function uf({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:o=!1,isBusy:i=!1,canContinue:c=!0,onSelectedQueryIdsChange:d,onApplySelectedQueries:h,onClearQueryAssignments:m,onRemoveQuery:u,onCreateQueries:b,onCreateAndPairQuestions:p,isCreatingQueries:x=!1,createQueriesError:g=null,onManageProjectQueries:f,groups:w,audience:N,onAudienceChange:D,assignmentImpact:A=null,isPreviewingAssignmentImpact:y=!1,assignmentImpactError:j=null,onRetryAssignmentImpact:C,assignmentNotice:L=null,onReplaceAssignments:E,isReplacingAssignments:F=!1,onBack:V,onContinue:K}){const[k,q]=l.useState(""),[R,ae]=l.useState(!1),[O,X]=l.useState(!1),[ce,Y]=l.useState(""),[_,I]=l.useState(""),[le,T]=l.useState(null);if(gi(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(yi,{message:s.message})});const ee=pi(t),Z=N,ge=D,J=Ia(Z,n,w),de=J.length,xe=de>0&&r.length>0&&!o&&!i&&!y&&A!==null&&j===null,se=m??u,z=k.trim().toLocaleLowerCase(),ne=z?a.filter(H=>Ir(H).toLocaleLowerCase().includes(z)):a,Ee=ne.filter(H=>(H.propertyIds?.length??0)===0),we=O?Ee:ne,Se=R?we:we.slice(0,of),et=Se.filter(H=>!ei(H)),Ke=[...new Set(ce.split(`
|
|
4
|
-
`).map(H=>H.trim()).filter(Boolean))],ze=[..._.matchAll(/\{([a-z][\w-]*)\}/gi)].map(H=>H[1]),He=n.filter(H=>J.includes(H.id)),Ge=ze.length===0||_.trim()===""?[]:He.map(H=>({propertyId:H.id,text:ze.reduce((Re,_e)=>Re.replaceAll(`{${_e}}`,H.label),_.trim())})),U=[...new Set(Ge.map(H=>H.text))];function B(){const H=new Set([...r,...et.map(Re=>Re.id)]);d(a.filter(Re=>H.has(Re.id)).map(Re=>Re.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."})]})}),ee?e.jsx(fi,{}):null,ee?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:Z.kind==="all"?"all":Z.kind==="specific"?"specific":`group:${Z.groupIds[0]??""}`,onChange:H=>{const Re=H.currentTarget.value;Re==="all"?ge({kind:"all"}):Re==="specific"?ge({kind:"specific",propertyIds:[]}):Re.startsWith("group:")&&ge({kind:"groups",groupIds:[Re.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]}),w.length>0?e.jsx("optgroup",{label:"Groups",children:w.map(H=>{const Re=Ia({kind:"groups",groupIds:[H.id]},n,w).length;return e.jsx("option",{value:`group:${H.id}`,disabled:Re===0,children:Rr(H,n)},H.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),Z.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:Z.groupIds.map(H=>{const Re=w.find(_e=>_e.id===H);return Re?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:[Rr(Re,n),e.jsx("button",{type:"button","aria-label":`Remove ${Re.name}`,className:"-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>{const _e=Z.groupIds.filter(Ue=>Ue!==Re.id);ge(_e.length>0?{kind:"groups",groupIds:_e}:{kind:"all"})},children:"×"})]},Re.id):null})}),w.some(H=>!Z.groupIds.includes(H.id)&&Ia({kind:"groups",groupIds:[H.id]},n,w).length>0)?e.jsxs("label",{className:"block max-w-sm",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Add another group"}),e.jsxs("select",{"aria-label":"Add another group",value:"",onChange:H=>{H.currentTarget.value&&ge({kind:"groups",groupIds:[...Z.groupIds,H.currentTarget.value]})},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",children:"Choose a group"}),w.filter(H=>!Z.groupIds.includes(H.id)).map(H=>{const Re=Ia({kind:"groups",groupIds:[H.id]},n,w).length;return e.jsx("option",{value:H.id,disabled:Re===0,children:Rr(H,n)},H.id)})]})]}):null,de===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,Z.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(ti,{legend:"Specific Properties",properties:n,selectedPropertyIds:Z.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:H=>{ge({kind:"specific",propertyIds:H})}})}):null,e.jsx("p",{className:"mt-3 max-w-2xl text-sm text-secondary",children:"Groups are shortcuts resolved when you assign. Changing membership later does not rewrite existing assignments, and a Property added later does not receive earlier group queries."})]}),ee||!b?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:ce,onChange:H=>Y(H.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(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ke.length===0||x||i,onClick:()=>{Promise.resolve(b(Ke)).then(()=>Y(""),()=>{})},children:x?"Adding…":`Add ${Ke.length||""} ${Ke.length===1?"query":"queries"}`.replace(" "," ")}),f?e.jsx(P,{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:_,onChange:H=>I(H.target.value),placeholder:"apartments near {property}"}),_.trim()===""?null:ze.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."]}):He.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:[U.length," ",U.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:U.slice(0,3).map(H=>e.jsx("li",{className:"text-sm text-strong",children:H},H))}),U.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",U.length-3," more"]}):null]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Ge.length===0||x||i||!p,onClick:()=>{p&&Promise.resolve(p(Ge)).then(()=>I(""),()=>{})},children:x?"Adding…":`Add ${Ge.length||""} ${Ge.length===1?"query":"queries"}`.replace(" "," ")}),Ge.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"," ",Ge.length," assignment",Ge.length===1?"":"s","."]}):null]})]})]}),ee?null:e.jsx("div",{className:"space-y-3 border-y border-default py-4",children:a.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:et.length===0,onClick:B,children:"Select all shown queries"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>d([]),children:"Clear query selection"}),e.jsx(P,{type:"button",size:"sm",className:"min-h-11",disabled:!xe,onClick:()=>{h({queryIds:r,propertyIds:J,...Z.kind==="groups"?{groupIds:Z.groupIds}:{}})},children:o?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${lf(Z,w,de)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[y?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",Z.kind==="groups"?` · ${A.resolvedPropertyCount} unique ${A.resolvedPropertyCount===1?"Property":"Properties"}${A.overlapCount>0?`, ${A.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):j?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:j}),C?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:C,children:"Retry impact"}):null,V?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:V,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",de," Properties = ",r.length*de," 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:H=>{q(H.currentTarget.value),ae(!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 ",Se.length," of ",we.length," queries,"," ",ne.length-Ee.length," of ",ne.length," applied"]}),ee||Ee.length===0?null:e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{X(H=>!H),ae(!1)},children:O?"Show all queries":`Show the ${Ee.length} not applied`})]})]}):null,Se.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:[ee?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),ee?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:Se.map(H=>{const Re=ei(H),_e=Ir(H),Ue=r.includes(H.id),ie=(H.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[ee?null:Re?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 ${_e}`,checked:Ue,type:"checkbox",onChange:pt=>d(ec(r,H.id,pt.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:_e})}),e.jsx("td",{className:"text-secondary",children:tc(H.propertyIds??[],n)}),ee?null:e.jsx("td",{className:"text-right",children:ie?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[E?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||F,onClick:()=>T({queryId:H.id,propertyIds:[...H.propertyIds??[]]}),"aria-label":`Replace query assignments for ${_e}`,children:"Replace assignments"}):null,e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{se(H.id)},"aria-label":`Clear query assignments for ${_e}`,children:"Clear assignments"})]}):null})]},H.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,ee||!le?null:(()=>{const H=a.find(Ue=>Ue.id===le.queryId),Re=H?Ir(H):"this query",_e=le.propertyIds.filter(Ue=>n.some(ie=>ie.id===Ue));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 “",Re,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(ti,{legend:"Properties for this query",properties:n,selectedPropertyIds:_e,onSelectedPropertyIdsChange:Ue=>T(ie=>ie&&{...ie,propertyIds:[...Ue]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:F||i,onClick:()=>T(null),children:"Keep current assignments"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:_e.length===0||F||i||!E,onClick:()=>{E&&Promise.resolve(E({queryId:le.queryId,propertyIds:_e}))},children:F?"Replacing assignments…":`Replace with ${_e.length} ${_e.length===1?"Property":"Properties"}`})]})]})})(),Se.length<we.length?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>ae(!0),children:"Show all queries"}):null,ee?null:e.jsxs(e.Fragment,{children:[c?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${V?"justify-between":"justify-end"}`,children:[V?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:V,children:"Back"}):null,e.jsx(P,{type:"button",variant:xe?"outline":"default",className:"min-h-11",disabled:!c||i,onClick:K,children:"Continue"})]})]})]})}function mf({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:o=!1,onGroupDraftChange:i,onSaveGroup:c,onEditGroup:d,onRemoveGroup:h,onClearGroupDraft:m,membershipImport:u,onBack:b,onContinue:p}){if(gi(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(yi,{message:s.message})});const x=pi(t),g=r.name.trim().length>0&&r.propertyIds.length>0&&!o,f=n.filter(A=>r.propertyIds.includes(A.id)).length,w=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,N=!x&&(d!==void 0||h!==void 0);function D(){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(fi,{}):null,x||!u?null:e.jsx(cf,{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(ti,{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(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!g,onClick:()=>{c(r)},children:o?"Saving group…":"Save group"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!w,onClick:D,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."})]}),w?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:tc(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:[d?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${A.name}`,onClick:()=>d(A),children:"Edit"}):null,h?e.jsx(P,{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 ${b?"justify-between":"justify-end"}`,children:[b?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:b,children:"Back"}):null,e.jsx(P,{type:"button",className:"min-h-11",disabled:w,onClick:p,children:a.length===0&&!w?"Continue without groups":"Continue"})]})]})}function hf({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:o,onReviewChanges:i,isReviewing:c=!1,canReviewChanges:d=!0,reviewedChanges:h,reviewChangesError:m,canPublish:u,isPublishing:b=!1,onPublish:p}){const[x,g]=l.useState(Pr),[f,w]=l.useState(Pr),[N,D]=l.useState(Pr);if(gi(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(yi,{message:s.message})});const A=pi(t),y=r?.items??[],j=r?.coverageItems??[],C=y.slice(0,x),L=j.slice(0,f),E=a.slice(0,N),F=i!==void 0,V=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(fi,{}):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,")"]}),y.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:C.map(K=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:K.url}),e.jsx("p",{className:"mt-1 text-secondary",children:K.reason})]},`${K.url}-${K.reason}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected sitemap URLs before confirming."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",C.length," of ",y.length]}),C.length<y.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>g(K=>K+Ms),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(K=>e.jsxs("section",{"aria-label":`${K.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:K.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:K.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"}),K.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:K.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."})]})]})]},K.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 ",j.length]}),L.length<j.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>w(K=>K+Ms),children:"Show next 50 URL changes"}):null]})]}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected Properties before confirming."})]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="keep-existing",onChange:()=>r.onCoverageResolutionChange("keep-existing")}),"Keep existing Property URLs"]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="replace-with-imported",onChange:()=>r.onCoverageResolutionChange("replace-with-imported")}),"Use current sitemap URLs"]})]}):null,e.jsx(P,{type:"button",className:"min-h-11",onClick:()=>{r.onResolve()},children:"Confirm sitemap changes"})]})]})}):null,e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Groups"}),e.jsx("th",{children:"Assignments"}),e.jsx("th",{children:"Provider requests / run"})]})}),e.jsx("tbody",{children:e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-heading",children:n.properties}),e.jsx("td",{className:"tabular-nums text-heading",children:n.queries}),e.jsx("td",{className:"tabular-nums text-heading",children:n.groups}),e.jsx("td",{className:"tabular-nums text-heading",children:n.assignments??"—"}),e.jsx("td",{className:"tabular-nums text-heading",children:n.providerCalls??df})]})})]})}),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((K,k)=>e.jsx("li",{children:K},`${K}-${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:E.map(K=>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:K.title}),K.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:K.detail}):null]}),e.jsx(ue,{tone:K.tone??"caution",children:"Needs attention"})]},K.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",E.length," of ",a.length]}),E.length<a.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>D(K=>K+Ms),children:"Show next 50 exceptions"}):null]})]})]}),A?null:e.jsxs(e.Fragment,{children:[F&&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(P,{type:"button",variant:"outline",className:"min-h-11",onClick:o,children:"Back"}):null,i!==void 0&&!V?e.jsx(P,{type:"button",className:"min-h-11",disabled:c||!d,onClick:()=>{i()},children:c?"Reviewing changes…":"Review changes"}):e.jsx(P,{type:"button",className:"min-h-11",disabled:!u||b,onClick:()=>{p()},children:b?"Publishing setup…":"Publish setup"})]})]})]})}const xf={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function pf(t){return t.trim().toLocaleLowerCase()}function gf(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function ff({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 yf({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 c(d,h){n({...s,[d]: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(ue,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:d=>{d.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:o,onChange:d=>c("sitemapUrl",d.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:o,onChange:d=>c("examplePropertyUrl",d.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:o,onChange:d=>c("preferredHost",d.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:o,onChange:d=>c("propertyPathPattern",d.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:o,onChange:d=>c("additionalHost",d.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:o,onChange:d=>c("additionalPathPattern",d.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:o,onChange:d=>c("excludedPaths",d.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(P,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function bf({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:o,onSelectedPropertyIdsChange:i,onContinue:c,isContinuing:d=!1,onRetryProperties:h,onReturnToImport:m,maxVisibleProperties:u,onShowAllProperties:b}){const p=pf(a),x=s.filter(E=>gf(E,p)),g=Math.max(1,u??x.length),f=x.slice(0,g),w=new Set(o),N=s.filter(E=>w.has(E.id)).map(E=>E.id),D=f.length<x.length;function A(E){const F=new Set(E);i(s.filter(V=>F.has(V.id)).map(V=>V.id))}function y(E,F){if(!t||d)return;const V=new Set(N);F?V.add(E):V.delete(E),A(V)}function j(){!t||d||A([...N,...f.map(E=>E.id)])}function C(){!t||d||i([])}function L(){!t||d||N.length===0||c(N)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||d,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick: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(P,{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(P,{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:d,onChange:E=>r(E.target.value),className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),t?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:d,onClick:j,children:"Select all shown"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:d||N.length===0,onClick:C,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(P,{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(E=>{const F=xf[E.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:E.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(ff,{property:E})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(ue,{tone:F.tone,children:F.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 ${E.name}`,checked:N.includes(E.id),disabled:d,onChange:V=>y(E.id,V.target.checked),className:"size-6 accent-accent"})})}):null]},E.id)})})]})}),D&&b?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:d,onClick:b,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(P,{type:"button",variant:"ghost",disabled:d,onClick:m,children:"Back"}),e.jsx(P,{type:"button",disabled:d||N.length===0,onClick:L,children:d?"Saving Properties…":"Continue"})]}):null]}):null]})}function vf(t){return t.activeStep==="import"?e.jsx(yf,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(bf,{...t})}const jf=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function Nf({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:o}){const i=l.useRef(null),c=l.useRef(null),d=l.useRef(null),h=l.useRef(null),m=l.useRef(!1),[u,b]=l.useState(!1);return l.useEffect(()=>{s||b(!1)},[s]),l.useEffect(()=>{const p=m.current;m.current=u,u?d.current?.focus():p&&h.current?.focus()},[u]),l.useEffect(()=>{const p=i.current;if(i.current=t,p===null||p===t)return;const x=c.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(ue,{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(P,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>b(!1),children:"Keep editing"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(P,{ref:h,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>b(!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:jf.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:c,children:o})]})}function wf(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(vf,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(uf,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(mf,{...t.groups,access:s}):"review"in t?e.jsx(hf,{...t.review,access:s}):null}function Ta(t){return e.jsx(Nf,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:wf(t)})}function sc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function _t(t){return{"If-Match":t,"Idempotency-Key":sc()}}function cn(t){return t instanceof pn&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function os(t,s){return t instanceof pn?s:(t instanceof Error?t.message.trim():"")||s}function Sf(t){const s="Could not calculate assignment impact.";if(!(t instanceof pn)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const Cf={loadSetup:t=>xt(()=>bu({client:W,path:{name:t}})),loadDraft:t=>xt(()=>yu({client:W,path:{name:t}})),createDraft:(t,s)=>xt(()=>fu({client:W,path:{name:t},headers:{"Idempotency-Key":sc()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>xt(()=>gu({client:W,path:{name:t},headers:_t(s),body:n})),applySitemapSelection:(t,s,n,a)=>xt(()=>pu({client:W,path:{name:t},headers:_t(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>xt(()=>xu({client:W,path:{name:t},body:s})),applyAssignments:(t,s,n)=>xt(()=>hu({client:W,path:{name:t},headers:_t(s),body:n})),replaceAssignments:(t,s,n)=>xt(()=>mu({client:W,path:{name:t},headers:_t(s),body:n})),applyPairedAssignments:(t,s,n)=>xt(()=>uu({client:W,path:{name:t},headers:_t(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>xt(()=>du({client:W,path:{name:t},headers:_t(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>xt(()=>cu({client:W,path:{name:t},headers:_t(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>xt(()=>lu({client:W,path:{name:t},headers:_t(s),body:{target:n}})),upsertGroup:(t,s,n)=>xt(()=>ou({client:W,path:{name:t},headers:_t(s),body:{group:n}})),removeGroup:(t,s,n)=>xt(()=>iu({client:W,path:{name:t},headers:_t(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>xt(()=>ru({client:W,path:{name:t},headers:_t(s),body:n})),removeCompetitor:(t,s,n,a)=>xt(()=>au({client:W,path:{name:t},headers:_t(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>xt(()=>nu({client:W,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>xt(()=>su({client:W,path:{name:t},headers:_t(s),body:n})),compilePreview:t=>xt(()=>tu({client:W,path:{name:t}})),diffPreview:t=>xt(()=>eu({client:W,path:{name:t}})),publish:(t,s,n)=>xt(()=>Zd({client:W,path:{name:t},headers:_t(s),body:n})),discard:(t,s)=>xt(()=>Xd({client:W,path:{name:t},headers:_t(s)}))},Mo={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},zn={name:"",propertyIds:[],competitorDomains:""},Lo=50;function Yn(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function kf(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 qo(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 Af(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,c=i.startsWith("*"),d=i.endsWith("*"),h=i.slice(c?1:0,d?-1:void 0).trim();if(!h)throw new Error("Ignored URL patterns must include text besides *.");const m=c&&d?"contains":c?"suffix":d?"prefix":"exact",u=`${m}:${h}`;n.has(u)||(n.add(u),s.push({kind:m,value:h}))}return s}function Pf(t){const s=kf(t.sitemapUrl),n=t.examplePropertyUrl.trim()?Yn(t.examplePropertyUrl):null,a=Yn(t.preferredHost)??n??Yn(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=Yn(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 c=Af(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:qo(t)},...r?{aliases:[{host:r,pathTemplate:qo({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...c.length>0?{excludedSlugPatterns:c}:{}}}}function Rf(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 If(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 Eo(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function $f(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 si(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function Do(t){return Yn(t)}function nc(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 ac(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 rc(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function ic(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Tf(t,s){const n=nc(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 Mf(t,s){const n=ac(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=ic(t.authoring,n.targetKeys[r]);return`${n.label} — ${o}`}return n.label}function Lf(t,s){const n=rc(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${ic(t.authoring,n.targetKey)} — ${a}`}function qf(t,s){return s.path[0]==="identities"?"Project domain":Tf(t,s)??Mf(t,s)??Lf(t,s)}function Oo(t,s,n){const a=rc(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 Ef(t,s){const n=qf(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,Oo(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,Oo(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 Ma(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function oc(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 Df(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${Ma(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${Ma(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${Ma(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${Ma(n,"item")} need review.`:s}})()}${oc(a)}`}function Of(t,s){const n=new Map;for(const a of t){const r=Ef(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:Df(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function Tr(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function Mr(t,s,n){const a=nc(n,t.path),r=ac(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,c=a?.label??r?.label,d=oc(c?[c]:[]),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.${d}`};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.${d}`};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.${d}`};case"measurement.discovery.proposed_new_target":{const m=Tr(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=Tr(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=Tr(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 Ff(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 zs(t){return ws(t).sort()}function Kf(t,s,n){return t.kind==="groups"?{groupKeys:zs(t.groupIds),queryIds:zs(n)}:{targetKeys:zs(t.kind==="all"?s:t.propertyIds),queryIds:zs(n)}}function Gf(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 Fo(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function _f(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(Fo).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(Fo).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:si(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function Uf({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:o,canEdit:i=!0,onCreateQueries:c,onManageProjectQueries:d,onPublished:h,service:m=Cf}){const[u,b]=l.useState(null),[p,x]=l.useState(null),[g,f]=l.useState("import"),[w,N]=l.useState(!0),[D,A]=l.useState(null),[y,j]=l.useState(null),[C,L]=l.useState([]),[E,F]=l.useState({...Mo}),[V,K]=l.useState("idle"),[k,q]=l.useState(""),[R,ae]=l.useState(Lo),[O,X]=l.useState([]),[ce,Y]=l.useState([]),[_,I]=l.useState({kind:"all"}),[le,T]=l.useState(null),[ee,Z]=l.useState(null),[ge,J]=l.useState(!1),[de,xe]=l.useState(null),[se,z]=l.useState(0),[ne,Ee]=l.useState(null),[we,Se]=l.useState({...zn}),[et,Ke]=l.useState(null),[ze,He]=l.useState(""),[Ge,U]=l.useState(null),[B,H]=l.useState(!1),[Re,_e]=l.useState(!1),[Ue,ie]=l.useState(null),[pt,ut]=l.useState(null),[Qe,Fe]=l.useState(null),[wt,Be]=l.useState(null),[Me,tt]=l.useState(null),Tt=l.useRef(0),Mt=l.useRef(0),De=p?.draft??null,S=p?.etag??null,Ae=l.useMemo(()=>!i&&o?{baseActiveRevision:o.revision,authoring:_f(o)}:null,[i,o]),ve=De??Ae;async function We(G){const oe=++Tt.current;N(!0),A(null);try{let[Ne,me]=await Promise.all([m.loadSetup(t),m.loadDraft(t)]);if(!me.draft&&G&&i&&(await m.createDraft(t,Ne.activeRevision),[Ne,me]=await Promise.all([m.loadSetup(t),m.loadDraft(t)])),oe!==Tt.current)return;b(Ne),x(me),f(Rf(me.draft));const je=$r(me.draft);X(je)}catch(Ne){if(oe!==Tt.current)return;A(os(Ne,"Could not load advanced measurement setup."))}finally{oe===Tt.current&&N(!1)}}l.useEffect(()=>(We(!0),()=>{Tt.current+=1}),[t,i,m]),l.useEffect(()=>{!w&&!De&&Ae&&f("properties")},[De,w,Ae]);async function vt(){const G=await m.loadDraft(t);return x(G),G}async function st(G){tt(null);try{const[oe,Ne]=await Promise.all([m.loadSetup(t),m.loadDraft(t)]);b(oe),x(Ne);const me=$r(Ne.draft);X(me),f(je=>If(Ne.draft,je)),j(G)}catch(oe){j(os(oe,G))}}async function Lt(G,oe,Ne,me={}){const{preserveBusyAction:je=!1}=me;if(!i||!S||Qe&&!je)return null;je||Fe(G),j(null),tt(null);try{const Ie=await oe(S),as=await vt();return L((Ie.warnings??[]).map((ot,bs)=>Mr(ot,bs,as.draft?.authoring))),as}catch(Ie){return cn(Ie)?await st("This setup changed in another session. The latest draft is loaded; review your changes again."):j(os(Ie,Ne)),null}finally{je||Fe(null)}}const Xe=l.useMemo(()=>(ve?.authoring.targets??[]).map(G=>{const oe=Eo(G);return{id:G.stableKey,name:G.label,url:oe[0]??"No URL",urls:oe,state:$f(G.status)}}),[ve]),te=l.useMemo(()=>ve?.authoring.targets.filter(G=>G.status==="included")??[],[ve]),qe=l.useMemo(()=>te.map(G=>({id:G.stableKey,label:G.label,urlCount:Eo(G).length})),[te]),Ce=ve?.authoring.assignments.length??0,Pe=l.useMemo(()=>{if(!ve)return[];const G=new Set(s.map(me=>me.id)),oe=s.map(me=>({id:me.id,text:me.query,source:"saved-project-queries",propertyIds:ws(ve.authoring.assignments.filter(je=>je.queryId===me.id).map(je=>je.targetKey))})),Ne=ws(ve.authoring.assignments.map(me=>me.queryId).filter(me=>!G.has(me))).map(me=>({id:me,source:"unavailable-tracked-query",state:"missing",propertyIds:ws(ve.authoring.assignments.filter(je=>je.queryId===me).map(je=>je.targetKey))}));return[...oe,...Ne]},[s,ve]),Yt=l.useMemo(()=>(ve?.authoring.groups??[]).map(G=>({id:G.stableKey,name:G.label,propertyIds:G.targetKeys,competitors:G.competitors.map(oe=>oe.domain)})),[ve]),Jt=l.useMemo(()=>{if(ce.length===0)return null;const G=Kf(_,qe.map(Ne=>Ne.id),ce);return(G.groupKeys?.length??G.targetKeys?.length??0)>0?G:null},[_,qe,ce]),yt=Jt?JSON.stringify(Jt):"";l.useEffect(()=>{const G=Jt,oe=++Mt.current;if(!i||!De||!S||!G){T(null),Z(null),xe(null),J(!1);return}T(null),Z(null),xe(null),J(!0);const Ne=window.setTimeout(()=>{m.previewAssignments(t,G).then(me=>{if(oe===Mt.current){if(me.draftEtag!==S){T(null),Z(null),xe("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}T(me),Z(yt)}}).catch(me=>{oe===Mt.current&&(T(null),Z(null),xe(Sf(me)))}).finally(()=>{oe===Mt.current&&J(!1)})},250);return()=>{window.clearTimeout(Ne),Mt.current+=1}},[Jt,yt,se,i,De,S,t,m]);const St=l.useMemo(()=>[...Ce===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"}]:[],...ve?.authoring.assignments.some(G=>G.queryClass==="unclassified")&&!(Ae&&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"}]:[],...C],[Ce,Ae,o,C,ve]),mt=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 Xt(G){let oe;try{oe=Pf(G)}catch(me){j(os(me,"Check the sitemap details and try again."));return}F(G),K("reviewing");const Ne=await Lt("import",me=>m.importSitemap(t,me,oe),"Could not review this sitemap.");if(Ne?.draft){const me=Ne.draft.authoring.targets.filter(Ie=>Ie.status==="proposed").map(Ie=>Ie.stableKey),je=Ne.draft.authoring.targets.filter(Ie=>Ie.status==="included").map(Ie=>Ie.stableKey);X([...je,...me]),q(""),ae(Lo),f("properties"),K("idle")}else K("error")}async function zt(G){if(!c||G.length===0||Qe)return[];Fe("create-queries"),Be(null);try{return await c(G)}catch(oe){throw Be(ft(oe)),oe}finally{Fe(null)}}async function ss(G){if(!De||!S||Qe)return;const oe=new Set(G),me=De.authoring.targets.filter(Ie=>Ie.status==="proposed"&&Ie.discoveryIdentity).map(Ie=>({discoveryIdentity:Ie.discoveryIdentity,action:oe.has(Ie.stableKey)?"create":"ignore"})),je=me.length>0||De.authoring.targets.some(Ie=>Ie.status!=="proposed"&&Ie.status==="included"!==oe.has(Ie.stableKey));Fe("properties"),j(null),tt(null);try{if(!je){X([...oe]),I({kind:"all"}),f("groups");return}await m.applySitemapSelection(t,S,me,[...oe]);const Ie=await vt(),as=$r(Ie.draft);X(as),I({kind:"all"}),f("groups")}catch(Ie){cn(Ie)?await st("This setup changed in another session. The latest Properties are loaded."):j(os(Ie,"Could not save the selected Properties."))}finally{Fe(null)}}async function at(G){const oe=G.groupIds&&G.groupIds.length>0?{groupKeys:zs(G.groupIds),queryIds:zs(G.queryIds)}:{targetKeys:zs(G.propertyIds),queryIds:zs(G.queryIds)};if(!le||ee!==JSON.stringify(oe)||!S||le.draftEtag!==S){j("Review the latest assignment impact before assigning queries.");return}await Lt("assignments",me=>m.applyAssignments(t,me,oe),"Could not apply these queries.")&&(Y([]),Ee(`${le.assignments.added} new assignment${le.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function fs(G){if(G.propertyIds.length===0)return;await Lt("replace-assignments",Ne=>m.replaceAssignments(t,Ne,{targetKeys:ws(G.propertyIds),queryIds:[G.queryId]}),"Could not replace this query assignment.")&&(Y(Ne=>Ne.filter(me=>me!==G.queryId)),Ee("Query assignments replaced."))}async function gt(G,oe=!1){if(G.length===0)return;if(!await Lt("paired-assignments",me=>m.applyPairedAssignments(t,me,[...G]),"Could not assign these queries.",{preserveBusyAction:oe}))throw new Error("Could not assign these queries.")}async function dt(G){if(!(!i||!c||G.length===0||Qe)){Fe("create-and-pair-questions"),Be(null);try{let oe;try{oe=await c(ws(G.map(je=>je.text)))}catch(je){throw Be(ft(je)),je}const Ne=new Map(oe.map(je=>[je.query,je.id])),me=G.map(je=>({targetKey:je.propertyId,queryId:Ne.get(je.text)})).filter(je=>je.queryId!==void 0);if(me.length!==G.length){const je=new Error("The created queries could not be matched to their Properties.");throw Be("The queries were added, but could not be paired with every Property. Try again to pair them."),je}try{await gt(me,!0)}catch(je){throw Be("The queries were added, but could not be assigned to their Properties. Try again to pair them."),je}}finally{Fe(null)}}}async function Ct(G){if(!De)return;const oe=ws(De.authoring.assignments.filter(me=>me.queryId===G).map(me=>me.targetKey));if(oe.length===0)return;await Lt(`remove-${G}`,me=>m.removeAssignment(t,me,oe,G),"Could not clear this query assignment.")&&Y(me=>me.filter(je=>je!==G))}async function ns(G){if(!De||!S||Qe)return;const oe=G.name.trim();if(!oe)return;const Ne=et??si(oe,"group"),me=De.authoring.groups.find(ot=>ot.stableKey===Ne);if(me&&et===null){j(`A group named "${me.label}" already exists. Edit it or choose a different name.`);return}const je=G.competitorDomains.split(/[\s,]+/).map(ot=>ot.trim()).filter(Boolean),Ie=je.find(ot=>Do(ot)===null);if(Ie){j(`"${Ie}" is not a valid competitor domain.`);return}const as=ws(je.map(ot=>Do(ot)));Fe("group"),j(null),tt(null);try{const ot=await m.upsertGroup(t,S,{stableKey:Ne,label:oe,targetKeys:ws(G.propertyIds),competitors:as.map(M=>me?.competitors.find(pe=>pe.domain===M)??{stableKey:si(M,"competitor"),label:M,domain:M,aliases:[]})}),bs=await vt();L(ot.warnings.map((M,pe)=>Mr(M,pe,bs.draft?.authoring))),Se({...zn}),Ke(null)}catch(ot){cn(ot)?await st("This setup changed in another session. The latest groups are loaded."):j(os(ot,"Could not save this group."))}finally{Fe(null)}}function hs(G){const oe=De?.authoring.groups.find(Ne=>Ne.stableKey===G);oe&&(Ke(G),Se({name:oe.label,propertyIds:[...oe.targetKeys],competitorDomains:oe.competitors.map(Ne=>Ne.domain).join(", ")}))}async function qt(G){await Lt("remove-group",Ne=>m.removeGroup(t,Ne,G),"Could not remove this group.")&&(I(Ne=>Ne.kind==="groups"&&Ne.groupIds.includes(G)?{kind:"all"}:Ne),et===G&&(Ke(null),Se({...zn})))}function Ps(G){He(G),U(null),ie(null),ut(null)}async function Qt(){if(!(!i||!ze.trim()||B||Re)){H(!0),ie(null),ut(null);try{U(await m.previewGroupMembership(t,{csv:ze}))}catch(G){U(null),ie(os(G,"Could not review this CSV."))}finally{H(!1)}}}async function kt(G){if(!(!i||!S||!Ge||G.length===0||Qe)){if(Ge.draftEtag!==S){ie("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}_e(!0),Fe("group-import"),ie(null),ut(null),tt(null);try{const oe=await m.applyGroupMembership(t,S,{csv:ze,sourceChecksum:Ge.sourceChecksum,previewChecksum:Ge.previewChecksum,acceptedRows:ws(G.map(String)).map(Number)}),Ne=await vt();L(oe.warnings.map((me,je)=>Mr(me,je,Ne.draft?.authoring))),He(""),U(null),ut(`${oe.addedMemberships} membership${oe.addedMemberships===1?"":"s"} added${oe.unchangedMemberships>0?`; ${oe.unchangedMemberships} already present`:""}.`)}catch(oe){cn(oe)?(await st("This setup changed in another session. The latest draft is loaded; review the CSV again."),ie("The setup changed while this CSV was open. Review the latest CSV before applying it.")):ie(os(oe,"Could not apply this CSV."))}finally{Fe(null),_e(!1)}}}async function xs(){if(!(!De||!S||Qe||Ce===0)){Fe("review"),j(null),tt(null);try{const[G,oe]=await Promise.all([m.compilePreview(t),m.diffPreview(t)]),Ne=[...G.checks,...oe.checks],me=Ne.some(je=>je.ruleId==="active-revision-schema-v1");if(L(Of(Ne.filter(je=>je.ruleId!=="active-revision-schema-v1"),{authoring:ve?.authoring,queries:s})),!G.ok||!oe.ok)return;if(oe.diff.activeRevision!==De.baseActiveRevision){await st("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(G.compiledChecksum!==oe.compiledChecksum){j("The setup changed while it was being reviewed. Review the latest changes again.");return}tt({etag:S,baseActiveRevision:De.baseActiveRevision,compiledChecksum:G.compiledChecksum,changes:Ff(oe.diff,me),providerCalls:G.plan.executionNodes.reduce((je,Ie)=>je+Ie.expectedSnapshots,0)})}catch(G){j(os(G,"Could not review this setup."))}finally{Fe(null)}}}async function ht(){if(!(!De||!S||!Me||Qe)){if(S!==Me.etag||De.baseActiveRevision!==Me.baseActiveRevision){tt(null),j("The setup changed after review. Review the latest changes before publishing.");return}Fe("publish"),j(null);try{await m.publish(t,S,{expectedActiveRevision:Me.baseActiveRevision,expectedCompiledChecksum:Me.compiledChecksum}),x({draft:null,etag:null}),tt(null),h?.()}catch(G){cn(G)?await st("The setup changed before it could be published. Review the latest draft and publish again."):j(os(G,"Could not publish this setup."))}finally{Fe(null)}}}async function Zt(){if(!(!S||Qe)){Fe("discard"),j(null);try{await m.discard(t,S),x({draft:null,etag:null}),tt(null),h?.()}catch(G){cn(G)?await st("This setup changed in another session. The latest draft is loaded."):j(os(G,"Could not discard these changes."))}finally{Fe(null)}}}async function ys(){if(!(!De||!S||!u||Qe)){Fe("restart"),j(null),tt(null);try{await m.discard(t,S),await m.createDraft(t,u.activeRevision),F({...Mo}),q(""),X([]),Y([]),I({kind:"all"}),T(null),xe(null),Ee(null),Se({...zn}),Ke(null),He(""),U(null),ie(null),ut(null),await We(!1)}catch(G){cn(G)?await st("The setup changed again. Reloaded the latest draft and published setup."):j(os(G,"Could not restart this setup."))}finally{Fe(null)}}}if(w)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(D)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:D}),e.jsx(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{We(!0)},children:"Try again"})]})]});if(!ve||i&&!S)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(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:Qe==="restart",onClick:()=>{ys()},children:Qe==="restart"?"Restarting…":"Discard draft and restart"})]}),y?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:y}):null]});const ps=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:r,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[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,y?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:y}):null,ps,g==="import"||g==="properties"?e.jsx(Ta,{currentStep:g,hasDraft:De!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{Zt()},importProperties:{importDraft:E,onImportDraftChange:G=>{F(G),K("idle"),j(null)},onReviewSitemap:G=>{Xt(G)},reviewState:V,properties:Xe,propertiesState:"ready",propertiesSearch:k,onPropertiesSearchChange:q,maxVisibleProperties:R,onShowAllProperties:()=>ae(Xe.length),selectedPropertyIds:O,onSelectedPropertyIdsChange:G=>X([...G]),onContinue:G=>{ss(G)},isContinuing:Qe==="properties",onRetryProperties:()=>{vt()},onReturnToImport:()=>f("import")}}):g==="queries"?e.jsx(Ta,{currentStep:"queries",hasDraft:De!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{Zt()},onManageProjectQueries:d,queries:{onCreateQueries:c?G=>zt(G):void 0,isCreatingQueries:Qe==="create-queries"||Qe==="create-and-pair-questions",isBusy:Qe!==null,createQueriesError:wt,availability:mt,properties:qe,queries:Pe,selectedQueryIds:ce,isApplying:Qe==="assignments"||Qe==="paired-assignments",onSelectedQueryIdsChange:G=>Y([...G]),onApplySelectedQueries:G=>at(G),groups:Yt,audience:_,onAudienceChange:G=>{I(G),Ee(null)},assignmentImpact:le&&ee===yt?Gf(le):null,isPreviewingAssignmentImpact:ge,assignmentImpactError:de,onRetryAssignmentImpact:()=>z(G=>G+1),assignmentNotice:ne,onReplaceAssignments:fs,isReplacingAssignments:Qe==="replace-assignments",onCreateAndPairQuestions:i&&c?dt:void 0,onClearQueryAssignments:Ct,onRemoveQuery:Ct,canContinue:Ce>0,onBack:()=>f("groups"),onContinue:()=>f("review")}}):g==="groups"?e.jsx(Ta,{currentStep:"groups",hasDraft:De!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{Zt()},groups:{properties:qe,groups:Yt,groupDraft:we,isSaving:Qe==="group",onGroupDraftChange:Se,onSaveGroup:ns,onEditGroup:G=>hs(G.id),onRemoveGroup:qt,onClearGroupDraft:()=>{Ke(null),Se({...zn})},membershipImport:{csv:ze,preview:Ge,isReviewing:B,isApplying:Re,error:Ue,notice:pt,onCsvChange:Ps,onReview:Qt,onApply:kt},onBack:()=>{f("properties")},onContinue:()=>f("queries")}}):e.jsx(Ta,{currentStep:"review",hasDraft:De!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{Zt()},review:{counts:{properties:te.length,queries:new Set(ve.authoring.assignments.map(G=>G.queryId)).size,groups:ve.authoring.groups.length,assignments:ve.authoring.assignments.length,providerCalls:Me?.providerCalls},flaggedExceptions:St,reviewedChanges:Me?.changes,isReviewing:Qe==="review",canReviewChanges:Ce>0&&!Qe,onReviewChanges:xs,onBack:()=>f("queries"),canPublish:Me!==null&&!Qe,isPublishing:Qe==="publish",onPublish:ht}})]})}const Bf=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function Ko(t){return t.label!=="Complete"}const dn="__all_properties__",Vf=50,lc=50,zf=20,Qf=50,Hf=250,Wf=5,Yf=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Jf={"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"},cc={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."},Xf={numerator:null,denominator:null,reason:"plan_v1"};function Zn(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 Zf(t){return Zn(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function dc(t){if(Zn(t))return"";const s=t.reason??"unavailable";return cc[s]??s}function Go(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 ey(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function ty(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function sy(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function Jn({metric:t,compact:s=!1}){const n=s?Zn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Zn(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",...Zn(t)?{}:{title:dc(t)},children:e.jsx("span",{className:n,children:Zf(t)})})}function bi({shown:t,total:s,onShowAll:n,itemLabel:a}){return t>=s?null:e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",t," of ",s]}),e.jsxs(P,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function _o({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,o]=l.useState(lc),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((c,d)=>e.jsx("li",{className:a,children:c},`${c}:${d}`))}),e.jsx(bi,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>o(Number.MAX_SAFE_INTEGER)})]})]})}function ny({evidence:t,state:s="ready",onRetry:n}){const[a,r]=l.useState(lc),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(P,{type:"button",size:"sm",variant:"outline",onClick:n,children:"Retry evidence"}):null]}):t.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"No source evidence is available."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[640px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children: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(ue,{tone:i.tone,children:Jf[i.kind]}),i.historical?e.jsx(ue,{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(bi,{shown:o.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function ay({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(_o,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(_o,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(ny,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function ry({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(Jn,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function Uo({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function o(i){if(r)return;const c=n.findIndex(m=>m.value===s);let d=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?d=(c+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?d=(c-1+n.length)%n.length:i.key==="Home"?d=0:i.key==="End"&&(d=n.length-1),d===null)return;i.preventDefault();const h=n[d];a(h.value),i.currentTarget.querySelectorAll('[role="radio"]')[d].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:o,children:n.map(i=>{const c=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":c,tabIndex:c?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${c?"segmented-option-active":""}`,children:i.label},i.value)})})}function iy({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 oy({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:o=!1,isViewLoading:i=!1,isLoadingMore:c=!1,isLoadMoreError:d=!1,viewSearch:h,onViewChange:m,onLoadMore:u,onPropertyExpand:b,onRetryEvidence:p,renderPropertyLink:x}){const g=t.currentView!=null,f=t.classReporting==="available"&&(g||t.classScopes!=null),[w,N]=l.useState(t.currentView?.queryClass??"all"),[D,A]=l.useState(t.currentView?.scope.key??dn),[y,j]=l.useState(h??""),[C,L]=l.useState(Vf),[E,F]=l.useState(zf),[V,K]=l.useState(t.currentView?.sort??"label-asc"),[k,q]=l.useState(null),R=l.useRef(h??""),ae=f&&!g&&w!=="all"?w==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,O=g?{aggregate:t.currentView.aggregate,groups:[]}:ae,X=l.useCallback(U=>{if(!g||!m)return;const B=U.scope??(D===dn?"all":"group"),H=U.search??y;R.current=H,m({scope:B,...B==="group"?{groupKey:U.groupKey??D}:{},queryClass:U.queryClass??w,...H?{search:H}:{},...U.sort?{sort:U.sort}:{}})},[m,y,w,D,g]);l.useEffect(()=>{!t.currentView||i||(N(t.currentView.queryClass),A(t.currentView.scope.key??dn),t.currentView.sort&&K(t.currentView.sort))},[i,t.currentView]),l.useEffect(()=>{h!==void 0&&(R.current=h,j(U=>U.trim()===h.trim()?U:h))},[h]),l.useEffect(()=>{if(!g||!m||y===R.current)return;const U=window.setTimeout(()=>X({search:y}),Hf);return()=>window.clearTimeout(U)},[m,X,y,g]);const ce=t.availableGroups??O.groups;l.useEffect(()=>{D===dn||ce.some(U=>U.id===D)||A(dn)},[ce,D]);const Y=g?void 0:O.groups.find(U=>U.id===D),_=Y?.aggregate??O.aggregate,I=U=>f?U:Xf,le=V,T=y.trim().toLocaleLowerCase(),ee=l.useMemo(()=>!g&&T?_.properties.filter(U=>U.name.toLocaleLowerCase().includes(T)):_.properties,[_.properties,T,g]),Z=g?ee:ee.slice(0,C),ge=(g?t.currentView?.scope.kind==="group":Y!=null)&&w==="non-brand"&&f&&(g||Y.confirmedCompetitorCount>0)&&(_.shareOfVoice?.length??0)>0,J=f?_.unavailablePropertyCount??0:0,de=t.flaggedResults.reduce((U,B)=>U+(B.count??1),0),xe=t.flaggedResultsTotal??de,se=[I(_.metrics.propertiesMentioned),I(_.metrics.mentionCoverage),I(_.metrics.citationCoverage)].map(dc).find(Boolean),z=f?t.nextActionText??se??(J>0?`${J} ${J===1?"property is":"properties are"} unavailable.`:xe>0?`${xe} flagged ${xe===1?"result needs":"results need"} review.`:null):cc.plan_v1,we=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?ey(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Se=ty(t.latestMeasurement.date),et=[{value:dn,label:"All properties"},...ce.map(U=>({value:U.id,label:U.label}))],Ke=ce.length>Wf;function ze(U){A(U),X(U===dn?{scope:"all"}:{scope:"group",groupKey:U})}function He(U){N(U),X({queryClass:U})}function Ge(U){const B=k!==U;q(B?U:null),B&&b?.(U)}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(ue,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(ue,{tone:"caution",children:"Includes historical data"}):null,we?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:we}):null,Se?e.jsx("span",{className:"text-sm text-secondary",children:Se}):null,z?e.jsx("span",{className:"text-sm text-secondary",children:z}):null,s&&f&&n?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!f?e.jsx(P,{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:Ke?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),Ke?e.jsx("select",{id:"advanced-measurement-group",value:D,onChange:U=>ze(U.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:et.map(U=>e.jsx("option",{value:U.value,children:U.label},U.value))}):e.jsx(Uo,{ariaLabelledBy:"advanced-measurement-group-label",value:D,options:et,onChange:ze})]}),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(Uo,{ariaLabelledBy:"advanced-measurement-class-label",value:w,options:Yf,onChange:He,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:y,onChange:U=>j(U.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&&ge?e.jsx(ry,{values:_.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??ee.length," ",(t.currentView?.propertyTotal??ee.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(iy,{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:[Bf.map(U=>{const B=le.startsWith(`${U.key}-`),H=B&&le.endsWith("-desc")?"descending":B?"ascending":"none";return e.jsx("th",{"aria-sort":H,className:(U.numeric,void 0),children:m?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const Re=`${U.key}-${B&&le.endsWith("-asc")?"desc":"asc"}`;K(Re),X({sort:Re})},"aria-label":`Sort by ${U.label.toLowerCase()}`,children:[U.label,e.jsx(gn,{className:`h-3 w-3 transition-transform ${B?"opacity-100":"opacity-0"} ${H==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):U.label},U.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[Z.map(U=>{const B=k===U.id;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:H=>{sy(H.target)||Ge(U.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[x?x({id:U.id,name:U.name}):U.name,Ko(U.status)||U.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[Ko(U.status)?e.jsx(ue,{tone:U.status.tone,children:U.status.label}):null,U.historical?e.jsx(ue,{tone:"caution",children:"Historical"}):null]}):null,Go(U)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Go(U)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(Jn,{metric:U.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Jn,{metric:U.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{size:"icon",variant:"ghost","aria-expanded":B,"aria-label":B?`Hide details for ${U.name}`:`Show details for ${U.name}`,onClick:()=>Ge(U.id),children:e.jsx(gn,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${B?"rotate-180":""}`,"aria-hidden":"true"})})})]},U.id),B?(U.providers??[]).map(H=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:H.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(Jn,{metric:H.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Jn,{metric:H.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${U.id}:${H.provider}`)):null,B?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(ay,{property:U,onRetryEvidence:p})})},`${U.id}:details`):null]},U.id)}),Z.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 ",Z.length," of ",t.currentView.propertyTotal]}),d?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(P,{size:"sm",variant:"outline",disabled:c,onClick:()=>u(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more properties":"Show 50 more"})]}):g?Z.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",Z.length," of ",t.currentView.propertyTotal]}):null:e.jsx(bi,{shown:Z.length,total:ee.length,itemLabel:"properties",onShowAll:()=>L(Number.MAX_SAFE_INTEGER)})]}),!i&&!T&&xe>0?e.jsx("section",{"aria-label":"Flagged results",className:"border-t border-default pt-4",children:e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:["Flagged results (",xe,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,E).map(U=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(ue,{tone:U.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:U.property}),e.jsx("span",{className:"text-secondary",children:U.summary})]},U.id))}),E<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,E).reduce((U,B)=>U+(B.count??1),0)," of ",xe," flagged results"]}),e.jsx(P,{size:"sm",variant:"outline",onClick:()=>F(U=>Math.min(t.flaggedResults.length,U+Qf)),children:"Show 50 more"})]}):de<xe?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",de," of ",xe," flagged results"]}),g&&t.currentView.nextCursor&&u?e.jsx(P,{size:"sm",variant:"outline",disabled:c,onClick:()=>u(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function uc(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function ly(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 cy({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:o,onRunMeasurement:i,onRetryReport:c,onViewChange:d,onLoadMore:h,onPropertyExpand:m,onRetryEvidence:u,renderPropertyLink:b,isRunningMeasurement:p,isOpeningSetup:x,isViewLoading:g,isLoadingMore:f,isLoadMoreError:w,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(P,{type:"button",size:"sm",disabled:x,onClick:o,children:x?"Opening setup…":uc(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,r==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):r==="error"&&!a?e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load the advanced measurement report."}),c?e.jsx(P,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:c,children:"Retry report"}):null]}):a?e.jsx(oy,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:o,onViewChange:d,onLoadMore:h,onPropertyExpand:m,onRetryEvidence:u,renderPropertyLink:b,isRunningMeasurement:p,isRepublishingSetup:x,isViewLoading:g,isLoadingMore:f,isLoadMoreError:w,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 Pn={numerator:null,denominator:null,reason:"plan_v1"};function dy(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Bo(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function uy(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function my(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function hy(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 xy(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function py(t){const s=new Map;for(const n of t){const a=xy(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function gy(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=py(s.evidence),c=n.executionNodes.reduce((x,g)=>x+g.expectedSnapshots,0),d=s.run?.status==="completed"&&c>0,h=d?c:0,m=d?c:0,u=s.targets.map(x=>{const g=a.get(x.id),f=i.get(x.id)??[],w=f.map(A=>({id:`${A.observationId}:${A.usageEdgeId}:${A.sourceUrl}`,kind:uy(A.classification),query:A.queryText,url:A.sourceUrl,tone:my(A.classification),historical:A.historical||A.bridged})),N=f.some(A=>A.historical||A.bridged),D=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:Bo(x.mentionCoverage),citationCoverage:Bo(x.citationCoverage),status:D,assignedQueries:o.get(x.id)??[],urls:g?.urls.map(dy)??[],evidence:w,historical:N}}),b=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:hy(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Pn,mentionCoverage:Pn,citationCoverage:Pn},properties:u},groups:s.groups.map(x=>({id:x.id,label:x.label,confirmedCompetitorCount:p.get(x.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Pn,mentionCoverage:Pn,citationCoverage:Pn},properties:x.targetIds.map(g=>b.get(g)).filter(g=>!!g)}}))},flaggedResults:[]}}function fy({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":Et.title,children:[e.jsx("h2",{className:"text-xl font-semibold text-heading",children:Et.title}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:t.selection.mode==="advanced"?Et.description:Et.simpleDescription}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:vu(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:[Et.queryType,Et.queries,Et.answers,Et.mentioned,Et.cited].map(a=>e.jsx("th",{children:a},a))})}),e.jsx("tbody",{children:s.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:Ri(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:Ii(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:ju(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:[Et.date,Et.queryType,Et.mentioned,Et.cited,Et.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:Ri(a.queryClass)}),[r.mentionCoverage,r.citationCoverage].map((o,i)=>e.jsxs("td",{children:[Ii(o),e.jsx("p",{className:"text-xs text-secondary",children:$i(o)})]},i)),e.jsx("td",{children:Nu(r.continuity.state,r.continuity.comparedRunId!==null&&!a.trend.some(o=>o.runId===r.continuity.comparedRunId))})]},`${a.queryClass}:${r.runId}`)))})]})})]})]})}const yy={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function bt(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 by(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 vy(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function jy({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[o,i]=l.useState(wu),c=$e({...Su({client:W,path:{name:t},query:{period:o}}),placeholderData:ni});async function d(){n(!0),r(null);try{await Au(t,"client",o)}catch(m){const u=m instanceof pn||m instanceof Error?m.message:"Download failed";r(u)}finally{n(!1)}}if(c.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(c.error){const m=c.error instanceof Error?c.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=c.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"?` · ${Cu(h.visibility)}`:h.meta.location?` · Location: ${vy(h.meta.location)}`:" · No location set"," · ","Last ",h.meta.periodDays," days"," · ","Generated ",by(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(wy,{period:o,onChange:i}),e.jsxs(P,{variant:"secondary",size:"sm",onClick:Ye(d),disabled:s,children:[e.jsx(bl,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),h.visibility?e.jsx(fy,{visibility:h.visibility}):e.jsx(Iy,{report:h}),h.visibility?.selection.mode!=="advanced"&&e.jsx(Ny,{report:h}),!h.visibility&&e.jsx(Ey,{report:h,audience:"client"}),e.jsx(ky,{report:h}),e.jsx(My,{report:h,audience:"client",projectName:t}),e.jsx(Ly,{report:h})]}):null}function Ny({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:Pu(n.percent,n.queryClass,n)}),n.reason?e.jsx("p",{children:tl(n.reason)}):null]},n.queryClass):null)})}function wy({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:ku.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 Vo="AI Visibility — Server-Side",zo="AI engine attention",Sy=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,Cy="Live telemetry from your server logs.";function ky({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ra,{eyebrow:zo,title:Vo,subtitle:Cy}),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:oh(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,r=`vs prior ${a} days`,o=ir(n,"requests",r),i=`${bt(s.verifiedCrawlerHits.current)} verified · ${bt(s.unverifiedCrawlerHits.current)} unverified${o?` · ${o}`:""}`,c=ir(s.aiUserFetchHits,"requests",r),d=ir(s.referralArrivals,"sessions",r),h=s.referralRedirects>0?`${bt(s.referralRedirects)} blocked by redirects`:"",m=[d,s.referralArrivalsClassSummary,h].filter(Boolean).join(" · "),u=s.byOperator.filter(b=>b.verifiedHits>0||b.unverifiedHits>0||b.userFetchHits>0||b.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ra,{eyebrow:zo,title:Vo,subtitle:Sy(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Er,{label:"AI bot requests observed",value:bt(n.current),subtitle:i}),e.jsx(Er,{label:"AI user-fetch requests",value:bt(s.aiUserFetchHits.current),subtitle:c||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(Er,{label:"AI referral sessions",value:bt(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(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:b.operator}),e.jsx("td",{children:bt(b.verifiedHits+b.unverifiedHits)}),e.jsx("td",{children:bt(b.userFetchHits)}),e.jsx("td",{children:bt(b.referralArrivals)})]},b.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 Ay(t,s){return t.audience==="both"||t.audience===s}const Py={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Qa(t){return Py[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Ry(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 Iy({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=Ry(t.whatsChanged.mentionRate),c=n.providers.length>0?n.providers.map(Qa).join(", "):`${bt(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(Lr,{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(Lr,{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(Lr,{label:"AI tools tested",value:bt(s.providerCount),subtitle:c})]}),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((d,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:['"',d,'"']})]},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(d=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:Qa(d.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(d.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[d.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",d.mentionedCount,"/",d.totalCount,")"]})]})]},d.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((d,h)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:d},h))})]})}function Lr({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 $y(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function Ty(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function My({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=>Ay(u,s)),r=hh(t,a),o=s==="client",i=Ru(),[c,d]=l.useState(new Set),h=c.size>0?r.filter(u=>!u.targetRef||!c.has(u.targetRef)):r,m=u=>{if(!u.targetRef)return;const b=u.targetRef;d(p=>new Set(p).add(b)),i.mutate({projectName:n,body:{targetRef:b}},{onSuccess:()=>{Te({tone:"positive",title:`Dismissed "${u.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:p=>{Te({tone:"negative",title:`Couldn't dismiss "${u.title}"`,detail:String(p)}),d(x=>{const g=new Set(x);return g.delete(b),g})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ra,{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(Ni,{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,b)=>{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:b+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(ue,{tone:$u(u),children:o?$y(u.horizon):Iu(u.horizon)}),!o&&e.jsx(ue,{tone:"neutral",children:Tu(u.category)}),e.jsx(ue,{tone:"neutral",children:o?Ty(u.confidence):`${Mu(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(Dy,{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&&!re()&&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 Qo({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 Ly({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=xh(t).slice(0,5),o=s.length>0?Math.max(...s.map(d=>d.count)):0,i=n?Math.max(...n.topQueries.slice(0,5).map(d=>d.impressions),1):0,c=s.length>0||n!==null||a!==null||r.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ra,{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."}),c?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(d=>e.jsx(Qo,{label:d.domain+(d.isCompetitor?" (competitor)":""),value:d.count,displayValue:`${bt(d.count)}×`,max:o,barClass:"bg-mono-400/70"},d.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:[bt(a.indexed)," of ",bt(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:bt(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:bt(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:bt(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(d=>e.jsx(Qo,{label:d.query,value:d.impressions,displayValue:`${bt(d.impressions)} ${d.impressions===1?"search":"searches"}`,max:i,barClass:"bg-info-500/70"},d.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((d,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:d.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[Lu(d.action),d.winnabilityClass==="ceded"&&e.jsx(ue,{tone:"caution",children:"Ceded surface"})]})]},h))})]})]}):e.jsx(Ni,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function vi(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function ji(t){return t==="up"?"↑":t==="down"?"↓":"→"}function qr({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=vi(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}%`:lh(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:ji(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=vi(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=ch(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:[bt(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:ji(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function qy({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=vi(r.direction),c=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?Qa(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:c,children:[o,r.deltaAbs.toFixed(1),"% ",ji(r.direction)]})]},r.provider)})})]})})]})}function Wo({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(ue,{tone:yy[o.severity],children:qu(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?Qa(o.provider):o.provider})]},o.id))})]})})]})}function Ey({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(ra,{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(Ni,{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(qr,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(qr,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(qr,{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(qy,{movements:n.providerMovements,audience:s}),e.jsx(Wo,{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(Wo,{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 Er({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 ra({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 Dy({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 Ni({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function Oy({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(null),[h,m]=l.useState(t.displayName),[u,b]=l.useState(t.canonicalDomain),[p,x]=l.useState(t.country),[g,f]=l.useState(t.language),[w,N]=l.useState(t.ownedDomains??[]),[D,A]=l.useState(""),[y,j]=l.useState(t.aliases??[]),[C,L]=l.useState(""),[E,F]=l.useState(null),[V,K]=l.useState(!1),[k,q]=l.useState(!1),[R,ae]=l.useState(""),[O,X]=l.useState(""),[ce,Y]=l.useState(""),[_,I]=l.useState(""),[le,T]=l.useState(""),[ee,Z]=l.useState(null),[ge,J]=l.useState(null);l.useEffect(()=>{a||(m(t.displayName),b(t.canonicalDomain),x(t.country),f(t.language),N(t.ownedDomains??[]),j(t.aliases??[]))},[t,a]);function de(){r(!1),d(null),m(t.displayName),b(t.canonicalDomain),x(t.country),f(t.language),N(t.ownedDomains??[]),j(t.aliases??[]),A(""),L("")}function xe(){const B=D.trim();B&&(w.includes(B)||N([...w,B]),A(""))}function se(B){N(w.filter(H=>H!==B))}function z(){const B=C.trim();if(!B)return;const H=B.toLowerCase();y.some(Re=>Re.toLowerCase()===H)||j([...y,B]),L("")}function ne(B){j(y.filter(H=>H!==B))}async function Ee(){if(!(!h.trim()||!u.trim()||!p.trim()||!g.trim())){i(!0),d(null);try{await s(t.name,{displayName:h.trim(),canonicalDomain:u.trim(),ownedDomains:w,aliases:y,country:p.trim(),language:g.trim()}),r(!1),Te({title:"Project settings saved",detail:`${h.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(B){d(B instanceof Error?B.message:"Failed to save")}finally{i(!1)}}}async function we(){const B=R.trim(),H=O.trim(),Re=ce.trim(),_e=_.trim();if(!(!B||!H||!Re||!_e)){K(!0),F(null);try{const Ue={label:B,city:H,region:Re,country:_e};le.trim()&&(Ue.timezone=le.trim()),await Ou(t.name,Ue),n(),ae(""),X(""),Y(""),I(""),T(""),q(!1),Te({title:"Location added",detail:`${B} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${B}`,dedupeMode:"drop"})}catch(Ue){F(Ue instanceof Error?Ue.message:"Failed to add location")}finally{K(!1)}}}async function Se(B){K(!0),F(null);try{await Du(t.name,B),n(),Te({title:"Location removed",detail:`${B} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${B}`,dedupeMode:"drop"})}catch(H){F(H instanceof Error?H.message:"Failed to remove location")}finally{K(!1)}}async function et(B){K(!0),F(null);try{await Eu(t.name,B),n(),Te({title:"Default location updated",detail:`${B} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(H){F(H instanceof Error?H.message:"Failed to set default location")}finally{K(!1)}}async function Ke(B){Z(B),J(null);try{await Fu(t.name,B),Te({title:`${B.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(H){J(H instanceof Error?H.message:"Could not download tracking results.")}finally{Z(null)}}const ze=h!==t.displayName||u!==t.canonicalDomain||p!==t.country||g!==t.language||JSON.stringify(w)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(y)!==JSON.stringify(t.aliases??[]),He="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",Ge="mb-1 block text-sm font-medium text-secondary",U=R.trim()&&O.trim()&&ce.trim()&&_.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!re()&&!a&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),c&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[c,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>d(null),children:"×"})]}),!re()&&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:Ge,children:"Display name"}),e.jsx("input",{className:He,type:"text",value:h,onChange:B=>m(B.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ge,children:"Canonical domain"}),e.jsx("input",{className:He,type:"text",value:u,onChange:B=>b(B.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ge,children:"Country"}),e.jsx("input",{className:He,type:"text",value:p,onChange:B=>x(B.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ge,children:"Language"}),e.jsx("input",{className:He,type:"text",value:g,onChange:B=>f(B.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ge,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:w.map(B=>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:[B,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>se(B),"aria-label":`Remove ${B}`,children:"×"})]},B))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${He} flex-1`,type:"text",placeholder:"docs.example.com",value:D,onChange:B=>A(B.target.value),onKeyDown:B=>B.key==="Enter"&&(B.preventDefault(),xe())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!D.trim(),onClick:xe,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ge,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:y.map(B=>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:[B,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>ne(B),"aria-label":`Remove ${B}`,children:"×"})]},B))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${He} flex-1`,type:"text",placeholder:"Facebook",value:C,onChange:B=>L(B.target.value),onKeyDown:B=>B.key==="Enter"&&(B.preventDefault(),z())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!C.trim(),onClick:z,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(P,{type:"button",disabled:o||!ze||!h.trim()||!u.trim(),onClick:Ye(Ee),children:o?"Saving...":"Save changes"}),e.jsx(P,{type:"button",variant:"outline",disabled:o,onClick:de,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(B=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:B},B))}):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(B=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:B},B))}):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:[E&&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:[E,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>F(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(B=>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 ${B.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[B.label,B.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:B.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:B.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:B.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:B.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!re()&&B.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:V,onClick:()=>{et(B.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${B.label} as default location`,children:"Set default"}),!re()&&e.jsx("button",{type:"button",disabled:V,onClick:()=>{Se(B.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${B.label}`,children:"Remove"})]})})]},B.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),re()?null: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:He,type:"text",value:R,onChange:B=>ae(B.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:He,type:"text",value:O,onChange:B=>X(B.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:He,type:"text",value:ce,onChange:B=>Y(B.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:He,type:"text",value:_,onChange:B=>I(B.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:He,type:"text",value:le,onChange:B=>T(B.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(P,{type:"button",size:"sm",disabled:V||!U,onClick:Ye(we),children:V?"Adding...":"Add location"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:V,onClick:()=>{q(!1),F(null)},children:"Cancel"})]})]}):e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>q(!0),children:"+ Add location"})]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted",children:"Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"max-w-xl text-xs leading-5 text-muted",children:"Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ee!==null,onClick:Ye(()=>Ke("csv")),children:ee==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ee!==null,onClick:Ye(()=>Ke("json")),children:ee==="json"?"Preparing JSON...":"Download JSON"})]})]}),ge&&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:ge})]})]})]})}function Qn(t){return{...t??{}}}function Fy(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 c=a[i];return c?.[0]===r&&c[1]===o})}function Ky({project:t,onSave:s}){const{isAdmin:n}=bn(),a=$e({queryKey:["settings"],queryFn:il,staleTime:6e4,enabled:n&&!re()}),[r,o]=l.useState(t.providers.length===0),[i,c]=l.useState(t.providers),[d,h]=l.useState(()=>Qn(t.providerModels)),[m,u]=l.useState({providers:t.providers,providerModels:Qn(t.providerModels)}),[b,p]=l.useState(!1),[x,g]=l.useState(!1),[f,w]=l.useState(null),[N,D]=l.useState(null),A=l.useRef(null),y=a.data?.providerCatalog??[],j=l.useMemo(()=>new Set((a.data?.providers??[]).filter(q=>q.configured).map(q=>q.name)),[a.data]),C=l.useMemo(()=>{const q=new Map(a.data?.providers.map(ae=>[ae.name,ae.model])),R=new Map(y.map(ae=>[ae.name,{...ae,defaultModel:q.get(ae.name)||ae.defaultModel}]));for(const ae of Object.keys(d))R.has(ae)||R.set(ae,{name:ae,displayName:ae,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...R.values()].sort((ae,O)=>ae.displayName.localeCompare(O.displayName))},[y,d,a.data?.providers]),L=!Fy(d,m.providerModels);l.useEffect(()=>{if(b||x)return;const q={providers:t.providers,providerModels:Qn(t.providerModels)};u(q),o(q.providers.length===0),c(q.providers),h(q.providerModels)},[t]);function E(){g(!0),o(!1),i.length===0&&c([...j])}function F(q,R,ae=!1){g(!0),h(O=>{const X={...O};return R==="__inherit__"?delete X[q]:R==="__custom__"?X[q]=ae?"":X[q]??"":X[q]=R,X}),R==="__custom__"&&queueMicrotask(()=>A.current?.focus())}function V(q,R){g(!0),c(ae=>R?[...new Set([...ae,q])]:ae.filter(O=>O!==q))}function K(){g(!1),o(m.providers.length===0),c(m.providers),h(Qn(m.providerModels)),w(null),D(null)}async function k(){if(!(a.isError||a.isLoading||!r&&i.length===0)){p(!0),w(null),D(null);try{const q=Object.fromEntries(Object.entries(d).filter(([ae,O])=>O.trim()!==""&&(r||i.includes(ae)))),R={providers:r?[]:i,providerModels:q};await s(R),u({providers:[...R.providers],providerModels:Qn(R.providerModels)}),g(!1),D("Engine settings saved. They apply on the next sweep.")}catch(q){w(ea(q))}finally{p(!1)}}}return re()||!n?null:a.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):a.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):y.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):j.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":b,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:b,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:E})," Choose engines"]}),!r&&e.jsx("div",{className:"project-engine-list",children:C.map(q=>{const R=i.includes(q.name),ae=j.has(q.name),O=R&&!ae,X=d[q.name],ce=q.knownModels.some(_=>_.id===X),Y=X===void 0?"__inherit__":ce?X:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:R,disabled:!ae&&!R,onChange:_=>V(q.name,_.target.checked)})," ",e.jsx("span",{children:q.displayName}),O&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),R&&(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:Y,onChange:_=>F(q.name,_.target.value,ce),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",q.defaultModel||"default"]}),q.knownModels.map(_=>e.jsx("option",{value:_.id,children:_.displayName},_.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),Y==="__custom__"&&e.jsx("input",{ref:A,"aria-label":`${q.displayName} custom model ID`,value:X??"",onChange:_=>{g(!0),h(I=>({...I,[q.name]:_.target.value}))},"aria-describedby":`project-model-hint-${q.name}`}),e.jsxs("p",{id:`project-model-hint-${q.name}`,className:"project-engine-help",children:[X?"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(P,{type:"button",onClick:()=>{k()},disabled:b||!r&&i.length===0,children:b?"Saving engines…":"Save engines"}),e.jsx(P,{type:"button",variant:"outline",onClick:K,disabled:b,children:"Cancel"})]})]})}const La={edit:"Edit schedule",pause:"Pause",resume:"Resume",save:"Save schedule"},Gy=[{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"}],Yo=["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 Dr(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),c=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 ${c} · ${n}`}function _y({projectName:t}){const s=Bt(),n=!re()&&!s,a=ms(),[r,o]=l.useState(!1),[i,c]=l.useState("daily"),[d,h]=l.useState(6),[m,u]=l.useState(""),[b,p]=l.useState(14),[x,g]=l.useState(""),[f,w]=l.useState("00:00"),[N,D]=l.useState("UTC"),[A,y]=l.useState(!1),[j,C]=l.useState(""),[L,E]=l.useState(!1),[F,V]=l.useState(!1),[K,k]=l.useState(null),[q,R]=l.useState(void 0),ae=Ku({client:W,path:{name:t}}),O=$e({...ml({client:W,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),X=O.isPending||O.isFetching,ce=O.isError,Y=O.data?.find(se=>se.kind==="answer-visibility")??null,_=r&&q!==void 0&&(Y?.updatedAt??null)!==q,I=se=>{a.setQueryData(ae,z=>{const ne=(z??[]).filter(Ee=>Ee.kind!=="answer-visibility");return se?[...ne,se]:ne})},le=se=>{if(se){if(se.recurrence)c("calendar"),p(se.recurrence.everyDays),g(se.recurrence.startDate),w(se.recurrence.time);else{const ne=Bu(se.preset??null,se.cronExpr);c(ne.freq),h(ne.hour),u(ne.customCron)}const z=Yo.includes(se.timezone);D(z?se.timezone:"Other"),y(!z),C(z?"":se.timezone)}else c("daily"),h(6),u(""),p(14),g(""),w("00:00"),D("UTC"),y(!1),C("");R(se?.updatedAt??null)},T=()=>{n&&(le(Y),k(null),o(!0))},ee=()=>{le(Y),k(null)},Z=async()=>{(await O.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.")},ge=async(se,z)=>{if(se instanceof pn&&se.code==="SCHEDULE_VERSION_CONFLICT"){await Z();return}k(se instanceof Error?se.message:z)},J=async()=>{if(n&&!(_||q===void 0)){E(!0),k(null);try{const se=await O.refetch();if(se.isError||se.data===void 0){k("Canonry could not verify the latest schedule. Try again before saving.");return}const z=se.data.find(Se=>Se.kind==="answer-visibility")??null;if((z?.updatedAt??null)!==q)return;const Ee={timezone:A?j.trim()||"UTC":N,enabled:z?.enabled??!0,providers:z?.providers??[],expectedUpdatedAt:q};i==="calendar"?Ee.recurrence={everyDays:b,startDate:x,time:f}:i==="custom"?Ee.cron=m.trim():Ee.preset=Uu(i,d);const we=await Ti(t,Ee);o(!1),R(void 0),I(we),Te({title:"Schedule saved",detail:we.recurrence?Dr(we.recurrence,we.timezone):ar(we.preset??null,we.cronExpr,we.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(se){await ge(se,"Failed to save schedule")}finally{E(!1)}}},de=async()=>{if(!n||!Y)return;const se=Y.updatedAt;E(!0),k(null);try{const z=await O.refetch();if(z.isError||z.data===void 0){k("Canonry could not verify the latest schedule. Try again before updating it.");return}const ne=z.data.find(Se=>Se.kind==="answer-visibility")??null;if(!ne||ne.updatedAt!==se){k("This schedule changed elsewhere. Review the latest version and try again.");return}const Ee={timezone:ne.timezone,enabled:!ne.enabled,providers:ne.providers,expectedUpdatedAt:se};ne.recurrence?Ee.recurrence=ne.recurrence:ne.preset?Ee.preset=ne.preset:Ee.cron=ne.cronExpr;const we=await Ti(t,Ee);I(we),Te({title:we.enabled?"Schedule resumed":"Schedule paused",detail:we.recurrence?Dr(we.recurrence,we.timezone):ar(we.preset??null,we.cronExpr,we.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(z){await ge(z,"Failed to update schedule")}finally{E(!1)}},xe=async()=>{if(!n||!Y)return;const se=Y.updatedAt;V(!0),k(null);try{await _u(t,se),I(null),o(!1),R(void 0),Te({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(z){await ge(z,"Failed to remove schedule")}finally{V(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),n&&!X&&!ce&&!r&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:T,children:Y?La.edit:"+ Set schedule"})]}),X&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),K&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:K}),!X&&ce&&e.jsxs(ye,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{O.refetch()},children:"Retry"})]}),!X&&!ce&&!r&&Y===null&&e.jsx(ye,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?Js:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!X&&!ce&&!r&&Y!==null&&e.jsx(ye,{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:Js}),e.jsx("p",{className:"text-sm font-medium text-strong",children:Y.recurrence?Dr(Y.recurrence,Y.timezone):ar(Y.preset??null,Y.cronExpr,Y.timezone)}),!Y.recurrence&&e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:Y.cronExpr})]}),Y.enabled&&Y.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",dh(Y.nextRunAt,Y.timezone)]}),Y.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(Y.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(ue,{tone:Y.enabled?"positive":"neutral",children:Y.enabled?"Active":"Paused"}),n&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:L,onClick:Ye(de),children:Y.enabled?La.pause:La.resume}),n&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:F,onClick:Ye(xe),children:F?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[_&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",role:"alert",children:[e.jsx("p",{children:"This schedule changed elsewhere. Load the latest version before saving."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:ee,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:se=>c(se.target.value),children:Gy.map(se=>e.jsx("option",{value:se.value,children:se.label},se.value))})]}),i!=="calendar"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:d,disabled:i==="twice-daily"||i==="custom",onChange:se=>h(parseInt(se.target.value)),children:Array.from({length:24},(se,z)=>e.jsx("option",{value:z,children:Gu(z)},z))})]})]}),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:se=>u(se.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:b,onChange:se=>p(Number(se.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:se=>g(se.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:se=>w(se.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:se=>{se.target.value==="Other"?(y(!0),D("Other")):(y(!1),D(se.target.value))},children:[Yo.map(se=>e.jsx("option",{value:se,children:se},se)),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:j,onChange:se=>C(se.target.value)})]}),K&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:K}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{o(!1),R(void 0),k(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:L||O.isFetching||ce||_||i==="custom"&&!m.trim()||i==="calendar"&&(!Number.isInteger(b)||b<1||b>3650||!x||!f),onClick:Ye(J),children:L?"Saving...":La.save})]})]})]})}const Uy=[{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 By({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[o,i]=l.useState(""),[c,d]=l.useState(["citation.lost","citation.gained"]),[h,m]=l.useState(!1),[u,b]=l.useState(null),[p,x]=l.useState({}),[g,f]=l.useState(new Set);l.useEffect(()=>{Vu(t).then(n).catch(()=>n([]))},[t]);const w=y=>{d(j=>j.includes(y)?j.filter(C=>C!==y):[...j,y])},N=async()=>{if(!(!o.trim()||c.length===0)){m(!0),b(null);try{const y=await zu(t,{channel:"webhook",url:o.trim(),events:c});n(j=>j==="loading"?[y]:[...j,y]),i(""),d(["citation.lost","citation.gained"]),r(!1),Te({title:"Webhook added",detail:`Notifications will be sent to ${y.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(y){b(y instanceof Error?y.message:"Failed to add webhook")}finally{m(!1)}}},D=async y=>{if(!g.has(y)){f(j=>new Set(j).add(y));try{await Hu(t,y),n(j=>j==="loading"?j:j.filter(C=>C.id!==y)),Te({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${y}`,dedupeMode:"drop"})}catch(j){b(j instanceof Error?j.message:"Failed to remove webhook")}finally{f(j=>{const C=new Set(j);return C.delete(y),C})}}},A=async y=>{x(j=>({...j,[y]:{state:"testing"}}));try{const j=await Qu(t,y);x(C=>({...C,[y]:{state:j.ok?"ok":"fail",status:j.status}})),j.ok&&Te({title:"Test notification sent",detail:`Webhook returned status ${j.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${y}`,dedupeMode:"replace"})}catch{x(j=>({...j,[y]:{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"})]}),!re()&&s!=="loading"&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),b(null)},children:a?"Cancel":"+ Add webhook"})]}),!re()&&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:y=>i(y.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:Uy.map(y=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:c.includes(y.value),onChange:()=>w(y.value)}),e.jsx("span",{className:"text-sm text-neutral",children:y.label})]},y.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(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),b(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:h||!o.trim()||c.length===0,onClick:Ye(N),children:h?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(ye,{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(y=>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:y.urlHost,children:y.urlDisplay??y.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:y.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(ue,{tone:y.enabled?"positive":"neutral",children:y.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[p[y.id]&&(()=>{const j=p[y.id],C=j.state==="testing"?"Sending…":j.state==="ok"?`Delivered${j.status?` (${j.status})`:""}`:`Failed${j.status?` (${j.status})`:""}`;return e.jsx(ue,{tone:j.state==="ok"?"positive":j.state==="fail"?"negative":"neutral",children:C})})(),!re()&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:p[y.id]?.state==="testing",onClick:()=>{A(y.id)},children:"Test"}),!re()&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:g.has(y.id),onClick:()=>{D(y.id)},children:g.has(y.id)?"Removing…":"Remove"})]})})]},y.id))})]}),u&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:u})]})]})}function Vy({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:o}){return re()||Bt()?null:e.jsx(Yu,{open:t,onOpenChange:n,children:e.jsxs(Ju,{onCloseAutoFocus:i=>{r&&(i.preventDefault(),r())},children:[e.jsxs(Xu,{children:[e.jsx(Zu,{children:"Run AI sweep for the whole project?"}),e.jsxs(em,{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(P,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(Je,{disabled:o,onClick:a,children:"Run project-wide sweep"})]})]})})}const Jo=2e3,Xo=3e5;function zy(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Qy(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 Hy({projectName:t,refreshNonce:s}){const n=ms(),[a,r]=l.useState(null),[o,i]=l.useState([]),[c,d]=l.useState(null),[h,m]=l.useState([]),[u,b]=l.useState([]),[p,x]=l.useState(null),[g,f]=l.useState(""),[w,N]=l.useState(""),[D,A]=l.useState(""),[y,j]=l.useState(!0),[C,L]=l.useState(!1),[E,F]=l.useState(null),[V,K]=l.useState("performance");l.useEffect(()=>{k()},[t,s]);async function k(){j(!0),F(null);try{const I=await n.fetchQuery({...yl({client:W,path:{name:t}}),staleTime:Ut});if(r(I),I.connected){const[le,T,ee,Z]=await Promise.all([n.fetchQuery({...km({client:W,path:{name:t}}),staleTime:Ut}).catch(()=>null),n.fetchQuery({...Am({client:W,path:{name:t}}),staleTime:Ut}).catch(()=>[]),n.fetchQuery({...Pm({client:W,path:{name:t}}),staleTime:Ut}).catch(()=>[]),I.siteUrl?Promise.resolve([]):n.fetchQuery({...Rm({client:W,path:{name:t}}),staleTime:Ut}).then(ge=>ge.sites).catch(()=>[])]);d(le),m(T),b(ee),i(Z)}else d(null),m([]),b([]),i([])}catch(I){F(I instanceof Error?I.message:"Failed to load Bing data")}finally{j(!1)}}async function q(){if(w.trim()){F(null);try{const I=await Im(t,w.trim());await Nt(n,"bing"),N(""),I.availableSites.length>0&&i(I.availableSites),await k()}catch(I){F(I instanceof Error?I.message:"Failed to connect")}}}async function R(){try{await $m(t),await Nt(n,"bing"),r(null),i([]),d(null),m([]),b([]),x(null),A(""),F(null)}catch(I){F(I instanceof Error?I.message:"Failed to disconnect")}}async function ae(){if(D)try{await Tm(t,D),await Nt(n,"bing"),await k()}catch(I){F(I instanceof Error?I.message:"Failed to set site")}}async function O(){if(g.trim())try{const I=await Mm(t,g.trim());await Nt(n,"bing"),x(I),m(le=>[I,...le])}catch(I){F(I instanceof Error?I.message:"Inspection failed")}}async function X(I){L(!0),F(null);try{const le=await qi(t,{urls:[I]}),{succeeded:T,failed:ee,total:Z}=le.summary;Te({title:"Bing submission requested",detail:ee===0?`${T} URL submitted to Bing.`:`${T}/${Z} submitted successfully, ${ee} failed.`,tone:ee===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${I}`,dedupeMode:"replace"})}catch(le){const T=le instanceof Error?le.message:"Submission failed";F(T),Te({title:"Bing submission failed",detail:T,tone:"negative",dedupeKey:`bing:indexing:${t}:${I}`,dedupeMode:"replace"})}finally{L(!1)}}async function ce(){L(!0),F(null),Te({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const I=await qi(t,{allUnindexed:!0}),{succeeded:le,failed:T,total:ee}=I.summary;Te({title:"Bing submissions requested",detail:T===0?`${le}/${ee} URL${ee!==1?"s":""} submitted to Bing.`:`${le}/${ee} submitted successfully, ${T} failed.`,tone:T===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(I){const le=I instanceof Error?I.message:"Batch submission failed";F(le),Te({title:"Bing submissions failed",detail:le,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{L(!1)}}if(y)return e.jsx(ye,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return re()?e.jsxs(ye,{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(ue,{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(ye,{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(ue,{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:w,onChange:I=>N(I.target.value),onKeyDown:I=>{I.key==="Enter"&&q()}}),e.jsx(Je,{size:"sm",disabled:!w.trim(),onClick:Ye(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"})]})]}),E&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:E})]});if(!a.siteUrl)return e.jsxs(ye,{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(ue,{tone:"positive",children:"Connected"}),!re()&&e.jsx(Je,{size:"sm",variant:"ghost",onClick:Ye(R),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.domain})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Wt(a.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Select site"}),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:D,onChange:I=>A(I.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),o.map(I=>e.jsxs("option",{value:I.url,children:[I.url,I.verified?" (verified)":""]},I.url))]}),!re()&&e.jsx(Je,{size:"sm",disabled:!D,onClick:Ye(ae),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."})]})]}),E&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:E})]});const Y=[{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"}],_=Y.find(I=>I.key===V)??Y[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ye,{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(ue,{tone:"positive",children:"Connected"}),!re()&&e.jsx(Je,{size:"sm",variant:"ghost",onClick:Ye(R),children:"Disconnect"})]})]}),E&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:E}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["This project uses ",e.jsx("code",{children:a.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Wt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(ye,{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:_.eyebrow}),e.jsx("h3",{children:_.title})]}),e.jsx("p",{className:"text-xs text-muted",children:c?.lastInspectedAt?`Last inspected ${Wt(c.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:Y.map(I=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${V===I.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>K(I.key),children:I.label},I.key))}),V==="coverage"&&c&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(va,{label:"Indexed",value:c.summary.indexed,tone:"positive"}),e.jsx(va,{label:"Not in index",value:c.summary.notIndexed+(c.summary.unknown??0),tone:"negative"}),e.jsx(va,{label:"Status unknown",value:c.summary.unknown??0,tone:"neutral"}),e.jsx(va,{label:"Coverage",value:`${c.summary.percentage}%`,tone:"neutral"})]}),c.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",c.notIndexed.length,")"]}),!re()&&e.jsx(Je,{size:"sm",variant:"ghost",disabled:C,onClick:Ye(ce),children:C?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!re()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:c.notIndexed.map(I=>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:I.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:I.httpCode??"—"}),!re()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:C,onClick:()=>{X(I.url)},children:"Submit"})})]},I.id))})]})})]}),(c.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(c.unknown??[]).length,")"]}),!re()&&e.jsx(Je,{size:"sm",variant:"ghost",disabled:C,onClick:Ye(ce),children:C?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!re()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(c.unknown??[]).map(I=>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:I.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:I.lastCrawledDate?Wt(I.lastCrawledDate):"—"}),!re()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:C,onClick:()=>{X(I.url)},children:"Submit"})})]},I.id))})]})})]}),c.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",c.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:c.indexed.map(I=>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:I.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:I.lastCrawledDate?Wt(I.lastCrawledDate):"—"})]},I.id))})]})})]})]}),V==="coverage"&&!c&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),V==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!re()&&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:I=>f(I.target.value),onKeyDown:I=>{I.key==="Enter"&&O()}}),e.jsx(Je,{size:"sm",disabled:!g.trim(),onClick:Ye(O),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(I=>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:I.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(ue,{tone:I.inIndex?"positive":"negative",children:I.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:I.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Wt(I.inspectedAt)})]},I.id))})]})})]}),V==="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:ba[hn.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:ba[hn.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:ba[hn.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:ba[hn.Position]})]})}),e.jsx("tbody",{children:u.map((I,le)=>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:I.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:I.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:I.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(I.ctr)?I.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:I.averagePosition.toFixed(1)})]},le))})]})})})]})]})}function Wy({projectName:t}){const s=ms(),[n,a]=l.useState("google"),[r,o]=l.useState(!0),[i,c]=l.useState("idle"),[d,h]=l.useState(null),m=l.useRef(null),[u,b]=l.useState(null),[p,x]=l.useState(null),[g,f]=l.useState(0);async function w(D=!1){D||o(!0),h(null);try{const[A,y]=await Promise.all([s.fetchQuery({...ai({client:W,path:{name:t}}),staleTime:Ut}).catch(()=>[]),s.fetchQuery({...yl({client:W,path:{name:t}}),staleTime:Ut}).catch(()=>null)]),j=A.find(C=>C.connectionType==="gsc")??null;b(j),x(y)}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 D=new AbortController;m.current=D;const A=D.signal;c("syncing"),h(null),Te({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const y=[],j=[];try{async function C(){if(!u)return;const F=await Sm(t);if(!F?.id)return;const V=Date.now()+Xo;for(;Date.now()<V;){if(A.aborted||(await new Promise(k=>setTimeout(k,Jo)),A.aborted))return;const K=await Fr(F.id).catch(()=>null);if(!K)break;if(["completed","failed","cancelled"].includes(K.status)){K.status!=="completed"&&y.push(`Google sync ${K.status}`);return}}j.push("Google sync is still running — search data will appear shortly")}async function L(){if(!p?.connected)return;const F=await Cm(t).catch(()=>null);if(!F?.id){y.push("Bing sweep could not be started");return}const V=Date.now()+Xo;for(;Date.now()<V;){if(A.aborted||(await new Promise(k=>setTimeout(k,Jo)),A.aborted))return;const K=await Fr(F.id).catch(()=>null);if(!K)break;if(["completed","failed","cancelled","partial"].includes(K.status)){K.status==="failed"?y.push("Bing sweep failed"):K.status==="partial"&&j.push("Bing sweep finished with some pages unverified");return}}j.push("Bing sweep is still running — coverage will update shortly")}const E=await Promise.allSettled([C(),L()]);for(const F of E)F.status==="rejected"&&y.push(F.reason instanceof Error?F.reason.message:"Sync failed");if(await Promise.all([Nt(s,"gsc"),Nt(s,"bing")]),A.aborted)return;if(c("reloading"),await w(!0),f(F=>F+1),y.length>0){const F=`Partial refresh: ${[...y,...j].join("; ")}`;h(F),Te({title:"Search coverage partially refreshed",detail:F,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else j.length>0?Te({title:"Search coverage refresh incomplete",detail:j.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):Te({title:"Search coverage refreshed",detail:"Google and Bing workspaces are reloaded with the latest stored coverage.",tone:"positive",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}catch(C){if(!A.aborted){const L=C instanceof Error?C.message:"Refresh failed";h(L),Te({title:"Search coverage refresh failed",detail:L,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{A.aborted||c("idle")}}return l.useEffect(()=>(w(),()=>{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(([D,A])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===D,className:`project-subnav-link ${n===D?"project-subnav-link-active":""}`,onClick:()=>a(D),children:A},D))}),!re()&&e.jsxs(Je,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{N()},children:[e.jsx(ta,{className:`h-3.5 w-3.5 ${i!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":i==="syncing"?"Refreshing search data…":i==="reloading"?"Reloading workspaces…":"Refresh search data"]})]}),d&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:d}),n==="google"&&e.jsx(fx,{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(Hy,{projectName:t,refreshNonce:g})]})]})}function Ha({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 ${el[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 Yy({model:t,sweepRunning:s,hasVisibilityBaseline:n}){const a=t.citationMovement,r=t.mentionMovement,o=t.movementComparison,i=t.recentRuns.find(p=>p.kind===Ys["answer-visibility"]&&(p.status===Ka.completed||p.status===Ka.partial)),c=p=>p.tone==="positive"?"improved":p.tone==="negative"?"declined":p.gained>0||p.lost>0?"mixed":"steady",d=c(r),h=c(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(d===h)return d==="steady"?"Answer mentions and citation coverage held steady":d==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${d}`;const p=d==="mixed"?"Answer mention movement was mixed":d==="steady"?"Answer mentions held steady":`Answer mentions ${d}`,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(", "),b=`${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(Ha,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(Ha,{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"} · ${b}.`:`${b}.`})]}):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:Bt()?Js:"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.":Bt()?Js:"Complete your first AI Visibility sweep to measure both signals."})]})})]})}function Or({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(gn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:o})]})}function Jy({insights:t,suggestedQueries:s,onManageQueries:n}){const{openEvidence:a}=sl(),r=n?s.rows:[];if(t.length===0&&r.length===0)return null;const o=b=>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:b.title}),b.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:b.detail}):null]}),e.jsx(ue,{tone:b.tone,children:b.actionLabel})]}),b.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 · ",b.affectedPhrases.length," affected ",b.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:b.affectedPhrases.map((p,x)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(Gr,{state:p.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:p.query}),p.provider?e.jsx(Ln,{provider:p.provider}):null,!re()&&p.evidenceId?e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(p.evidenceId)},children:"View evidence"}):null]},p.evidenceId||`${b.id}-${x}`))})]}):null]},b.id),i=b=>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:b.query}),e.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:b.reason})]}),n?e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},b.query),c=t.slice(0,1),d=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:[c.map(o),d.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 xb(t){const{projectName:s}=hc({from:"/projects/$projectName"}),a=hl()?.dashboard.projects.find(j=>j.project.name===s||j.project.id===s)?.project.name??null,r=$e({...Wu({client:W}),enabled:!a}),o=a??r.data?.find(j=>j.name===s||j.id===s)?.name??null,i=xl(),c=pl(t.tab,i?gl(i.projectTabs):void 0),[d,h]=l.useState(null),m=o!==null&&d===o,u=l.useCallback(()=>{o&&h(o)},[o]),{commandCenter:b,isLoading:p,overviewLoading:x,overviewError:g,isError:f,latestVisibilityRevision:w,competitorHistoryRevision:N,refetch:D}=fl(o,{overview:c==="overview"&&m}),A=!a&&r.isLoading||p;return!o&&!a&&r.isSuccess&&!p?e.jsx("div",{className:"page-container",children:e.jsxs(ye,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(P,{asChild:!0,children:e.jsx(As,{to:"/",children:"Return to overview"})})]})}):!b&&(f||r.isError)?e.jsxs("div",{className:"page-container",role:"alert",children:[e.jsx("p",{children:"Could not load this project."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{Promise.all([r.refetch(),D()])},children:"Retry"})]}):!b||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(j=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},j))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(j=>e.jsx("div",{className:"skeleton-text-sm w-full"},j))})]})]}):e.jsx(eb,{model:b,refetch:D,latestVisibilityRevision:w,competitorHistoryRevision:N,overviewLoading:x,overviewError:g,overviewRequested:m,onRequestOverview:u,...t})}function Xy({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(null);l.useLayoutEffect(()=>{const m=r.current,u=o.current;if(!m||!u)return;const b=()=>{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(j=>[j.dataset.projectTab,j.getBoundingClientRect().width])),w=j=>f.get(j)??0,N=j=>j.reduce((C,L)=>C+w(L),0)+Math.max(0,j.length-1)*g,D=[...t.map(j=>j.key),...s.length?["more"]:[],...n?[n.key]:[]];let A=t.map(j=>j.key),y=!1;if(N(D)>x){const j=t.find(E=>E.key===a),C=j?[j.key]:[];y=!!(n&&N([...C,"more",n.key])>x);const L=["more",...n&&!y?[n.key]:[]];for(const E of t)if(E.key!==j?.key){if(N([...C,E.key,...L])>x)break;C.push(E.key)}A=t.filter(E=>C.includes(E.key)).map(E=>E.key)}c(j=>j?.settingsInMore===y&&j.visibleKeys.join()===A.join()?j:{visibleKeys:A,settingsInMore:y})};if(b(),typeof ResizeObserver>"u")return window.addEventListener("resize",b),()=>window.removeEventListener("resize",b);const p=new ResizeObserver(b);return p.observe(m),p.observe(u),()=>p.disconnect()},[t,s,n,a]);const d=i?t.filter(m=>i.visibleKeys.includes(m.key)):t,h=[...t.filter(m=>!d.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(gn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),d.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(Zy,{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 Zy({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null),o=l.useRef(null),i=l.useRef("first"),c=l.useId(),d=t.map(m=>m.key).join();if(l.useEffect(()=>{a(!1)},[d]),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=b=>{r.current&&!r.current.contains(b.target)&&a(!1)},u=b=>{b.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?c: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(gn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:c,"aria-label":"More project sections",onKeyDown:m=>{const u=[...m.currentTarget.querySelectorAll('[role="menuitem"]')],b=u.indexOf(document.activeElement),p=m.key==="Home"?0:m.key==="End"?u.length-1:m.key==="ArrowDown"?(b+1)%u.length:m.key==="ArrowUp"?(b-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 eb({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r,overviewLoading:o,overviewError:i,overviewRequested:c,onRequestOverview:d}){const h=xc(),m=ms(),{canWrite:u}=bn(),[b,p]=l.useState(null),x=l.useRef(null),g=hl(),f=s.project.name,w=g?.dashboard.projects.some($=>$.project.name===f)??!1,N=$e({...tm({client:W,path:{name:f}}),enabled:!re()&&!!f&&(u||t==="portfolio"||t==="overview"||t==="settings"),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),D=g?g.dashboard.settings.providerStatuses.filter($=>$.state==="ready").map($=>Mi($.name)):void 0,A=N.data?.answerVisibilityProviderReady,y=D,j=s.project.providers.map(Mi),C=y?.some($=>j.length===0||j.includes($))===!0,L=j.length===0||j.includes(sm),E=$e({...nm({client:W}),enabled:!re()&&u&&A===void 0&&L&&!C,staleTime:6e4,retry:!1}),F=L?E.isSuccess?typeof E.data.browserVersion=="string":E.isError?!1:void 0:!1,V=A??am({projectProviders:j,configuredApiProviders:y,cdpConfigured:F}),K=l.useMemo(()=>{const $=xl();return $?gl($.projectTabs):void 0},[]),k=pl(t,K),q=l.useMemo(()=>s.competitors.map($=>$.domain),[s.competitors]),[R,ae]=l.useState(!1),[O,X]=l.useState(!1),ce=rm(),Y=pc({strict:!1}),_=jh(Y),I=l.useCallback($=>{h({to:".",search:fe=>Nh(fe,$)})},[h]),le=Y.manageQueries===!0,T=l.useCallback(()=>{h({to:".",replace:!0,search:$=>({...$,siteHealthRunId:void 0})})},[h]),[ee,Z]=l.useState(le),[ge,J]=l.useState(""),[de,xe]=l.useState(!1),[se,z]=l.useState(null),[ne,Ee]=l.useState("30d"),[we,Se]=l.useState(void 0),[et,Ke]=l.useState(!1),[ze,He]=l.useState(null),[Ge,U]=l.useState(!1),B=$l(Y),[H,Re]=l.useState(void 0),[_e,Ue]=l.useState(void 0),ie=l.useCallback($=>{Re($.search),$.sort&&Ue($.sort),h({to:".",search:fe=>({...fe,...bh($)}),replace:!1})},[h]),[pt,ut]=l.useState(!1),Qe=s?.project.displayName||s?.project.name||f,Fe=im(),wt=$e({...Li({client:W,path:{name:f}}),enabled:k==="portfolio"&&!!f,staleTime:0,refetchOnMount:"always"}),Be=$e({...om({client:W,path:{name:f}}),enabled:!re()&&!!f&&(u||k==="portfolio"||k==="overview"||k==="settings"),staleTime:0,refetchOnMount:"always"}),Me=Be.data?.active??null,tt=Be.data!==void 0,Tt=new Set(Me&&Number(Me.plan.schemaVersion)===2?Me.plan.groups?.map($=>$.stableKey)??[]:[]),De={...B.scope==="group"&&!!B.groupKey&&tt&&!Tt.has(B.groupKey)?{scope:"all",queryClass:B.queryClass}:B,...H?{search:H}:{}},S=Me===null?null:Number(Me.plan.schemaVersion),Ae=Me?.revision??0,ve=tt?`${f}:${Ae}`:null,We=l.useRef(null);l.useEffect(()=>{const $=We.current;ve!==null&&(We.current=ve),yh($,ve)&&(ie({scope:"all",queryClass:"all"}),ut(!1))},[ve,ie]);const vt={client:W,path:{name:f},query:{scope:De.scope,...De.groupKey?{groupKey:De.groupKey}:{},queryClass:De.queryClass,...De.search?{search:De.search}:{},..._e?{sort:_e}:{},limit:50}},st=Zo({...lm(vt),enabled:!1,initialPageParam:vt,getNextPageParam:($,fe)=>{if(!$.properties.nextCursor)return;const Le=fe[0]?.measurement.displayedRunId;return{path:vt.path,query:{...vt.query,cursor:$.properties.nextCursor,...Le?{runId:Le}:{}}}},placeholderData:ni,staleTime:0,refetchOnMount:"always"}),Lt=st.data?.pages[0]?.measurement.displayedRunId,Xe=$e({...cm({client:W,path:{name:f},query:{revision:Ae,...Lt?{runId:Lt}:{}}}),enabled:k==="overview"&&!!f&&Me!==null&&S===1,staleTime:0,refetchOnMount:"always"}),te=Be.data!==void 0,qe=wt.data!==void 0,Ce=Be.isPending&&!te,Pe=Be.isError&&!te,Yt=wt.isPending&&!qe,Jt=wt.isError&&!qe,yt=Xe.data!==void 0,St=ly({activePlanSchemaVersion:N.data?.activeSchemaVersion??S,hasDraft:N.data?.draft!==null&&N.data?.draft!==void 0}),mt=St.surface==="simple-overview",Xt=N.data===void 0&&Be.data===void 0&&(Be.isLoading||N.isLoading);l.useEffect(()=>{k==="overview"&&mt&&!Xt&&d()},[Xt,mt,d,k]);const zt=k==="overview"&&mt&&!Xt,ss=fl(f,{evidence:zt}),at=ss.commandCenter?.visibilityEvidence??s.visibilityEvidence,fs=u&&!re()&&!Bt()&&k!=="overview",gt=$e({...Li({client:W,path:{name:f}}),enabled:fs,staleTime:ri,refetchOnWindowFocus:"always"}),dt=S===2&&_.measurementScope==="group"?_.measurementScopeKey:void 0,Ct=S===2&&_.measurementScope==="project",ns=l.useMemo(()=>{if(!(Me?.plan.schemaVersion!==2||!dt))return Me.plan.groups.find($=>$.stableKey===dt)},[Me,dt]),hs={client:W,path:{name:f},query:{window:ne,queryClass:S===2&&_.queryClass!=="unknown"?_.queryClass:"non-brand",...dt?{groupKey:dt}:{},...Ct?{scope:"all-markets"}:{}}},qt=k==="overview"&&!_.marketKey&&!!f&&(mt||tt)&&!Xt&&(mt||(_.measurementScope==="project"||S===2&&_.measurementScope==="group")&&_.queryClass!=="unknown"&&(S===2||_.queryClass!=="branded")),[Ps,Qt]=l.useState(null);l.useEffect(()=>{qt||Qt(null)},[qt]),l.useEffect(()=>{Qt(null)},[f]);const kt=Ps===f,xs=qt&&kt,ht=$e({...dm(hs),enabled:xs,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});um(f,JSON.stringify([r,s.competitors.map($=>$.domain).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,Ae,N.data?.draft?.etag??null]),xs);const Zt=ht.isError?ht.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,ys=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]),ps=l.useMemo(()=>{if(Me?.plan.schemaVersion!==2)return ys;const $=dt?ns?.competitors??[]:Me.plan.groups.flatMap(Le=>Le.competitors),fe=new Map;for(const Le of $){const es=Le.domain.trim().toLowerCase();!es||fe.has(es)||fe.set(es,{domain:Le.domain,label:Le.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const Le of ys){const es=Le.domain.trim().toLowerCase();!es||fe.has(es)||fe.set(es,Le)}return[...fe.values()]},[Me,dt,ys,ns]),G=S===2?ps:ys,oe=$t({...mm({client:W}),meta:{skipGlobalErrorToast:!0}}),Ne=N.data!==void 0?"success":N.isError?"error":"pending",me=l.useMemo(()=>{const $=st.data?.pages;return $?!sh($):!1},[st.data]),je=l.useMemo(()=>{const $=st.data?.pages,fe=$?.[0],Le=$?.at(-1);if(!(!fe||!Le||me))return{...fe,properties:{...fe.properties,items:$.flatMap(es=>es.properties.items),nextCursor:Le.properties.nextCursor}}},[me,st.data]),Ie=l.useMemo(()=>{if(Me)return Me.plan.schemaVersion===1?Xe.data?gy(Me,Xe.data):void 0:je?nh({overview:je,activePlan:Me,sort:_e,report:Xe.data,reportState:je.measurement.displayedRunId===void 0?"ready":Xe.isFetching&&Xe.data===void 0?"loading":Xe.isError&&Xe.data===void 0?"error":Xe.data?"ready":"loading"}):void 0},[Me,Xe.data,Xe.isError,Xe.isFetching,je]),as=S===2?me?"error":st.isPending?"loading":st.isError&&Ie===void 0?"error":"ready":Xe.isPending&&!yt?"loading":Xe.isError&&!yt?"error":"ready",ot=(s?.recentRuns??[]).some($=>$.kind===Ys["answer-visibility"]&&($.status===Ka.running||$.status===Ka.queued)),bs=s.queryCounts.total>0,M=l.useMemo(()=>(s?.project.locations??[]).map($=>$.label),[s?.project.locations]),pe=l.useMemo(()=>new Set(at.map($=>$.location??"")),[at]),it=pe.has(""),At=l.useMemo(()=>[...new Set(at.map($=>$.query))].sort(($,fe)=>$.localeCompare(fe)),[at]),Pt=At.length>0||s.queryCounts.total>0||(gt.data?.length??0)>0||Me!==null,vn=u&&!Pt&&(Be.data===void 0&&Be.isPending||gt.isLoading||zt&&ss.evidenceLoading),Ht=u&&(N.isError&&!N.isFetching||fs&>.isError&&!gt.isFetching),jn=u&&!Ht&&(vn||V===void 0||N.isFetching),Rt=!jn&&!Ht&&Pt&&V===!0,vs=u&&!jn&&!Rt,Nn=$e({...ml({client:W,path:{name:f}}),enabled:!re()&&!Bt()&&!!f,retry:!1}).data?.find($=>$.kind===Ys["answer-visibility"]),ca=Nn?.enabled&&Nn.nextRunAt?`Next AI sweep ${new Date(Nn.nextRunAt).toLocaleString()}`:null,Ja=l.useMemo(()=>{const $=[...pe].filter(Boolean);return $.length>1?$:M},[pe,M]);l.useEffect(()=>{if(!zt||we===void 0||we===""||!f){He(null),U(!1);return}U(!0),hm(f,we,20).then($=>{He($),U(!1)}).catch(()=>{He(null),U(!1)})},[we,f,zt]);const Os=l.useMemo(()=>{if(!ze)return null;const $=new Map;for(const fe of ze){for(const[Le,es]of Object.entries(fe.providerRuns??{}))$.set(`${fe.query}::${Le}`,es.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(Le=>({runId:Le.runId,citationState:Le.citationState,createdAt:Le.createdAt,answerMentioned:Le.answerMentioned,visibilityState:Le.visibilityState,visibilityTransition:Le.visibilityTransition,mentionState:Le.mentionState,mentionTransition:Le.mentionTransition})))}return $},[ze]),Dn=l.useMemo(()=>{const $=we!==void 0?at.filter(fe=>we===""?!fe.location:fe.location===we):at;return Os?$.map(fe=>{const Le=Os.get(`${fe.query}::${fe.provider}`)??Os.get(`${fe.query}::`);return Le?{...fe,runHistory:Le}:fe}):$},[at,we,Os]);async function da(){if(!(b!==f||!u||re()||Bt()||Fe.isPending||ot||!Rt))try{await Fe.mutateAsync({projectName:f,projectLabel:Qe,sourceAction:"project-run"}),p(null),n()}catch{}}function nn(){h({to:"/setup",search:{experience:"legacy",setupProject:f}})}async function On(){X(!0);try{await wm(f),Te({title:"Project deleted",detail:`${Qe} was removed.`,tone:"positive",dedupeKey:`project:delete:${f}`,dedupeMode:"drop"}),h({to:"/"}),n()}catch($){console.error("Failed to delete project:",$)}finally{X(!1)}}async function wn(){const $=ge.split(`
|
|
7
|
-
`).map(fe=>fe.trim()).filter(Boolean);if($.length!==0){xe(!0);try{await gm(f,$),n(),J("")}finally{xe(!1)}}}async function ua($){z($);try{await pm(f,[$]),n()}catch(fe){Te({title:"Could not remove query",detail:fe instanceof Error?fe.message:`Failed to remove "${$}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{z(null)}}async function Fn($){const fe=$.trim();if(!fe)return!1;try{return await fm(f,[fe]),n(),!0}catch(Le){return Te({title:"Could not add competitor",detail:Le instanceof Error?Le.message:`Failed to add ${fe}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function Xa($){const fe=s.competitors.find(Le=>Le.domain===$);if(!fe)return Te({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 ym(f,fe.id),n(),!0}catch(Le){return Te({title:"Could not remove competitor",detail:Le instanceof Error?Le.message:`Failed to remove ${fe.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function Sn($){const fe=$.trim();if(!fe||!dt||S!==2||!u||re()||oe.isPending)return!1;try{const Le=await oe.mutateAsync({client:W,path:{name:f},headers:{"Idempotency-Key":zy()},body:{expectedActiveRevision:Ae,groupKey:dt,domain:fe}});return Promise.allSettled([N.refetch()]),Te({title:Le.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:${dt}:${fe}`,dedupeMode:"replace"}),!0}catch(Le){return Te({title:"Could not add market competitor",detail:Le instanceof Error?Le.message:`Failed to add ${fe} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function ma($,fe){const Le=await bm($,fe);return await m.invalidateQueries({queryKey:vm({client:W})}),m.setQueryData(jm({client:W,path:{name:$}}),Le),Qy(m,Le),fe.providers!==void 0&&await m.invalidateQueries({queryKey:Nm({client:W,path:{name:$}}),exact:!0}),Le}const jt=`/projects/${encodeURIComponent(s.project.name)}`,Za=[{key:"overview",label:"AI Visibility",href:jt},{key:"search-console",label:"Search Engines",href:`${jt}/search-console`},{key:"activity",label:"Activity",href:`${jt}/activity`},{key:"technical-aeo",label:"Site Health",href:`${jt}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${jt}/conversions`},{key:"local",label:"Local Presence",href:`${jt}/local`},{key:"queries",label:"Queries",href:`${jt}/queries`},{key:"backlinks",label:"Backlinks",href:`${jt}/backlinks`}],ha=[{key:"report",label:"Report",href:`${jt}/report`},{key:"history",label:"Change History",href:`${jt}/history`}],xa=Za.filter($=>rr($.key,K)),pa=ha.filter($=>rr($.key,K)),ga=rr("settings",K)?{key:"settings",label:"Settings",href:`${jt}/settings`}:null;function Kn($){return mt?$:e.jsx(Np,{projectName:f,selection:_,showUnmeasuredFallback:!Me&&!bs&&_.measurementScope==="project"&&_.queryClass==="all"&&!_.provider&&!_.model&&!_.location&&!_.from&&!_.to&&!_.revision&&!_.measurementRunId&&!_.queryKey&&!_.marketKey,onSelectionChange:I,onManageQueries:re()?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({..._,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]}),!re()&&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:Bt()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:[k==="overview"&&(mt||_.from||_.to)?e.jsx("p",{className:"text-sm text-muted",children:mt?s.dateRangeLabel:`${_.from?.slice(0,10)??"First measurement"} to ${_.to?.slice(0,10)??"Latest measurement"}`}):null,!re()&&(Bt()?e.jsx(xm,{projectName:f,running:ot,portfolio:!mt}):e.jsxs("div",{className:"flex items-center gap-3",children:[ca?e.jsx("p",{className:"text-sm text-secondary",children:ca}):null,e.jsx(Je,{type:"button",variant:"outline",disabled:Fe.isPending||ot||jn,onClick:Ht?()=>{Promise.all([N.refetch(),...fs?[gt.refetch()]:[]])}:vs?nn:$=>{x.current=$.currentTarget,p(f)},children:Fe.isPending?"Starting…":ot?"AI sweep running…":jn?"Checking AI readiness…":Ht?"Retry AI readiness":vs?"Set up AI Visibility":"Run AI sweep"})]}))]})]}),!re()&&!Bt()&&e.jsx(Vy,{open:b===f,projectLabel:Qe,onOpenChange:$=>p($?f:null),onConfirm:Ye(da),onClosed:()=>x.current?.focus(),disabled:Fe.isPending||ot||!Rt}),e.jsx(Xy,{items:xa,overflowItems:pa,settingsItem:ga,activeTab:k}),k==="portfolio"&&!re()?e.jsx(Uf,{projectName:f,canEdit:u,queries:wt.data??[],isQueryLoading:Yt,isQueryError:Jt,onRetryQueries:()=>{wt.refetch()},publishedPlan:Me,onCreateQueries:async $=>(await ce.mutateAsync({projectName:f,queries:[...$]}),(await wt.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{h({to:"/projects/$projectName",params:{projectName:f},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([N.refetch(),Be.refetch()]).finally(()=>{h({to:"/projects/$projectName",params:{projectName:f}})})}},f):k==="overview"?Xt||mt&&!w&&(!c||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"})]}):mt&&i?e.jsxs("div",{role:"alert",className:"page-section-divider",children:[e.jsx("p",{children:"Could not load AI visibility."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[Pe?e.jsxs("div",{role:"alert",className:"mb-5 flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("span",{children:"Could not check the advanced measurement setup. Existing project-wide results remain available."}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{Be.refetch()},children:"Retry setup check"})]}):null,Kn(e.jsx(cy,{mode:St,canEdit:u&&!re()&&!Ce&&!Pe,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(qp,{projectName:s.project.name,competitorDomains:q,analyticsRevision:a})}),e.jsx(Yy,{model:s,sweepRunning:ot,hasVisibilityBaseline:bs}),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."})]})}),bs?e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsx(Ah,{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(Ha,{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(Ha,{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(Or,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[!re()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(Je,{type:"button",variant:"outline",size:"sm",onClick:()=>Z(!ee),children:ee?"Done":"Manage queries"})}),!re()&&ee&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[At.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:At.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:se!==null,onClick:()=>{ua($)},children:se===$?"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:ge,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:[ge.split(`
|
|
8
|
-
`).filter($=>$.trim()).length," to add"]}),e.jsx(Je,{type:"button",size:"sm",disabled:!ge.trim()||de,onClick:Ye(wn),children:de?"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 ${we===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":we===void 0,onClick:()=>{Se(void 0)},children:"All locations"}),s.project.locations.map($=>e.jsx("button",{className:`filter-chip ${we===$.label?"filter-chip-active":""}`,type:"button","aria-pressed":we===$.label,onClick:()=>{Se($.label),Ke(!1)},children:$.label},$.label)),it&&e.jsx("button",{className:`filter-chip ${we===""?"filter-chip-active":""}`,type:"button","aria-pressed":we==="",onClick:()=>{Se(""),Ke(!1)},children:"No location"}),Ja.length>1&&we===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${et?"filter-chip-active":""}`,type:"button","aria-pressed":et,onClick:()=>Ke($=>!$),title:"Side-by-side location comparison",children:"Compare"})]}),ss.evidenceLoading?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading query evidence…"}):ss.evidenceError?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load query evidence."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{ss.refetch()},children:"Retry"})]}):e.jsx(Kh,{evidence:Dn,compareLocations:et})]}),e.jsxs(Or,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:re(),children:[e.jsx(Bx,{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(Ln,{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"}`))})]})})]})]}),!re()&&e.jsx(Or,{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(Vm,{run:$},$.id))})})]}),report:Ie,reportState:as,onOpenSetup:re()?void 0:()=>{h({to:"/projects/$projectName/portfolio",params:{projectName:f}})},onRetryReport:()=>{S===2?Promise.all([st.refetch(),Xe.refetch()]):Xe.refetch()},onViewChange:$=>{ie({scope:$.scope,...$.groupKey?{groupKey:$.groupKey}:{},queryClass:$.queryClass,...$.search?.trim()?{search:$.search.trim()}:{}})},onLoadMore:$=>{$===je?.properties.nextCursor&&st.fetchNextPage()},onPropertyExpand:()=>{pt&&Xe.isError&&Xe.refetch(),ut(!0)},onRetryEvidence:()=>{Xe.refetch()},renderPropertyLink:S===2&&!re()?({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:st.isPlaceholderData,isLoadingMore:st.isFetchingNextPage,isLoadMoreError:st.isFetchNextPageError,viewSearch:De.search??""},`${f}:${Ae}`)),!mt&&_.measurementScope==="project"?e.jsxs("details",{className:"page-section-divider",onToggle:$=>{$.currentTarget.open&&d()},children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm font-medium text-heading",children:"Project signals"}),!c||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(P,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsx(Jy,{insights:s.insights,suggestedQueries:s.suggestedQueries,onManageQueries:re()?void 0:()=>{h({to:"/projects/$projectName/queries",params:{projectName:f},search:$=>({...$,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]},f):null,qt?e.jsxs("details",{className:"page-section-divider",open:kt,onToggle:$=>Qt($.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(Mh,{window:ne,landscape:ht.data,pinnedFallback:G,canWrite:u,isEmbed:re(),onWindowChange:Ee,onPin:dt&&u&&!re()?Sn:!Ct&&u&&!re()?Fn:void 0,onUnpin:dt||Ct||!u||re()?void 0:Xa,onAddCompetitor:dt&&u&&!re()?Sn:!Ct&&u&&!re()?Fn:void 0,error:Zt,onRetry:xs?()=>{ht.refetch()}:void 0,isLoading:xs&&ht.isPending&&ht.data===void 0,scopeLabel:dt?`${ns?.label??dt} group`:Ct?"All markets":"Project-wide"})]}):null]}):k==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(Oy,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async($,fe)=>{await ma($,fe)},onRefresh:()=>{n()}}),e.jsx(Ky,{project:s.project,onSave:async $=>{await ma(s.project.name,$)}}),u&&!re()?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."}),Ne==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):Ne==="error"?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:"Could not load advanced measurement setup."}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{N.refetch()},children:"Retry"})]}):e.jsx(P,{type:"button",variant:"outline",onClick:()=>{h({to:"/projects/$projectName/portfolio",params:{projectName:f}})},children:uc(St.setupAction)})]}):null,e.jsx(_y,{projectName:s.project.name}),e.jsx(By,{projectName:s.project.name}),u&&!re()?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."}),R?e.jsxs(ye,{className:"surface-card p-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(P,{type:"button",variant:"destructive",disabled:O,onClick:Ye(On),children:O?"Deleting...":"Yes, delete project"}),e.jsx(P,{type:"button",variant:"outline",disabled:O,onClick:()=>ae(!1),children:"Cancel"})]})]}):e.jsxs(Je,{type:"button",variant:"outline",onClick:()=>ae(!0),children:[e.jsx(jl,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):k==="report"?e.jsx(jy,{projectName:s.project.name}):k==="queries"||k==="discovery"?e.jsx(zp,{projectName:f,queryWorkspace:Y.queryWorkspace==="research"||k==="discovery"&&Y.queryWorkspace===void 0?"research":"tracked",onQueryWorkspaceChange:$=>I({queryWorkspace:$,trackingQueryId:void 0}),researchMode:Y.researchMode==="test"?"test":"find",onResearchModeChange:$=>I({researchMode:$}),selection:_,onSelectionChange:I,trackingQueryId:typeof Y.trackingQueryId=="string"?Y.trackingQueryId:void 0,onTrackingQueryIdChange:$=>I({trackingQueryId:$})}):k==="technical-aeo"?e.jsx(zm,{projectName:s.project.name,projectId:s.project.id,initialRunId:Y.siteHealthRunId,onReleaseInitialRun:T}):k==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(af,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(Bg,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):k==="history"?e.jsx(vg,{projectName:s.project.name}):k==="activity"?e.jsx(sx,{projectName:s.project.name}):k==="backlinks"?e.jsx(Ux,{projectName:s.project.name}):k==="local"?e.jsx(bx,{projectName:s.project.name,projectId:s.project.id}):k==="search-console"?e.jsx(Wy,{projectName:s.project.name}):null]})}export{xb as ProjectPage,Xy as ProjectSubnav,Vy as ProjectSweepConfirmation,Qy as patchProjectDashboardCache};
|