@ainyc/canonry 5.4.0 → 5.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/agent-workspace/skills/aero/references/portfolio-analysis.md +1 -1
- package/assets/agent-workspace/skills/canonry/references/aeo-analysis.md +10 -0
- package/assets/assets/{AuditHistoryPanel-DNSskBJN.js → AuditHistoryPanel-DVUbjx1M.js} +1 -1
- package/assets/assets/{BacklinksPage-COtLVzT8.js → BacklinksPage-D01VTDAp.js} +1 -1
- package/assets/assets/ChartPrimitives-BQC2VH0O.js +1 -0
- package/assets/assets/{HistoryPage-D9e6cGrq.js → HistoryPage-Bk1gsXe5.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-BSs4ba4N.js → MeasurementPropertyPage-D7p5vpY_.js} +1 -1
- package/assets/assets/ProjectPage-Dv3USEIE.js +8 -0
- package/assets/assets/{RunRow-DRjXGgeI.js → RunRow-Dpa0kAip.js} +1 -1
- package/assets/assets/{RunsPage-BXyqLNMQ.js → RunsPage-B59z7DQ_.js} +1 -1
- package/assets/assets/{SettingsPage-DKmzGwx3.js → SettingsPage-HJDgmQi9.js} +1 -1
- package/assets/assets/{SiteHealthSection-DuSY6jzY.js → SiteHealthSection-BnJA-zvQ.js} +3 -3
- package/assets/assets/TrafficPage-C8na59q_.js +40 -0
- package/assets/assets/{TrafficSourceDetailPage-Bw8PCVl9.js → TrafficSourceDetailPage-B2fO8bDc.js} +1 -1
- package/assets/assets/{extract-error-message-rTGTNN_D.js → extract-error-message-670MySRM.js} +1 -1
- package/assets/assets/index-DTrkuKOh.js +86 -0
- package/assets/assets/index-PT4UiPTM.css +1 -0
- package/assets/assets/{react-sigma_core.esm.min-Xwhtf0bv.js → react-sigma_core.esm.min-DOhuYLQj.js} +1 -1
- package/assets/assets/v2-overview-adapter-CQyDNkXa.js +1 -0
- package/assets/assets/vendor-lucide-CneDbhOr.js +1 -0
- package/assets/assets/{vendor-recharts-D-cUuLZo.js → vendor-recharts-llkUFBGR.js} +1 -1
- package/assets/index.html +4 -4
- package/dist/{chunk-SLOTTXIL.js → chunk-C4KBR4H6.js} +6 -6
- package/dist/{chunk-Z6RA7LWY.js → chunk-D3DKDTXP.js} +1027 -70
- package/dist/{chunk-L3FG66O7.js → chunk-GHAUT7XJ.js} +2 -2
- package/dist/{chunk-67OM5KEH.js → chunk-I4AHG7K3.js} +3 -3
- package/dist/{chunk-P5YYRGFS.js → chunk-KZYOJ4F5.js} +2 -2
- package/dist/{chunk-2P52FD5B.js → chunk-TM2NQMJA.js} +803 -777
- package/dist/cli.js +10 -9
- package/dist/{demo-server-6QU77ZMV.js → demo-server-JEGVGOPQ.js} +7 -3
- package/dist/index.js +5 -5
- package/dist/{intelligence-service-PHCK6A35.js → intelligence-service-5P62KKG6.js} +2 -2
- package/dist/mcp.js +3 -3
- package/package.json +13 -13
- package/assets/assets/ChartPrimitives-Bxa_vFmq.js +0 -1
- package/assets/assets/ProjectPage-BbpGgwgd.js +0 -8
- package/assets/assets/TrafficPage-Bc9NGm4L.js +0 -1
- package/assets/assets/index-CVK43vax.js +0 -86
- package/assets/assets/index-Hmnj0RO5.css +0 -1
- package/assets/assets/v2-overview-adapter-BgGH6oLq.js +0 -1
- package/assets/assets/vendor-lucide-CBIL4Nkq.js +0 -1
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{j as e,r as l,u as Ie,L as Ss,h as us,o as At,B as si,C as Ho,D as lc,k as cc,l as dc}from"./vendor-tanstack-ZXXkndVj.js";import{A as Wo,a as uc,V as Yo,p as mc,b as hc,c as xc,m as pc,s as gc,d as fc,e as yc,f as bc}from"./v2-overview-adapter-BgGH6oLq.js";import{T as ce,t as vc,a as jc,M as Jo,I as Ue,s as Xo,B as I,b as Nc,u as Zo,C as wc,P as Tn,h as Sc,c as Cc,d as xn,g as el,e as tl,f as pe,i as Q,j as ie,k as Is,l as wt,m as He,n as kc,o as Ac,p as Pc,q as sl,r as Rc,v as Ic,w as vn,S as pn,x as Tc,y as $c,z as Ks,A as Ht,D as Mc,E as ji,F as nl,G as Dt,H as ni,J as Lc,K as qc,L as Ec,N as Dc,O as Ni,Q as Te,R as Oc,U as Fc,V as er,W as Gc,X as Kc,Y as _c,Z as Uc,_ as Bc,$ as Vc,a0 as zc,a1 as Qc,a2 as Hc,a3 as Wc,a4 as Yc,a5 as Jc,a6 as Xc,a7 as Zc,a8 as ed,a9 as al,aa as Ws,ab as td,ac as rl,ad as Ea,ae as sd,af as ze,ag as nd,ah as ad,ai as rd,aj as Da,ak as id,al as od,am as ld,an as fn,ao as cd,ap as dd,aq as ud,ar as il,as as Or,at as md,au as ai,av as hd,aw as Zn,ax as Ys,ay as Ot,az as xd,aA as pd,aB as gd,aC as tr,aD as Rt,aE as fd,aF as yd,aG as bd,aH as vd,aI as jd,aJ as Jn,aK as wi,aL as ga,aM as sr,aN as Nd,aO as wd,aP as Si,aQ as nr,aR as gn,aS as Sd,aT as ol,aU as ll,aV as Cd,aW as kd,aX as Ci,aY as Ad,aZ as Pd,a_ as Rd,a$ as Id,b0 as Td,b1 as $d,b2 as Md,b3 as Ld,b4 as qd,b5 as Ed,b6 as Dd,b7 as Od,b8 as Fd,b9 as Gd,ba as Kd,bb as _d,bc as Ud,bd as Bd,be as Vd,bf as zd,bg as Qd,bh as Hd,bi as Wd,bj as Yd,bk as Jd,bl as Xd,bm as Zd,bn as eu,bo as bs,bp as tu,bq as xt,br as su,bs as nu,bt as au,bu as ru,bv as iu,bw as ou,bx as lu,by as cu,bz as du,bA as uu,bB as mu,bC as hu,bD as xu,bE as pu,bF as gu,bG as fu,bH as yu,bI as bu,bJ as vu,bK as ju,bL as Nu,bM as wu,bN as Su,bO as ki,bP as Ai,bQ as Pi,bR as Cu,bS as ku,bT as Au,bU as Pu,bV as Ru,bW as Iu,bX as Tu,bY as $u,bZ as Mu,b_ as Lu,b$ as qu,c0 as Eu,c1 as Du,c2 as Ou,c3 as Fu,c4 as Gu,c5 as Ku,c6 as _u,c7 as Uu,c8 as Bu,c9 as cl,ca as ar,cb as Vu,cc as Ri,cd as zu,ce as Qu,cf as Hu,cg as Wu,ch as Yu,ci as Ju,cj as Xu,ck as dl,cl as Zu,cm as ul,cn as ml,co as hl,cp as xl,cq as em,cr as tm,cs as sm,ct as nm,cu as am,cv as rm,cw as Ii,cx as im,cy as om,cz as lm,cA as cm,cB as dm,cC as Ti,cD as um,cE as mm,cF as hm,cG as xm,cH as pm,cI as gm,cJ as Oa,cK as fm,cL as ym,cM as rr,cN as bm,cO as vm,cP as jm,cQ as Nm,cR as wm,cS as Sm,cT as Cm,cU as km,cV as Am,cW as Pm,cX as pl,cY as Rm,cZ as Im,c_ as Tm,c$ as $m,d0 as Mm,d1 as Lm,d2 as fa,d3 as qm,d4 as Em,d5 as Dm,d6 as $i,d7 as Om}from"./index-CVK43vax.js";import{C as $n,f as gl,x as ea,U as Fm,y as Gm,L as Km,z as _m,k as Um,P as Fa,D as fl,I as Bm,J as yl,e as Vm,E as zm,q as Qm,K as Hm,N as bl}from"./vendor-lucide-CBIL4Nkq.js";import{R as Wm}from"./RunRow-DRjXGgeI.js";import{u as yn,D as zs,a as Ts,b as vl,M as Ma,c as Cs,S as Ym}from"./SiteHealthSection-DuSY6jzY.js";import{C as ta,f as bn,a as cs,b as $t,c as Ft,d as es,e as at,g as ds,h as $s,M as jl,i as Nl,o as Ms,j as Qs,p as Jm}from"./ChartPrimitives-Bxa_vFmq.js";import{u as Xm,a as Zm,b as eh,t as th,e as sh,c as bt}from"./extract-error-message-rTGTNN_D.js";import{R as Js,C as Xs,a as sa,X as Zs,Y as en,T as tn,b as Fr,L as Ga,A as Us,d as Rs,e as nh}from"./vendor-recharts-D-cUuLZo.js";import{A as ah}from"./AuditHistoryPanel-DNSskBJN.js";import"./vendor-markdown-B-Oq2NYq.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-yaml-GWJz5H2G.js";function Hs(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 rh(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=ih(r,1));return a}function ih(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 oh(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 lh(t,s){const n=oh(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} (${Hs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Hs(t.prior)} ${s})`:`Flat ${n} (${Hs(t.prior)} ${s})`}const wl=30;function Mi(t){return Math.round(t*10)/10}function ch(t){return t.prior>=wl&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Mi(t.deltaAbs)} vs ${Mi(t.prior)}`}function dh(t,s,n){return t.prior>=wl&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Hs(Math.round(t.deltaAbs))} ${s} ${n}`}function uh(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 mh=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Sl(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Cl(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 kl(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Sl).map(Cl).filter(Boolean)):new Set}function Al(t,s){const n=Sl(t).map(Cl).filter(Boolean).filter(a=>!mh.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function hh(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function xh(t,s){const n=kl(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=Al(hh(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function ph(t){const s=kl(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=Al(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const gh=1e6;function fh(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/gh)}function Gr({state:t,label:s}){return e.jsx(ce,{tone:jc(t),children:s??vc(t)})}const on=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Li={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},yh={"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."},bh="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function vh(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 jh({breakdown:t,projectLabel:s,competitorDomains:n}){const a=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(a===0)return null;const r=new Map(t.perCompetitor.map(i=>[i.domain,i.mentionSnapshots])),o=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...n.map(i=>({label:i,mentions:r.get(i)??0,isYou:!1}))].sort((i,d)=>d.mentions-i.mentions||(i.label<d.label?-1:1));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Ue,{text:bh})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:o.map(i=>{const d=i.mentions/a*100;return e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${i.isYou?"text-heading font-medium":"text-secondary"}`,children:i.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${i.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${d>0?Math.max(d,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:i.mentions}),e.jsxs("td",{className:"mention-share-share",children:[d.toFixed(1),"%"]})]},i.label)})})]})}function Nh({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=l.useState("non-brand"),o=l.useId(),i=t.scope==="pooled",d=!i&&t.branded.snapshotsTotal>0,c=d?a:"non-brand",h=i?"pooled":c,u=c==="branded"?t.branded:t.breakdown,m=c==="branded"?t.breakdown:t.branded,b=vh(u,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:m.snapshotsTotal>0}),g=h==="non-brand"?Jo[t.tone]:"text-secondary";function f(x){const y=on.findIndex(S=>S.value===c);let P=null;x.key==="ArrowRight"||x.key==="ArrowDown"?P=(y+1)%on.length:x.key==="ArrowLeft"||x.key==="ArrowUp"?P=(y-1+on.length)%on.length:x.key==="Home"?P=0:x.key==="End"&&(P=on.length-1),P!==null&&(x.preventDefault(),r(on[P].value),x.currentTarget.querySelectorAll('[role="radio"]')[P]?.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(Ue,{text:yh[h]})]}),d?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:f,children:on.map(x=>{const y=x.value===c;return e.jsx("button",{type:"button",role:"radio","aria-checked":y,tabIndex:y?0:-1,onClick:()=>r(x.value),className:`segmented-option min-h-11 ${y?"segmented-option-active":""}`,children:x.label},x.value)})}):e.jsx("span",{className:"mention-share-class",children:Li[h]})]}),b.numeric?e.jsxs("p",{className:`mention-share-value ${g}`,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:Li[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(jh,{breakdown:u,projectLabel:s,competitorDomains:n})]})}const ln=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],qi=5;function wh(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 Sh(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 Pl(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 Ch({value:t,onChange:s}){function n(a){const r=ln.findIndex(d=>d.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%ln.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+ln.length)%ln.length:a.key==="Home"?o=0:a.key==="End"&&(o=ln.length-1),o===null)return;a.preventDefault();const i=ln[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:ln.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 Kr({row:t,isProject:s=!1,metricState:n="measured",shareContext:a,canManage:r,onPin:o,onUnpin:i}){const d=!s&&r&&!t.pinned&&!!o,c=!s&&r&&t.pinned&&!!i,h=n==="measured",u=h&&t.sampleUrls.length>0,[m,b]=l.useState(!1),[g,f]=l.useState(null);async function x(y,P){if(!(!P||m)){b(!0),f(null);try{await P(t.domain)===!1&&f(`Could not ${y} competitor. Try again.`)}catch{f(`Could not ${y} 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":Pl(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:h?Nc(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:d||c||u?e.jsxs("div",{className:"flex min-w-max items-start justify-end gap-2",children:[u?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(y=>e.jsx("li",{className:"break-all",children:y},y))})]}):null,c&&i?e.jsxs(I,{type:"button",size:"sm",variant:"outline",disabled:m,onClick:()=>{x("unpin",i)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,d&&o?e.jsxs(I,{type:"button",size:"sm",variant:"outline",disabled:m,onClick:()=>{x("pin",o)},children:["Pin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,g?e.jsx("span",{role:"alert",className:"sr-only",children:g}):null]}):e.jsx("span",{className:"text-faint",children:"—"})})]})}function _r({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function kh({rows:t,shareContext:s,canManage:n,onPin:a}){const[r,o]=l.useState(!1),i=r?t:t.slice(0,qi);return e.jsxs("tbody",{children:[e.jsx(_r,{children:"Observed in this window"}),i.map(d=>e.jsx(Kr,{row:{...d,pinned:!1},shareContext:s,canManage:n,onPin:a},d.domain)),t.length>qi?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(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11 text-sm","aria-expanded":r,"aria-label":r?"Show fewer observed competitors":`Show all ${t.length} observed competitors`,onClick:()=>o(d=>!d),children:r?"Show fewer":`Show all ${t.length}`})]})})}):null]})}function Ah({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,d]=l.useState(null);async function c(){const h=n.trim();if(!(!h||r)){o(!0),d(null);try{if(await t(h)===!1){d("Could not add competitor. Try again.");return}a("")}catch{d("Could not add competitor. Try again.")}finally{o(!1)}}}return e.jsxs("details",{className:"inline-disclosure competitor-landscape-manage",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:h=>{h.preventDefault(),c()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:h=>a(h.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(I,{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 Ph({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:d,onAddCompetitor:c,error:h,onRetry:u,isLoading:m=!1,scopeLabel:b}){const g=a&&!r,f=s?.pinned??n,x=s?.observed??[],y=s?.otherSources??[],P=s?.evidence,S=Sh(s),q=s?.marketState?.draft?.pendingCompetitorDomains.length??0;return e.jsxs("section",{"aria-labelledby":"competitor-landscape-title","aria-busy":m,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:wh(s.filters?.queryClass)}):null,s?.reason?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Xo(s.reason)}):null]}),e.jsx(Ch,{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}),u?e.jsx(I,{type:"button",size:"sm",variant:"outline",onClick:u,children:"Retry competitor history"}):null]}):null,m&&!s&&f.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(_r,{children:"You"}),e.jsx(Kr,{row:s.project,shareContext:s,isProject:!0,metricState:S,canManage:!1})]}):null,e.jsx(_r,{children:"Pinned"}),f.length>0?f.map(T=>e.jsx(Kr,{row:{...T,pinned:!0},shareContext:s,metricState:S,canManage:g,onUnpin:d},T.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s&&x.length>0?e.jsx(kh,{shareContext:s,rows:x,canManage:g,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),P?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:[P.answeredResults," ",P.answeredResults===1?"answer":"answers"]}),P.missingAnswerTextResults>0?e.jsx("span",{className:"text-caution",children:"Answer data incomplete"}):null,P.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($n,{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:[x.length===0?e.jsx("p",{children:"No additional competitors were identified in this period."}):null,e.jsxs("p",{children:[P.sourceResults," ",P.sourceResults===1?"result includes":"results include"," source URLs."]}),P.missingAnswerTextResults>0?e.jsxs("p",{children:[P.missingAnswerTextResults," ",P.missingAnswerTextResults===1?"result has":"results have"," no answer text and ",P.missingAnswerTextResults===1?"is":"are"," excluded from mention share."]}):null,P.incompleteSourceResults>0?e.jsxs("p",{children:[P.incompleteSourceResults," ",P.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,P.excludedProbeResults+P.excludedNonCompletedResults>0?e.jsxs("p",{children:[P.excludedProbeResults+P.excludedNonCompletedResults," test or unfinished ",P.excludedProbeResults+P.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,q>0?e.jsx("p",{className:"text-sm text-secondary",children:s?.scope.kind==="all-markets"?`${q} competitor${q===1?" is":"s are"} pending publication across markets.`:`${q} competitor${q===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(T=>e.jsxs("li",{children:[T.name," · ",T.answerCount," answers"]},T.name))})]}):null,y.length>0?e.jsxs("details",{className:"inline-disclosure",children:[e.jsxs("summary",{children:["Other observed sources (",y.length,")"]}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:y.map(T=>e.jsxs("li",{children:[e.jsxs("span",{children:[T.label," · ",Pl(T.surfaceClass)," · ",T.citationCount," citations"]}),T.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:T.sampleUrls.map(v=>e.jsx("li",{className:"break-all",children:v},v))}):null]},T.domain))})]}):null]}),g&&c?e.jsx(Ah,{onAddCompetitor:c}):null]})}function Ei({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},r={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},o=n.length-1,i=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),d=new Date(n[o].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=n.map((h,u)=>{const m=new Date(h.createdAt).toLocaleDateString();return`${u===o?"Latest run, ":""}${m}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${c}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,u)=>{const m=!!(h.model&&u>0&&n[u-1]?.model&&n[u-1].model!==h.model),b=u===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${m?"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,m?"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:[d," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function Ur(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 Rh=320;function Ih(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function Th(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function Di(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 Oi(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 Fi(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const r=t[t.length-1].citationState,o=t[t.length-2].citationState;if(o!=="cited"&&r==="cited")return`Newly ${n}`;if(o==="cited"&&r!=="cited")return"Lost since last run";let i=0;for(let d=t.length-1;d>=0&&t[d].citationState===r;d--)i++;return r==="cited"?i<=1?`${a} in latest run`:`${a} for ${i} runs`:i<=1?`Not ${n} in latest run`:`Not ${n} across ${i} runs`}function $h(t,s){return t.map(n=>Rl(n,s))}function Rl(t,s){return s==="citations"?t:{...t,citationState:Di(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Di(n,s)}))}}function Gi(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,o=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",d=o==="cited"||o==="emerging";return r==="lost"||o!==null&&d&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||o!==null&&!d&&i?{key:s,label:`New ${n}`,tone:"positive"}:o===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Mh(t){const s=Ur($h(t,"mentions")),n=Ur(t);return[Gi(s,"mentions"),Gi(n,"citations")]}function Lh({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 Ki({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Mh(t).map(s=>e.jsx(Lh,{signal:s},s.key))})}function qh({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Zo(),[r,o]=l.useState(new Set),[i,d]=l.useState("mentions"),[c,h]=l.useState(n),[u,m]=l.useState("all"),b=l.useMemo(()=>{const v=new Map;for(const j of t){const N=j.query,k=j.queryClass??null,E=s?j.location??null:null,O=JSON.stringify([N,k,E]),Z=v.get(O)??{key:O,phrase:N,queryClass:k,location:E,items:[],rawItems:[]};Z.items.push(Rl(j,i)),Z.rawItems.push(j),v.set(O,Z)}return[...v.values()]},[t,i,s]),g=l.useMemo(()=>b.filter(v=>u==="all"||(u==="unclassified"?v.queryClass===null:v.queryClass===u)),[b,u]),f=yn({rows:g,getSearchText:Th}),x=f.rows.map(v=>v.key),y=x.length>0&&x.every(v=>r.has(v)),P=v=>{o(j=>{const N=new Set(j);return N.has(v)?N.delete(v):N.add(v),N})},S=i==="mentions"?"mentioned":"cited",q=i==="mentions"?"Mention History":"Citation History",T=i==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":i==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>d("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":i==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>d("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:i==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{o(v=>{const j=new Set(v);for(const N of x)y?j.delete(N):j.add(N);return j})},children:y?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),b.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(zs,{value:f.query,onChange:f.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:u,onChange:v=>{m(v.target.value),f.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:q}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:f.rows.map(({key:v,phrase:j,queryClass:N,location:k,items:E,rawItems:O})=>{const Z=r.has(v),U=E.map(Y=>Y.citationState),F=U.includes("cited")?"cited":U.includes("emerging")?"emerging":U.includes("lost")?"lost":U.every(Y=>Y==="pending")?"pending":"not-cited",z=Ur(E),V=E.filter(Y=>Y.citationState===wc.cited||Y.citationState==="emerging").length,te=Fi(z,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:()=>P(v),onKeyDown:Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),P(v))},tabIndex:0,role:"button","aria-expanded":Z,children:[e.jsx("td",{children:e.jsx(gl,{size:14,className:`transition-transform duration-150 text-muted ${Z?"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:k??"No location"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.jsx(ce,{tone:"neutral",className:"whitespace-nowrap",children:Ih(N)}),E.map(Y=>e.jsx(Tn,{provider:Y.provider},Y.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gr,{state:F,label:Oi(F,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${V} of ${E.length} engines ${T}`,children:[V,"/",E.length]})]})}),e.jsx("td",{children:e.jsx(Ei,{history:z})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:te}),e.jsx(Ki,{items:O})]}),e.jsx("td",{})]}),Z&&E.map((Y,A)=>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(Tn,{provider:Y.provider})}),e.jsx("td",{children:e.jsx(Gr,{state:Y.citationState,label:Oi(Y.citationState,i)})}),e.jsx("td",{children:e.jsx(Ei,{history:Y.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:Fi(Y.runHistory,i)}),e.jsx(Ki,{items:[O[A]??Y]})]}),e.jsx("td",{children:e.jsx(I,{variant:"ghost",size:"sm",type:"button",onClick:ee=>{ee.stopPropagation(),a(Y.id)},children:"View"})})]}),c==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Oh,{item:Y,onViewFull:()=>a(Y.id)})})]})]},Y.id))]},v)})})]})}),f.totalRows===0&&(f.hasQuery||u!=="all")?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ts,{page:f.page,pageSize:f.pageSize,visibleRows:f.rows.length,totalRows:f.totalRows,onPageChange:f.setPage,itemLabel:f.hasQuery||u!=="all"?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",S==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Eh(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=Cc(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 _i(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function Dh(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 Oh({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}=Dh(t.answerSnippet,Rh),o=Eh(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:Sc(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] ${_i(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,_i(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 ya({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 za({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=at[0],cr=at[1],Ui=at[2],Bi=at[3],Fh=["both","server","ga4"],Vi={fontSize:11,paddingTop:6},zi=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Qi=t=>typeof t=="number"?Hs(Math.round(t)):String(t),as=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(Ue,{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 Gh(t,s){return n=>{const{cx:a,cy:r,index:o,key:i}=n,d=o??-1;return!(t[d]!=null&&t[d-1]==null&&t[d+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function Kh({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,d]=l.useState("both"),c=Xm(t,{sinceMinutes:s,granularity:"day",limit:1}),h=Zm(t),m=Ie({...el({client:Q,path:{name:t}}),enabled:!!t,staleTime:xn}).data?.connected===!0,b=Ie({...tl({client:Q,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&m,staleTime:xn}),g=l.useMemo(()=>c.data?.series?.points??[],[c.data]),f=l.useMemo(()=>{const k=b.data;return new Map((k?.days??[]).map(E=>[E.date,E.sessions]))},[b.data]),x=l.useMemo(()=>{const k=O=>O.measured!==!1;if(g.length===0||k(g[0]))return null;const E=g.findIndex(k)-1;return E<0?{from:g[0].bucket,to:g[g.length-1].bucket}:{from:g[0].bucket,to:g[E].bucket}},[g]),y=c.data?.series?.coverageStart??null,P=c.data?.series?.trends,S=l.useMemo(()=>{const k=dr(P?.crawlerContentHits,g.length),E=dr(P?.aiUserFetchHits,g.length),O=dr(P?.aiReferralLandedHits,g.length);return g.map((Z,U)=>({...Z,crawlerContentHits:Z.measured!==!1?as(Z.crawlerContentHits):null,aiUserFetchHits:Z.measured!==!1?as(Z.aiUserFetchHits):null,aiReferralLandedHits:Z.measured!==!1?as(Z.aiReferralLandedHits):null,ga4Visits:f.get(Z.bucket)??null,crawlTrend:k[U],fetchTrend:E[U],visitTrend:O[U]}))},[g,f,P]),q=c.data?.totals,T=q&&{crawlers:as(q.crawlerContentHits),fetches:as(q.aiUserFetchHits),visits:as(q.aiReferralLandedHits)},v=l.useMemo(()=>g.reduce((k,E)=>({crawlers:k.crawlers+as(E.crawlerContentHits),fetches:k.fetches+as(E.aiUserFetchHits),visits:k.visits+as(E.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[g]),j=T??v,N=j.crawlers>0||j.fetches>0||j.visits>0;if(c.isLoading)return e.jsx(pe,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(c.isError)return e.jsxs(pe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!N){const k=h.data?.sources,E=k!==void 0&&k.length===0,O=!E&&y===null;return e.jsxs(pe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:E?"No server-side traffic source connected yet.":O?"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.":O?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(ur,{label:"AI crawlers",value:Hs(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:Hs(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:Hs(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."})]}),g.length>0&&e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-xs text-muted",children:[e.jsx("span",{className:"text-secondary font-semibold",children:"Latest day (UTC)"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(g[g.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(g[g.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(g[g.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:f.get(g[g.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(Ue,{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:k=>a(k.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:k=>o(k.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Js,{width:"100%",height:206,children:e.jsxs(Xs,{data:S,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(sa,{stroke:ta,vertical:!1}),e.jsx(Zs,{dataKey:"bucket",tick:$t,stroke:cs,tickFormatter:bn,minTickGap:28}),e.jsx(en,{tick:$t,stroke:cs,width:48,allowDecimals:!1}),e.jsx(tn,{contentStyle:es.contentStyle,labelStyle:es.labelStyle,itemStyle:es.itemStyle,labelFormatter:Ft,formatter:Qi}),x&&e.jsx(Fr,{x1:x.from,x2:x.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(Ga,{wrapperStyle:Vi,iconType:"plainline",iconSize:14,formatter:k=>zi.has(k)?"":k}),e.jsx(Us,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:lr,fill:lr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Us,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:cr,fill:cr,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Rs,{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(Rs,{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(Ue,{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(za,{windows:Fh,value:i,onChange:d,label:"Visit measurement source",formatOption:k=>k==="ga4"?"GA4":k==="both"?"Both":"Server"})]}),e.jsx(Js,{width:"100%",height:176,children:e.jsxs(Xs,{data:S,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(sa,{stroke:ta,vertical:!1}),e.jsx(Zs,{dataKey:"bucket",tick:$t,stroke:cs,tickFormatter:bn,minTickGap:28}),e.jsx(en,{tick:$t,stroke:cs,width:48,allowDecimals:!1}),e.jsx(tn,{contentStyle:es.contentStyle,labelStyle:es.labelStyle,itemStyle:es.itemStyle,labelFormatter:Ft,formatter:Qi}),x&&e.jsx(Fr,{x1:x.from,x2:x.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(Ga,{wrapperStyle:Vi,iconType:"plainline",iconSize:14,formatter:k=>zi.has(k)?"":k}),i!=="ga4"&&e.jsx(Rs,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Ui,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Rs,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Bi,strokeWidth:1.8,strokeDasharray:"5 3",dot:Gh(S.map(k=>k.ga4Visits),Bi)}),r&&i!=="ga4"&&e.jsx(Rs,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Ui,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const _h=6,Mn="__other__",Rn="_socialTotal";function Uh(t,s=_h){const n=new Map;for(const u of t)n.set(u.source,(n.get(u.source)??0)+u.sessions);const a=[...n.entries()].sort((u,m)=>m[1]!==u[1]?m[1]-u[1]:u[0].localeCompare(m[0])),r=a.slice(0,s),o=new Set(r.map(([u])=>u)),i=Math.max(0,a.length-s),d=new Map;for(const u of t){let m=d.get(u.date);m||(m={date:u.date,[Rn]:0},d.set(u.date,m));const b=o.has(u.source)?u.source:Mn;m[b]=(m[b]??0)+u.sessions,m[Rn]=(m[Rn]??0)+u.sessions}const c=[...d.values()].sort((u,m)=>String(u.date).localeCompare(String(m.date))),h=r.map(([u])=>u);return i>0&&h.push(Mn),{data:c,sources:h,otherCount:i}}function In(t){return t.replace(/\+/g," ")}function Il(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Hi="_totalSessions",Wi="_organicSessions";function Bh(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Hi]:i.sessions,[Wi]:i.organicSessions});for(const i of t.days){let d=n.get(i.date);d||(d={[Hi]:0,[Wi]:0},n.set(i.date,d));for(const c of i.bySource)d[c.source]=(d[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([i],[d])=>i.localeCompare(d)).map(([i,d])=>({date:i,...d})),r=a.map(i=>i.date),o=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:o}}const Vh=["7d","30d","90d"],zh={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},_s=at,Br=ds.textDim,Tl=ds.textFaint,Un=25;function Qh(t){return vl(t.landingPage)}const Hh=25,Wh=10,mr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function ba(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function $l(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 Yh({projectName:t}){const{data:s,isLoading:n,isError:a}=eh(t);if(n)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!ie()&&e.jsx(Ss,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(pe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ie()&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(pe,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(o=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:o.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ce,{tone:th(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?$l(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ie()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Ss,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function Jh({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Yh,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(za,{windows:Vh,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(Xh,{projectName:t,window:s}),e.jsx(Kh,{projectName:t,sinceMinutes:zh[s]})]})}function Xh({projectName:t,window:s}){const n=us(),a=s??"30d",[r,o]=l.useState(null),[i,d]=l.useState(null),[c,h]=l.useState(!0),[u,m]=l.useState(!1),[b,g]=l.useState(!1),[f,x]=l.useState(null),[y,P]=l.useState(null),[S,q]=l.useState("sessions"),[T,v]=l.useState("desc"),[j,N]=l.useState("sessions"),[k,E]=l.useState("desc"),[O,Z]=l.useState("sessions"),[U,F]=l.useState("desc"),[z,V]=l.useState("sessions"),[te,Y]=l.useState("desc"),[A,ee]=l.useState(mr),[_,B]=l.useState([]),[w,H]=l.useState([]),[se,oe]=l.useState(!1);async function ne(X){h(!0),x(null);try{const Le=await n.fetchQuery({...el({client:Q,path:{name:t}}),staleTime:xn});if(X.current)return;if(o(Le),!Le.connected){d(null),ee(mr),B([]),H([]),h(!1);return}const Ae=a==="all"?void 0:a,ke=await n.fetchQuery({...kc({client:Q,path:{name:t},query:Ae?{window:Ae}:void 0}),staleTime:xn}).then(it=>it),Wt=ke.windowStart||ke.windowEnd?{...ke.windowStart?{startDate:ke.windowStart}:{},...ke.windowEnd?{endDate:ke.windowEnd}:{}}:void 0,[Yt,Gt,ft]=await Promise.all([n.fetchQuery({...tl({client:Q,path:{name:t},query:Ae?{window:Ae}:void 0}),staleTime:xn}).catch(()=>mr),n.fetchQuery({...Ac({client:Q,path:{name:t},query:Ae?{window:Ae}:void 0}),staleTime:xn}).catch(()=>[]),n.fetchQuery({...Pc({client:Q,path:{name:t},query:Wt}),staleTime:xn}).catch(()=>[])]);if(X.current)return;d(ke),ee(Yt),B(Gt),H(ft),h(!1)}catch(Le){if(X.current)return;x(Le instanceof Error?Le.message:"Failed to load GA4 data"),h(!1)}}l.useEffect(()=>{const X={current:!1};return ne(X),()=>{X.current=!0}},[t,a,n]);async function ye(){m(!0),x(null),P(null);try{const X=await sl(t);P(`Synced ${X.rowCount.toLocaleString()} page rows, ${X.aiReferralCount.toLocaleString()} AI and ${X.socialReferralCount.toLocaleString()} social referral rows (${X.days} days)`),await wt(n,"ga"),await ne({current:!1})}catch(X){x(X instanceof Error?X.message:"Sync failed")}finally{m(!1)}}async function W(){g(!0),x(null),P(null);try{await Rc(t),await wt(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),d(null),P("GA4 disconnected")}catch(X){x(X instanceof Error?X.message:"Disconnect failed")}finally{g(!1)}}function ue(X){K.setPage(1),S===X?v(Le=>Le==="desc"?"asc":"desc"):(q(X),v("desc"))}function ve(X){j===X?E(Le=>Le==="desc"?"asc":"desc"):(N(X),E("desc"))}function J(X){O===X?F(Le=>Le==="desc"?"asc":"desc"):(Z(X),F("desc"))}const me=l.useMemo(()=>i?.topPages?[...i.topPages].sort((X,Le)=>{const Ae=X[S],ke=Le[S];return typeof Ae=="string"&&typeof ke=="string"?T==="asc"?Ae.localeCompare(ke):ke.localeCompare(Ae):T==="asc"?Ae-ke:ke-Ae}):[],[i?.topPages,S,T]),K=yn({rows:me,getSearchText:X=>vl(X.landingPage),pageSize:Wh}),xe=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((X,Le)=>{const Ae=X[j],ke=Le[j];return typeof Ae=="string"&&typeof ke=="string"?k==="asc"?Ae.localeCompare(ke):ke.localeCompare(Ae):k==="asc"?Ae-ke:ke-Ae}):[],[i?.aiReferrals,j,k]),we=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((X,Le)=>{const Ae=X[z],ke=Le[z];return typeof Ae=="string"&&typeof ke=="string"?te==="asc"?Ae.localeCompare(ke):ke.localeCompare(Ae):te==="asc"?Ae-ke:ke-Ae}):[],[i?.aiReferralLandingPages,z,te]),Se=yn({rows:we,getSearchText:Qh,pageSize:Hh}),Ze=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 Be(X){Se.setPage(1),z===X?Y(Le=>Le==="desc"?"asc":"desc"):(V(X),Y("desc"))}const Fe=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((X,Le)=>{const Ae=X[O],ke=Le[O];return typeof Ae=="string"&&typeof ke=="string"?U==="asc"?Ae.localeCompare(ke):ke.localeCompare(Ae):U==="asc"?Ae-ke:ke-Ae}):[],[i?.socialReferrals,O,U]),{socialChartData:et,socialChartSources:Me,socialOtherCount:D}=l.useMemo(()=>{const X=Uh(w);return{socialChartData:X.data,socialChartSources:X.sources,socialOtherCount:X.otherCount}},[w]),{chartData:$e,chartSources:R,dateRange:ge}=l.useMemo(()=>{const X=Bh(A,_);return{chartData:X.data,chartSources:X.sources,dateRange:X.dateRange}},[A,_]);if(c&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return ie()||Is()?e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Zh,{projectName:t,onConnected:()=>{(async()=>(await wt(n,"ga"),await ne({current:!1})))()}});const Ee=i?.organicSharePctDisplay??"0%",Qe=i?.channelBreakdown?.organic.sharePctDisplay??Ee,Ge=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,he=i?.aiSessionsDeduped??0,ht=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,Ke=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",De=i?.paidAiSessionsBySession??0,St=i?.paidAiSharePctBySessionDisplay??"0%",Ye=i?new Set(i.aiReferrals.map(X=>X.source.toLowerCase())).size:0,Ce=xe[0]??null,rt=i?.totalDirectSessions??0,pt=i?.directSharePctDisplay??"0%",Mt=i?.channelBreakdown?.direct.sessions??rt,qe=i?.channelBreakdown?.direct.sharePctDisplay??pt,C=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Re=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ne=i?.socialSessions??0,Ve=i?.socialSharePctDisplay??"0%",gt=i?.channelBreakdown?.social.sessions??Ne,tt=i?.channelBreakdown?.social.sharePctDisplay??Ve,Pt=i?new Set(i.socialReferrals.map(X=>X.source.toLowerCase())).size:0,We=Fe[0]??null;return e.jsxs(e.Fragment,{children:[f&&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:f}),y&&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:y}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!ie()&&!Is()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(I,{variant:"outline",size:"sm",disabled:u,onClick:He(ye),children:[e.jsx(ea,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(I,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:b,onClick:He(W),children:[e.jsx(Fm,{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(Ue,{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:ba(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(hr,{value:ba(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Ee} of total`,tone:"positive"}),e.jsx(hr,{value:i.totalUsers===null?"—":ba(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!ie()&&!Is()&&e.jsxs(I,{variant:"outline",size:"sm",disabled:u,onClick:He(ye),children:[e.jsx(ea,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Ue,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),ge&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(ge.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(ge.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),$e.length>0&&e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:R.length>0?"AI vs. total sessions":"All sessions (baseline)"}),R.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),R.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(Js,{width:"100%",height:"100%",children:e.jsxs(Xs,{data:$e,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Zs,{dataKey:"date",tick:$t,tickLine:!1,axisLine:{stroke:cs},tickFormatter:bn}),e.jsx(en,{tick:$t,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(tn,{...es,labelFormatter:Ft,formatter:(X,Le)=>{const Ae=typeof X=="number"?X.toLocaleString():String(X??0),ke=String(Le??"");return ke==="_totalSessions"?[Ae,"Total Sessions"]:ke==="_organicSessions"?[Ae,"Organic Sessions"]:[Ae,ke]}}),e.jsx(Ga,{wrapperStyle:{fontSize:11,color:ds.text},formatter:X=>X==="_totalSessions"?"Total Sessions":X==="_organicSessions"?"Organic Sessions":X}),e.jsx(Us,{type:"monotone",dataKey:"_totalSessions",stroke:ds.textFaint,fill:ds.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),R.map((X,Le)=>e.jsx(Us,{type:"monotone",dataKey:X,stackId:"ai",stroke:_s[Le%_s.length],fill:_s[Le%_s.length],fillOpacity:.4,strokeWidth:1.5},X))]})})})]}),e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(xs,{label:"Organic",value:Qe,hint:`${Ge.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions from Google organic search (sessionDefaultChannelGrouping = 'Organic Search'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(xs,{label:"Social",value:tt,hint:`${gt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(xs,{label:"Direct",value:qe,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(xs,{label:"Visitors from AI (at least)",value:Ke,hint:De>0?`${ht.toLocaleString()} sessions · ${De.toLocaleString()} paid`:`${ht.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(xs,{label:"Other channels",value:Re,hint:`${C.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."})]}),Ce&&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:Ce.source})," via ",Ce.medium,", accounting for ",Ce.sessions.toLocaleString()," sessions.",De>0&&e.jsxs("span",{children:[" Paid AI: ",De.toLocaleString()," sessions (",St,")."]})]})]}),e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${Ye} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(rs,{label:"Source",sortKey:"source",current:j,dir:k,onSort:ve,align:"left"}),e.jsx(rs,{label:"Medium",sortKey:"medium",current:j,dir:k,onSort:ve,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:j,dir:k,onSort:ve,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:xe.map(X=>e.jsx(tx,{referral:X,totalSessions:he},`${X.source}:${X.medium}:${X.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:Ze})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(zs,{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(rs,{label:"Landing Page",sortKey:"landingPage",current:z,dir:te,onSort:Be,align:"left"}),e.jsx(rs,{label:"Source",sortKey:"source",current:z,dir:te,onSort:Be,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:z,dir:te,onSort:Be,align:"right"})]})}),e.jsx("tbody",{children:Se.rows.map(X=>e.jsx(sx,{row:X},`${X.landingPage}:${X.source}:${X.medium}:${X.sourceDimension}`))})]})}),e.jsx(Ts,{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(Ue,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(xs,{label:"Social Sessions",value:ba(Ne),hint:`${Ne.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(xs,{label:"Share of Traffic",value:Ve,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(xs,{label:"Platforms",value:String(Pt),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),We&&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:`${We.source} via ${We.medium}`,children:Il(In(We.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:We.medium,children:["via ",In(We.medium)," · ",We.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(xs,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(xs,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(xs,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),et.length>0&&e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),D>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Me.length-1," sources · ",D," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Js,{width:"100%",height:"100%",children:e.jsxs(Xs,{data:et,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Zs,{dataKey:"date",tick:$t,tickLine:!1,axisLine:{stroke:cs},tickFormatter:bn}),e.jsx(en,{tick:$t,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(tn,{...es,labelFormatter:Ft,formatter:(X,Le)=>{const Ae=typeof X=="number"?X.toLocaleString():String(X??0),ke=String(Le??"");if(ke===Rn)return[Ae,"Total Social"];if(ke===Mn){const Wt=`Other (${D} source${D===1?"":"s"})`;return[Ae,Wt]}return[Ae,In(ke)]}}),e.jsx(Us,{type:"monotone",dataKey:Rn,stroke:Tl,fill:ds.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Me.map((X,Le)=>{const ke=X===Mn?Br:_s[Le%_s.length];return e.jsx(Us,{type:"monotone",dataKey:X,stackId:"social",stroke:ke,fill:ke,fillOpacity:.4,strokeWidth:1.5},X)})]})})}),e.jsx(ax,{sources:Me,otherCount:D})]}),e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Fe.length>Un&&!se?`Top ${Un} of ${Fe.length}`:`${Fe.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(rs,{label:"Source",sortKey:"source",current:O,dir:U,onSort:J,align:"left"}),e.jsx(rs,{label:"Medium",sortKey:"medium",current:O,dir:U,onSort:J,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:O,dir:U,onSort:J,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(se?Fe:Fe.slice(0,Un)).map(X=>e.jsx(nx,{referral:X,totalSessions:Ne},`${X.source}:${X.medium}:${X.channelGroup}`))})]})}),Fe.length>Un&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>oe(X=>!X),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:se?`Show top ${Un}`:`Show all ${Fe.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(Ue,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx(zs,{value:K.query,onChange:K.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(rs,{label:"Landing Page",sortKey:"landingPage",current:S,dir:T,onSort:ue,align:"left"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:S,dir:T,onSort:ue,align:"right"}),e.jsx(rs,{label:"Organic",sortKey:"organicSessions",current:S,dir:T,onSort:ue,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:K.rows.map(X=>e.jsx(ex,{page:X},X.landingPage))})]})}),K.totalRows===0&&K.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Ts,{page:K.page,pageSize:K.pageSize,visibleRows:K.rows.length,totalRows:K.totalRows,onPageChange:K.setPage,itemLabel:K.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 ${$l(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Zh({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,d]=l.useState(null),[c,h]=l.useState(!1),[u,m]=l.useState(null),b=l.useRef(null),g=l.useCallback(x=>{const y=x.target.files?.[0];if(!y)return;m(null),o(y.name);const P=new FileReader;P.onload=()=>{const S=P.result;try{const q=JSON.parse(S);if(!q.client_email||!q.private_key){m("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),d(null);return}d(S)}catch{m("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),d(null)}},P.onerror=()=>{m("Failed to read file."),d(null)},P.readAsText(y)},[]);async function f(){if(m(null),!n.trim()){m("Property ID is required.");return}if(!i){m("Please upload a service account key file.");return}h(!0);try{await Ic(t,{propertyId:n.trim(),keyJson:i});try{await sl(t)}catch{}s()}catch(x){m(x instanceof Error?x.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(pe,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),u&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:u}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:x=>a(x.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:g,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(Gm,{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(I,{variant:"default",size:"sm",disabled:c||!n.trim()||!i,onClick:He(f),children:c?"Connecting & syncing…":"Connect GA4"})]})}function rs({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 Ml={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 ${Ml[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function xs({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Ue,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Ml[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function ex({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 Ll={session:"Session",first_user:"First Visit",manual_utm:"UTM"},ql={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 tx({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Ll[t.sourceDimension]??t.sourceDimension,r=ql[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 sx({row:t}){const s=Ll[t.sourceDimension]??t.sourceDimension,n=ql[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(Ma,{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 nx({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=In(t.source),o=In(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 ax({sources:t,otherCount:s}){const n=[{key:Rn,color:Tl,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Mn)n.push({key:Mn,color:Br,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=In(r);n.push({key:r,color:_s[a%_s.length]??Br,label:Il(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 rx(t){const s=t.details;if(t.code!=="FORBIDDEN"||!s||s.reason!=="gsc-api-disabled")return null;const n=typeof s.projectNumber=="string"?s.projectNumber:void 0;return{title:"Enable the Search Console API",message:`Your Google Cloud project${n?` (${n})`:""} hasn't enabled the Search Console API. Enable the Search Console API and the Indexing API, wait ~2–5 minutes, then retry.`,enableUrl:typeof s.enableUrl=="string"?s.enableUrl:void 0,indexingApiUrl:typeof s.indexingApiUrl=="string"?s.indexingApiUrl:void 0,projectNumber:n}}const ix="Search Console is not connected yet. Your Canonry team can set this up.",ox=["7d","30d","90d","all"],va=500,Yi=[{key:"clicks",label:"Clicks",color:at[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:at[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:$s.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:at[2],inverted:!0,format:t=>t.toFixed(1)}],Fs=25,lx="canonry:google-oauth-complete",cx=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function dx(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const c=t.prior[s],h=t.trailing[s];return c!==null&&h!==null&&c<=0&&h>0?`new in the last ${a}d`:c===null||c<=0?`no prior ${a}d to compare`:h===null?`no value in the last ${a}d`:"comparison unavailable"}if(r===0)return`→ no change vs prior ${a}d`;const o=Math.abs(r*100),i=o<.1?"<0.1%":`${cx.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function ux(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,o=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,d=`${r.startDate} to ${r.endDate}`,c=`Tile percentages compare these ${s} ${o} (${d}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?c:`${c} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function Ji(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Xi(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 Zi(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function mx({projectName:t,refreshNonce:s}){const n=us(),{isAdmin:a}=vn(),r=Is(),[o,i]=l.useState(!1),[d,c]=l.useState([]),[h,u]=l.useState([]),[m,b]=l.useState([]),[g,f]=l.useState(null),[x,y]=l.useState([]),[P,S]=l.useState([]),[q,T]=l.useState(null),[v,j]=l.useState(""),[N,k]=l.useState(""),[E,O]=l.useState("30"),[Z,U]=l.useState(!1),[F,z]=l.useState("30d"),[V,te]=l.useState(["clicks","impressions"]),[Y,A]=l.useState(!0),[ee,_]=l.useState(null),[B,w]=l.useState(0),[H,se]=l.useState({startDate:"",endDate:"",query:"",page:""}),[oe,ne]=l.useState(0),[ye,W]=l.useState(!1),[ue,ve]=l.useState(0),[J,me]=l.useState(!1),[K,xe]=l.useState(""),[we,Se]=l.useState(!0),[Ze,Be]=l.useState(!1),[Fe,et]=l.useState(!1),[Me,D]=l.useState(!1),[$e,R]=l.useState(!1),[ge,Ee]=l.useState(!1),[Qe,Ge]=l.useState(!1),[he,ht]=l.useState(null),[Ke,De]=l.useState(!1),[St,Ye]=l.useState(!1),[Ce,rt]=l.useState(null),[pt,Mt]=l.useState(null),[qe,C]=l.useState([]),[Re,Ne]=l.useState(new Set),[Ve,gt]=l.useState({}),[tt,Pt]=l.useState(new Set),[We,X]=l.useState(""),[Le,Ae]=l.useState(null),[ke,Wt]=l.useState(""),[Yt,Gt]=l.useState(!1),[ft,it]=l.useState(!1),[Kt,ts]=l.useState(!1),[_t,Ut]=l.useState(!1),[dt,ss]=l.useState("indexed"),[Je,Lt]=l.useState(null),Bt=!!(H.query.trim()||H.page.trim()||Je),ps=Je!==null,ms=l.useMemo(()=>{if(!Je)return m;const{key:p,dir:$}=Je;return[...m].sort((re,de)=>{const Xe=p===pn.CTR?Number.isFinite(re.ctr)?re.ctr:0:re[p],st=p===pn.CTR?Number.isFinite(de.ctr)?de.ctr:0:de[p];return $==="asc"?Xe-st:st-Xe})},[m,Je]),Vt=yn({rows:ms,pageSize:Cs}),gs=J?Vt.rows:ms,Jt=yn({rows:(Ce??[]).filter(p=>p.path.toLowerCase().includes(We.trim().toLowerCase())),pageSize:Cs}),[vt,Xt]=l.useState([]),[yt,Zt]=l.useState(null),[fs,G]=l.useState(1),ae=l.useMemo(()=>{if(vt.length<2)return null;const p=vt[vt.length-1],$=vt[vt.length-2];return{indexed:p.indexed-$.indexed,notIndexed:p.notIndexed-$.notIndexed}},[vt]);l.useEffect(()=>{G(1)},[he,dt,yt]);const be=l.useMemo(()=>yt?(he?.reasonGroups??[]).find(p=>p.reason===yt):void 0,[he,yt]),le=l.useMemo(()=>he?dt==="indexed"?he.indexed:dt==="deindexed"?he.deindexed:dt==="notIndexed"?yt?be?.urls??[]:(he.reasonGroups??[]).length===0?he.notIndexed:[]:[]:[],[he,dt,yt,be]),je=Math.max(1,Math.ceil(le.length/Fs)),Oe=Math.min(Math.max(1,fs),je),ut=(Oe-1)*Fs,ot=l.useMemo(()=>he?.indexed.slice(ut,ut+Fs)??[],[he,ut]),ys=l.useMemo(()=>he?.notIndexed.slice(ut,ut+Fs)??[],[he,ut]),L=l.useMemo(()=>he?.deindexed.slice(ut,ut+Fs)??[],[he,ut]),fe=l.useMemo(()=>(be?.urls??[]).slice(ut,ut+Fs),[be,ut]),[nt,jt]=l.useState(!1),[ns,_e]=l.useState(null),[mt,Ls]=l.useState(null),[sn,zt]=l.useState(null);function qn(p,$){const re=sh(p),de=rx(re);de?(Ls(de),_e(null)):(Ls(null),_e(re.message||$))}const Ct=d.find(p=>p.connectionType==="gsc"),hs=(Ct?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),nn=qe.length>0?qe:(Ce??[]).map(p=>p.path),En=nn.filter(p=>Ce?.some($=>$.path===p&&$.isSitemapsIndex)).length,Ha=En===1?"Resubmit sitemap index":En>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Wa=m.length>0||x.length>0||P.length>0,oa=Tc(),an=$c();async function Dn(p,$=!1){if(r){u([]);return}if(!p){u([]),j("");return}et(!0);try{const{sites:re}=await n.fetchQuery({...zc({client:Q,path:{name:t}}),staleTime:$?0:Dt});u(re),j(p.propertyId??re[0]?.siteUrl??""),Ls(null)}catch(re){u([]),qn(re,"Failed to load Search Console properties")}finally{et(!1)}}async function rn(p){R(!0);const $=p??oe;try{const re=Bt?va:Cs,de=Bt?0:$,Xe={limit:String(re)};H.startDate&&(Xe.startDate=H.startDate),H.endDate&&(Xe.endDate=H.endDate),H.query&&(Xe.query=H.query),H.page&&(Xe.page=H.page),de>0&&(Xe.offset=String(de)),F&&F!=="all"&&!H.startDate&&(Xe.window=F);const st=await n.fetchQuery({...qc({client:Q,path:{name:t},query:Xe}),staleTime:Dt}),lt=st.rows;Bt?(W(!1),b(lt),ve(lt.length),me(!0)):(W(de+lt.length<st.totalMatching),b(lt),ve(0),me(!1))}catch(re){b([]),W(!1),ve(0),_e(re instanceof Error?re.message:"Failed to load GSC performance data")}finally{R(!1)}}async function qs(){try{const p={};H.startDate&&(p.startDate=H.startDate),H.endDate&&(p.endDate=H.endDate),F&&F!=="all"&&!H.startDate&&(p.window=F);const $=await n.fetchQuery({...Lc({client:Q,path:{name:t},query:p}),staleTime:Dt});f($)}catch{f(null)}}async function jn(p=!1){Ee(!0);try{const $=K.trim()||void 0,re={limit:"20"};$&&(re.url=$);const[de,Xe]=await Promise.all([n.fetchQuery({...Bc({client:Q,path:{name:t},query:re}),staleTime:p?0:Dt}),n.fetchQuery({...Vc({client:Q,path:{name:t}}),staleTime:p?0:Dt})]);y(de),S(Xe)}catch($){y([]),S([]),_e($ instanceof Error?$.message:"Failed to load GSC inspection history")}finally{Ee(!1)}}async function la(p=!1){De(!0);try{const[$,re]=await Promise.all([n.fetchQuery({...Oc({client:Q,path:{name:t}}),staleTime:p?0:Dt}),n.fetchQuery({...Fc({client:Q,path:{name:t}}),staleTime:p?0:Dt}).catch(()=>[])]);ht($),Xt(re)}catch($){ht(null),Xt([]),_e($ instanceof Error?$.message:"Failed to load coverage data")}finally{De(!1)}}async function ca(p){jt(!0),_e(null);try{const $=await Ni(t,{urls:p}),{succeeded:re,failed:de,total:Xe}=$.summary;Te({title:"Indexing requested",detail:de===0?`${re} URL${re!==1?"s":""} submitted for indexing.`:`${re}/${Xe} submitted successfully, ${de} failed.`,tone:de===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch($){_e($ instanceof Error?$.message:"Failed to request indexing")}finally{jt(!1)}}async function da(){jt(!0),_e(null);try{const p=await Ni(t,{urls:[],allUnindexed:!0}),{succeeded:$,failed:re,total:de}=p.summary;Te({title:"Indexing requested",detail:re===0?`${$} unindexed URL${$!==1?"s":""} submitted for indexing.`:`${$}/${de} submitted successfully, ${re} failed.`,tone:re===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(p){_e(p instanceof Error?p.message:"Failed to request indexing")}finally{jt(!1)}}async function On(){Ye(!0),_e(null);try{const p=await er(t);n.setQueryData(Gc({client:Q,path:{name:t}}),p),rt(p.sitemaps),Mt(p.summary),C(p.preferredSubmissionUrls),Ne(new Set),gt({}),p.sitemaps.length===0&&zt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(p){_e(p instanceof Error?p.message:"Failed to list sitemaps")}finally{Ye(!1)}}async function Ya(p){const $=Re.has(p);if(Ne(re=>{const de=new Set(re);return $?de.delete(p):de.add(p),de}),!($||Ve[p])){Pt(re=>new Set(re).add(p));try{const re=await er(t,p);gt(de=>({...de,[p]:re.sitemaps}))}catch(re){_e(re instanceof Error?re.message:"Failed to load sitemap files")}finally{Pt(re=>{const de=new Set(re);return de.delete(p),de})}}}async function Es(p){if(!hs||p.length===0)return;const $=[...new Set(p)];it(!0),_e(null),Ae({completed:0,total:$.length});let re=0,de=0,Xe=0,st=null;try{for(let kt=0;kt<$.length;kt+=50){const ct=$.slice(kt,kt+50);try{const Pe=await Kc(t,ct);re+=Pe.summary.accepted,de+=Pe.summary.failed,Xe+=ct.length,Ae({completed:Xe,total:$.length})}catch(Pe){Xe+=ct.length;const Ds=ct.length,_n=$.length-Xe,pa=Pe instanceof Error?Pe.message:"The batch request failed",Os=`${re} accepted, ${de} failed, ${Ds} unconfirmed, ${_n} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;st=`Sitemap submission stopped after a batch request failed. ${Os} ${pa}`,_e(st),Te({title:"Sitemap resubmission partially completed",detail:Os,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const lt=$.length;Te({title:de===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:de===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${re}/${lt} sitemap submissions; ${de} failed. Indexing is not guaranteed.`,tone:de===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Wt("")}catch(lt){_e(lt instanceof Error?lt.message:"Failed to submit sitemap to Google")}finally{it(!1),Ae(null),await On(),st&&_e(st)}}async function ua(){it(!0);const p=Ce??[];try{const $=p.filter(de=>de.isSitemapsIndex),re=[];for(let de=0;de<$.length;de+=4)(await Promise.all($.slice(de,de+4).map(async st=>{const lt=Ve[st.path];if(lt)return lt;const kt=await er(t,st.path);return gt(ct=>({...ct,[st.path]:kt.sitemaps})),kt.sitemaps}))).forEach((st,lt)=>{re.push(...st.length>0?st.map(kt=>kt.path):[$[de+lt].path])});await Es([...p.filter(de=>!de.isSitemapsIndex).map(de=>de.path),...re])}catch($){_e($ instanceof Error?$.message:"Failed to load sitemap files"),it(!1)}}async function ma(p){Gt(!0),_e(null);try{await _c(t,"gsc",p),await wt(n,"google"),c($=>$.map(re=>re.connectionType==="gsc"?{...re,sitemapUrl:p}:re)),Te({title:"Default sitemap updated",detail:p,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch($){_e($ instanceof Error?$.message:"Failed to set the default sitemap")}finally{Gt(!1)}}async function Fn(p){try{await an.mutateAsync({projectName:t,projectLabel:t,opts:p?{sitemapUrl:p}:void 0})}catch{}}async function Gn(){Se(!0),_e(null);try{const[p,$]=await Promise.all([r||!a?Promise.resolve(null):nl().catch(()=>null),n.fetchQuery({...ni({client:Q,path:{name:t}}),staleTime:Dt}).catch(()=>[])]);i(!!p?.google?.configured),c($);const re=$.find(de=>de.connectionType==="gsc");await Promise.all([r?Promise.resolve():Dn(re),rn(),qs(),jn(),la(),!r&&re?.propertyId?On():Promise.resolve()])}finally{Se(!1)}}l.useEffect(()=>{Gn()},[t,s,a]),l.useEffect(()=>{ne(0),_(null),se(p=>p.startDate||p.endDate?{...p,startDate:"",endDate:""}:p),w(p=>p+1),qs()},[F]);const Qt=l.useRef(!1);l.useEffect(()=>{if(!Qt.current){Qt.current=!0;return}ne(0),Vt.setPage(1),rn(0)},[B]);function Kn(p){const $=ee===p?null:p;_($),se(re=>({...re,startDate:$??"",endDate:$??""})),w(re=>re+1)}const ha=l.useRef(!1);l.useEffect(()=>{if(!ha.current){ha.current=!0;return}ne(0),rn(0)},[ps]);async function xa(){if(!o){_e("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Be(!0),_e(null),zt(null);try{let p=function(Pe){if(Pe.source!==de||Pe.origin!==Xe||!Pe.data||typeof Pe.data!="object")return;const Ds=Pe.data;Ds.type!==lx||Ds.connectionType!=="gsc"||ct(!0)};const{authUrl:$,redirectUri:re}=await Dc(t,"gsc");if(!$.startsWith("https://accounts.google.com/")){_e("Unexpected OAuth redirect URL. Please try again.");return}const de=window.open($,"_blank","width=600,height=700");if(!de){window.location.assign($);return}const Xe=re?new URL(re).origin:window.location.origin;let st=!1,lt=null;const kt=()=>{lt!==null&&window.clearInterval(lt),window.removeEventListener("message",p)},ct=async Pe=>{if(!st){st=!0,kt(),zt(Pe?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await wt(n,"google"),await Gn()}finally{zt(null)}}};window.addEventListener("message",p),zt("Finish the Google consent flow in the popup. This page will refresh automatically."),lt=window.setInterval(()=>{de.closed&&ct(!1)},1e3)}catch(p){_e(p instanceof Error?p.message:"Failed to start OAuth flow")}finally{Be(!1)}}async function Ja(){_e(null),zt(null);try{await Ec(t,"gsc"),await wt(n,"google"),c(p=>p.filter($=>$.connectionType!=="gsc")),u([]),j("")}catch(p){_e(p instanceof Error?p.message:"Failed to disconnect")}}async function Xa(){if(v){D(!0),_e(null);try{await Qc(t,"gsc",v),await wt(n,"google"),c(p=>p.map($=>$.connectionType==="gsc"?{...$,propertyId:v}:$)),Te({title:"GSC property updated",detail:`${t} is now linked to ${v}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(p){_e(p instanceof Error?p.message:"Failed to save GSC property")}finally{D(!1)}}}async function Za(){_e(null),zt(null);try{await oa.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(E,10)||void 0,full:Z||void 0}}),await wt(n,"gsc")}catch{}}async function M(){if(N.trim()){Ge(!0),_e(null),zt(null);try{const p=await Uc(t,N.trim());await wt(n,"gsc"),T(p),k(""),await jn()}catch(p){_e(p instanceof Error?p.message:"Failed to inspect URL")}finally{Ge(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),mt&&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:mt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:mt.message}),(Ks(mt.enableUrl)||Ks(mt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ks(mt.enableUrl)&&e.jsx("a",{href:Ks(mt.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 ↗"}),Ks(mt.indexingApiUrl)&&e.jsx("a",{href:Ks(mt.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:()=>Ls(null),children:"×"})]})}),ns&&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:[ns,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>_e(null),children:"×"})]}),sn&&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:[sn,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>zt(null),children:"×"})]}),we?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Ct?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:Ct.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",he?.lastInspectedAt?Ht(he.lastInspectedAt):"never"]}),!r&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:He(Ja),children:"Disconnect"})]}):a?e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ce,{tone:o?"caution":"negative",children:o?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:o?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[o?e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:Ze,onClick:He(xa),children:Ze?"Opening…":"Connect Google Search Console"}):e.jsx(I,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ss,{to:"/settings",children:"Open Settings"})}),!o&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}):e.jsx(pe,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:ix})}),(Ct||Wa)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Ue,{text:`${ux(g?.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 ${va.toLocaleString()} matching rows while the table shows ${Cs} per page.`})]}),g?.window?.startDate&&g.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[g.window.startDate," to ",g.window.endDate,(g.window.daysSinceLatestData??0)>0&&` · latest data ${g.window.daysSinceLatestData} day${g.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(za,{windows:ox,value:F,onChange:p=>{z(p),ne(0),Vt.setPage(1)},label:"Search Console time period",formatOption:p=>p==="all"?"All":p}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:$e,onClick:()=>{ne(0),Vt.setPage(1),rn(0),qs()},children:$e?"Loading…":"Apply filters"})]})]}),g&&g.daily.length>0&&(()=>{const{totals:p,daily:$,trends:re,periodComparison:de}=g,st=Yi.filter(Pe=>V.includes(Pe.key)).map(Pe=>({dataKey:Pe.key,label:Pe.label,color:Pe.color,axisId:Pe.key,inverted:Pe.inverted,formatValue:Pe.format,trend:Y?re?.[Pe.key]??null:null})),lt=Pe=>p[Pe]??null,kt=new Map($.map(Pe=>[Pe.date,Pe])),ct=$.length===0?[]:rh($[0].date,$[$.length-1].date).map(Pe=>kt.get(Pe)??{date:Pe});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Yi.map(Pe=>{const Ds=V.includes(Pe.key),_n=lt(Pe.key),pa=_n===null;return e.jsxs("button",{type:"button","aria-pressed":Ds,disabled:pa,className:`rounded-md border px-3 py-2 text-left transition-colors ${Ds?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${pa?"cursor-not-allowed opacity-50":""}`,onClick:()=>{te(Os=>Os.includes(Pe.key)?Os.length===1?Os:Os.filter(oc=>oc!==Pe.key):[...Os,Pe.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:Ds?Pe.color:"transparent",border:`1px solid ${Pe.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:Pe.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:_n===null?"—":Pe.format(_n)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:dx(de,Pe.key,Pe.inverted)})]},Pe.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:Y,onChange:Pe=>A(Pe.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(jl,{data:ct,xKey:"date",series:st,xTickFormatter:bn,labelFormatter:Ft,onSelectX:Kn,selectedX:ee})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:$.map(Pe=>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":ee===Pe.date,onClick:()=>Kn(Pe.date),children:[Ft(Pe.date),": ",Pe.clicks," clicks, ",Pe.impressions," impressions"]},Pe.date))}),ee&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Ft(ee)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Kn(ee),children:["Show all ",p.days," days"]})]}),p.position!==null&&(p.positionDays??p.days)<p.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",p.positionDays," of ",p.days," days. The rest have no property-level position recorded."]}),(p.position===null||p.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:H.startDate,onChange:p=>se($=>({...$,startDate:p.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:H.endDate,onChange:p=>se($=>({...$,endDate:p.target.value}))}),e.jsx(zs,{value:H.query,onChange:p=>se($=>({...$,query:p})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(zs,{value:H.page,onChange:p=>se($=>({...$,page:p})),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(pn).map(p=>e.jsx("th",{className:"text-right","aria-sort":Je?.key===p?Je.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:()=>{Vt.setPage(1),Lt($=>$?.key===p?$.dir==="desc"?{key:p,dir:"asc"}:null:{key:p,dir:"desc"})},children:[Mc[p],Je?.key===p?Je.dir==="desc"?" ↓":" ↑":""]})},p))]})}),e.jsx("tbody",{children:gs.map((p,$)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:p.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:p.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Ma,{value:p.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:p.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:p.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(p.ctr)?p.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:p.position.toFixed(1)})]},`${p.date}:${p.query}:${p.page}:${$}`))})]})}),e.jsx(Ts,{page:J?Vt.page:Math.floor(oe/Cs)+1,pageSize:Cs,visibleRows:gs.length,totalRows:J?ue:void 0,hasNextPage:J?void 0:ye,disabled:$e,itemLabel:J?"matches":"rows",onPageChange:p=>{if(J){Vt.setPage(p);return}const $=(p-1)*Cs;ne($),rn($)}}),J&&ue>=va?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",va.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Ue,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[he&&he.notIndexed.length>0&&e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:nt,onClick:()=>{da()},children:nt?"Requesting…":`Request indexing (${he.notIndexed.length})`}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:Ke,onClick:()=>{la(!0)},children:Ke?"Loading…":"Reload saved coverage"})]})]}),he&&he.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const p=he.summary.indexed+he.summary.notIndexed,$=p>0?he.summary.indexed/p:0,re=p>0?he.summary.notIndexed/p:0,de=54,Xe=2*Math.PI*de,st=Xe*(1-$),lt=Xe*re,kt=Xe*$;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:de,fill:"none",stroke:ds.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:$s.positiveDeep,strokeWidth:"14",strokeDasharray:Xe,strokeDashoffset:st,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),he.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:de,fill:"none",stroke:ds.textFaint,strokeWidth:"14",strokeDasharray:`${lt} ${Xe-lt}`,strokeDashoffset:-kt,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:[($*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:he.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:he.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(he.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(he.reasonGroups??[]).length," ",(he.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),he.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:he.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(p=>{const $=p==="indexed"?he.indexed.length:p==="notIndexed"?he.notIndexed.length:he.deindexed.length,re=p==="indexed"?"Indexed":p==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":dt===p,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${dt===p?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{ss(p),Zt(null)},children:[re," (",$,")"]},p)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[dt==="indexed"&&he.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:ot.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:p.url}),e.jsx("td",{className:"text-secondary",children:p.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:p.crawlTime?p.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:p.isMobileFriendly===!0?"Yes":p.isMobileFriendly===!1?"No":"—"})]},p.id))})]}),dt==="notIndexed"&&!yt&&(he.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(he.reasonGroups??[]).map(p=>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(p.reason),onKeyDown:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),Zt(p.reason))},tabIndex:0,role:"button","aria-label":`View ${p.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:p.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:p.count})]},p.reason))})]}),dt==="notIndexed"&&!yt&&(he.reasonGroups??[]).length===0&&he.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:ys.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:p.url}),e.jsx("td",{className:"text-secondary",children:p.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:p.coverageState??"Unknown"})]},p.id))})]}),dt==="notIndexed"&&yt&&(()=>{const p=(he.reasonGroups??[]).find($=>$.reason===yt);return p?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:p.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[p.count," affected page",p.count!==1?"s":""]})]}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:nt,onClick:()=>{ca(p.urls.map($=>$.url))},children:nt?"Requesting…":`Request indexing (${p.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:fe.map($=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:$.url}),e.jsx("td",{className:"text-secondary",children:$.crawlTime?$.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:nt,onClick:()=>{ca([$.url])},title:"Request indexing",children:"Index"})})]},$.id))})]})]}):null})(),dt==="deindexed"&&he.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:L.map((p,$)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:p.url}),e.jsx("td",{className:"text-secondary",children:p.previousState}),e.jsx("td",{className:"text-secondary",children:p.currentState}),e.jsx("td",{className:"text-secondary",children:p.transitionDate.split("T")[0]})]},`${p.url}-${$}`))})]}),(dt==="indexed"&&he.indexed.length===0||dt==="notIndexed"&&!yt&&he.notIndexed.length===0||dt==="deindexed"&&he.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ts,{page:Oe,pageSize:Fs,visibleRows:Math.min(Fs,le.length-ut),totalRows:le.length,onPageChange:G,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":_t,onClick:()=>Ut(p=>!p),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:_t?"Hide snapshots":vt.length>0?`View ${vt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",he.summary.indexed.toLocaleString()," indexed, ",he.summary.notIndexed.toLocaleString()," not indexed.",ae&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ae.indexed>=0?"+":"",ae.indexed.toLocaleString()," indexed, ",ae.notIndexed>=0?"+":"",ae.notIndexed.toLocaleString()," not indexed."]})]}),_t&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:vt.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:vt.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:p.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:p.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:p.notIndexed.toLocaleString()})]},p.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:Ke?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),!r&&e.jsxs(e.Fragment,{children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Ue,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:St||!Ct?.propertyId,onClick:()=>{On()},children:St?"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:ke,onChange:p=>Wt(p.target.value),onKeyDown:p=>p.key==="Enter"&&void Es([ke.trim()])}),e.jsx(I,{type:"button",size:"sm",disabled:!hs||ft||!ke.trim(),onClick:()=>{Es([ke.trim()])},children:ft?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(I,{type:"button",size:"sm",variant:"outline",disabled:!hs||ft||nn.length===0,onClick:()=>{Es(nn)},children:ft?"Resubmitting…":Ha}),e.jsx(I,{type:"button",size:"sm",variant:"outline",disabled:!hs||ft||!Ce?.length,onClick:()=>{ua()},children:"Resubmit all files"}),pt&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",pt.indexes," index",pt.indexes===1?"":"es",", ",pt.files," file",pt.files===1?"":"s"]}),Le&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Le.completed,"/",Le.total]})]}),!hs&&Ct&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:He(xa),children:"Reconnect"})]}),Ce&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:Ce.length>0?e.jsxs(e.Fragment,{children:[e.jsx(zs,{value:We,onChange:p=>{X(p),Jt.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:Jt.rows.flatMap(p=>{const $=Ji(p),re=Xi(p),de=Zi(p),Xe=Ve[p.path]??[],st=Re.has(p.path),lt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Ma,{value:p.path})}),e.jsx("td",{className:"text-secondary",children:p.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":st,"aria-label":`${st?"Collapse":"Expand"} files in ${p.path}`,onClick:()=>{Ya(p.path)},children:tt.has(p.path)?"Loading…":`${st?"▾":"▸"} Index${Ve[p.path]?` (${Xe.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:de}),e.jsx("td",{className:"text-secondary",children:p.lastSubmitted?p.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:p.lastDownloaded?p.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:$.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:re||"—"}),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:!hs||ft,onClick:()=>{Es([p.path])},children:p.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Ct?.sitemapUrl===p.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:()=>{ma(p.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:an.isPending,onClick:()=>{Fn(p.path)},children:"Inspect URLs"})]})})]},p.path),kt=p.isSitemapsIndex&&st?Xe.map(ct=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Ma,{value:ct.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Zi(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:Ji(ct).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Xi(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:!hs||ft,onClick:()=>{Es([ct.path])},children:"Resubmit"}),Ct?.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:()=>{ma(ct.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:an.isPending,onClick:()=>{Fn(ct.path)},children:"Inspect URLs"})]})})]},`${p.path}:${ct.path}`)):[];return[lt,...kt]})})]}),e.jsx(Ts,{page:Jt.page,pageSize:Cs,visibleRows:Jt.rows.length,totalRows:Jt.totalRows,onPageChange:Jt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:N,onChange:p=>k(p.target.value),onKeyDown:p=>p.key==="Enter"&&void M()}),e.jsx(I,{type:"button",size:"sm",disabled:Qe||!Ct?.propertyId||!N.trim(),onClick:He(M),children:Qe?"Inspecting…":"Inspect URL"})]}),q&&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:q.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:q.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:ji(q.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Ht(q.crawlTime)})]})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:ge,onClick:()=>{jn(!0)},children:ge?"Loading…":"Refresh history"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:K,onChange:p=>xe(p.target.value)}),e.jsx(I,{type:"button",size:"sm",variant:"outline",disabled:ge,onClick:()=>{jn(!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(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:p.url}),e.jsx("td",{className:"text-neutral",children:p.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:p.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:p.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:ji(p.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Ht(p.inspectedAt)})]},p.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),P.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:P.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:p.url}),e.jsx("td",{className:"text-secondary",children:p.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:p.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ht(p.transitionDate)})]},`${p.url}:${p.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Ct&&!r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>ts(p=>!p),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 ${Kt?"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"})]})}),Kt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Ue,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:v,disabled:Fe||h.length===0,onChange:p=>j(p.target.value),children:h.length===0?e.jsx("option",{value:"",children:Fe?"Loading properties…":"No properties available"}):h.map(p=>e.jsxs("option",{value:p.siteUrl,children:[p.siteUrl," · ",p.permissionLevel]},p.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(I,{type:"button",size:"sm",variant:"outline",disabled:Fe,onClick:()=>{Dn(Ct,!0)},children:Fe?"Refreshing…":"Refresh properties"}),e.jsx(I,{type:"button",size:"sm",disabled:!v||Me,onClick:He(Xa),children:Me?"Saving…":"Save property"})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:E,onChange:p=>O(p.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:Z,onChange:p=>U(p.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(I,{type:"button",size:"sm",disabled:oa.isPending||!Ct.propertyId,onClick:He(Za),children:oa.isPending?"Queueing…":"Queue sync"}),!Ct.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const hx=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function xx({projectName:t,projectId:s}){const n=us(),[a,r]=l.useState(null),[o,i]=l.useState(null),[d,c]=l.useState(!1),h=Ie(ni({client:Q,path:{name:t}})),u=h.data?.find(W=>W.connectionType==="gbp"),m=!!u,b=a?{locationName:a}:void 0,g=Ie({...Hc({client:Q,path:{name:t}}),enabled:m}),f=Ie({...Wc({client:Q,path:{name:t},query:b}),enabled:m}),x=Ie({...Yc({client:Q,path:{name:t},query:b}),enabled:m}),y=Ie({...Jc({client:Q,path:{name:t},query:b}),enabled:m}),P=Ie({...Xc({client:Q,path:{name:t},query:b}),enabled:m}),S=Ie({...Zc({client:Q,path:{name:t},query:b}),enabled:m}),q=Ie({queryKey:["gbp-section-insights",t],queryFn:()=>ed(t),enabled:m});function T(){wt(n,"gbp")}const v=At({...td(),onSuccess:W=>{al({id:W.runId,projectId:s,kind:Ws["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(rl,Ea,Ea),N=Object.values(j.runs).some(W=>W.kind===Ws["gbp-sync"]&&W.projectId===s),k=v.isPending||N,E=At({...sd(),onSuccess:()=>T()});if(l.useEffect(()=>{if(!a||!g.data)return;const W=g.data.locations.filter(ue=>ue.selected);(W.length<=1||!W.some(ue=>ue.locationName===a))&&r(null)},[a,g.data]),l.useEffect(()=>{if(!o||!g.data)return;(a?[a]:g.data.locations.filter(ue=>ue.selected).map(ue=>ue.locationName)).includes(o)||i(null)},[o,g.data,a]),h.isLoading)return null;if(!u){const W=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(pe,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:W.map((ue,ve)=>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:ve+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ue.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-bg-elevated/80 px-2 py-1 font-mono text-xs text-neutral",children:ue.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ue.note})]})]},ue.title))})]})})}const O=f.data,Z=g.data?.locations??[],U=Z.filter(W=>W.selected),F=x.data?.keywords??[],z=y.data?.lodging??[],V=P.data?.placeActions??[],te=S.data?.places??[],Y=Z.length>0?Z[0].accountName:u.domain,A=a?Z.find(W=>W.locationName===a)?.displayName??null:null,ee=a?Z.filter(W=>W.locationName===a):U,_=new Set(ee.map(W=>W.locationName)),B=z.filter(W=>_.has(W.locationName)),w=V.filter(W=>_.has(W.locationName)),H=te.filter(W=>_.has(W.locationName)),se=new Set(U.map(W=>W.locationName)),oe=a?F:F.filter(W=>se.has(W.locationName)),ne=!a&&U.length>1,ye=(q.data??[]).filter(W=>!W.dismissed&&hx.has(W.type)&&(!A||W.query===A||W.query===a||W.title.startsWith(A)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Ue,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(ze,{type:"button",variant:"outline",size:"sm",disabled:k,onClick:()=>v.mutate({client:Q,path:{name:t},body:{}}),children:k?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[Y?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:Y})," · "]}):null,g.data?`${g.data.totalSelected} of ${g.data.totalDiscovered} locations tracked`:"Loading locations…"]}),U.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:W=>r(W.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),U.map(W=>e.jsx("option",{value:W.locationName,children:W.displayName},W.id))]})]}),U.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[ye.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),ye.map(W=>e.jsx("div",{className:["insight-card",Ax(W.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:[W.title,W.recommendation?.reason&&e.jsx(Ue,{text:W.recommendation.reason})]})},W.id))]}),O&&e.jsx(Tx,{performance:O.performance,freshness:O.freshness,timeseries:O.timeseries}),O?.profileCompleteness&&e.jsx(px,{summary:O.profileCompleteness}),ee.length>0&&e.jsx(gx,{locations:ee,lodging:B,places:H,placeActions:w,expandedLocation:o,onToggleExpanded:W=>{i(ue=>ue===W?null:W)}}),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"}),x.data&&x.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[x.data.thresholdedPct,"% privacy-thresholded"]})]}),oe.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"}),ne&&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:oe.slice(0,25).map(W=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:W.keyword}),ne&&e.jsx("td",{className:"text-muted",children:Z.find(ue=>ue.locationName===W.locationName)?.displayName??W.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:W.valueCount!==null?W.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",W.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[W.periodStart,"–",W.periodEnd]})]},`${W.locationName}:${W.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>c(W=>!W),"aria-expanded":d,children:[e.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"})," Manage locations (",Z.length,")"]}),d&&e.jsx("div",{className:"mt-3",children:Z.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!ie()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:Z.map(W=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:W.displayName}),e.jsx("td",{className:"text-muted",children:W.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ce,{tone:W.selected?"positive":"neutral",children:W.selected?"Tracked":"Not tracked"})}),!ie()&&e.jsx("td",{className:"text-right",children:e.jsx(ze,{type:"button",variant:"outline",size:"sm",disabled:E.isPending,onClick:()=>E.mutate({client:Q,path:{name:t,locationName:W.locationName},body:{selected:!W.selected}}),children:W.selected?"Untrack":"Track"})})]},W.id))})]})})]})]})})}function px({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Bn(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Bn(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Bn(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Bn(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Bn(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(Ue,{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 ${kx(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function gx({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:o}){const i=new Map(s.map(h=>[h.locationName,h])),d=new Map(n.map(h=>[h.locationName,h])),c=new Map;for(const h of a){const u=c.get(h.locationName)??[];u.push(h),c.set(h.locationName,u)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Ue,{text:ie()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const u=i.get(h.locationName)??null,m=d.get(h.locationName)??null,b=c.get(h.locationName)??[],g=r===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ce,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ce,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:El(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(yx,{location:h})}),e.jsx("td",{children:e.jsx(bx,{lodging:u})}),e.jsx("td",{children:e.jsx(jx,{place:m,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(wx,{actions:b})}),e.jsx("td",{className:"text-right",children:e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:()=>o(h.locationName),children:g?"Hide":"Details"})})]}),g&&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(Cx,{location:h,lodging:u,place:m,placeActions:b})})})]},h.id)})})]})})]})}function fx(t){return[{label:"Description",tone:hn(t.description)?"positive":"neutral",value:hn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:hn(t.primaryPhone)?"positive":"neutral",value:hn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:hn(t.websiteUri)?"positive":"neutral",value:hn(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 yx({location:t}){const s=fx(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ce,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function bx({lodging:t}){return e.jsx(ri,{...vx(t)})}function vx(t){return t?t.populatedGroupCount===0?{tone:"neutral",label:"0 groups returned",detail:"Lodging API returned no readable groups; verify Hotel details."}:{tone:"positive",label:`${t.populatedGroupCount} group${t.populatedGroupCount===1?"":"s"} returned`,detail:"Owner lodging attributes."}:{tone:"neutral",label:"No Lodging API snapshot",detail:"Not returned for this scoped location."}}function jx({place:t,mapsUri:s}){return e.jsx(ri,{...Nx(t,s)})}function Nx(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 wx({actions:t}){return e.jsx(ri,{...Sx(t)})}function Sx(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 ri({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ce,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Cx({location:t,lodging:s,place:n,placeActions:a}){const r=s?Rx(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(qt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(qt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(qt,{label:"Description",value:hn(t.description)?t.description:"Not returned"}),e.jsx(qt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(qt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(qt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(qt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(qt,{label:"Open status",value:El(t.openStatus)}),e.jsx(qt,{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(qt,{label:"Last checked",value:eo(s.syncedAt)}),e.jsx(qt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(qt,{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(qt,{label:"Places tier",value:n.tier}),e.jsx(qt,{label:"Last checked",value:eo(n.syncedAt)}),e.jsx(qt,{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:[Ka(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Ka(o.providerType),o.uri?` · ${Px(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 qt({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 Bn(t,s,n){return t===s?"positive":t===0?n:"caution"}function kx(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Ax(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function hn(t){return typeof t=="string"&&t.trim().length>0}function El(t){return t?Ka(t):"Not returned"}function Ka(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Px(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function eo(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Rx(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Ix(n)).map(([s])=>Ka(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Ix(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Tx({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=nd.filter(f=>(a[f]??0)>0),o=ad.filter(f=>(a[f]??0)>0),i=Object.keys(a).filter(f=>(a[f]??0)>0&&rd(f)==="other").sort((f,x)=>(a[x]??0)-(a[f]??0)),d=Object.keys(a).filter(f=>(a[f]??0)===0).sort(),c=n.map(f=>{const x={date:f.date};for(const[y,P]of Object.entries(f.metrics))x[y]=P;return x}),h=n.find(f=>f.pending)?.date,u=n.length>0?n[n.length-1].date:void 0,m=c.length>0,b=s.dataThroughDate?`Data through ${Ft(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,g=[...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})]}),!m||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(to,{data:c,metrics:r,kind:"line",firstPending:h,lastDate:u}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:g.map(f=>e.jsxs("span",{className:"text-sm text-secondary",children:[Da(f)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[f]??0).toLocaleString()})]},f))})]})]}),m&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(to,{data:c,metrics:o,kind:"area",firstPending:h,lastDate:u})]}),d.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",d.map(f=>Da(f)).join(", ")]})]})}function to({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Js,{width:"100%",height:"100%",children:e.jsxs(Xs,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(sa,{stroke:ta,vertical:!1}),e.jsx(Zs,{dataKey:"date",tick:$t,tickLine:!1,axisLine:{stroke:cs},tickFormatter:bn,minTickGap:24}),e.jsx(en,{tick:$t,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(tn,{...es,labelFormatter:Ft,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),Da(String(i??""))]}),e.jsx(Ga,{wrapperStyle:{fontSize:11,color:ds.text},formatter:o=>Da(o)}),a&&r&&e.jsx(Fr,{x1:a,x2:r,fill:ds.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:ds.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(Rs,{type:"monotone",dataKey:o,stroke:at[i%at.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Us,{type:"monotone",dataKey:o,stackId:"reach",stroke:at[i%at.length],fill:at[i%at.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function $x(t){return Nl(Ms(String(t)))}function Mx(t){return Qs(Ms(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(Bm,{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 ja=Cs;function Nn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function gr(t){return t.toLocaleString()}function Lx(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function qx(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 Ex(t){const s=t.filter(n=>n.kind===Ws["backlink-extract"]&&!il(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Dx(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 Ox({projectName:t}){const s=Is(),[n,a]=l.useState(null),[r,o]=l.useState(null),[i,d]=l.useState([]),[c,h]=l.useState(null),[u,m]=l.useState(null),[b,g]=l.useState(null),[f,x]=l.useState(Date.now()),[y,P]=l.useState(0),[S,q]=l.useState(!0),[T,v]=l.useState(!1),[j,N]=l.useState(null),k=l.useCallback(async()=>{q(!0),N(null);try{const[A,ee,_,B,w]=await Promise.all([id().catch(()=>null),od(t,{excludeCrawlers:!0}).catch(()=>null),ld(t,{limit:ja,offset:y,excludeCrawlers:!0}).catch(se=>{if(se instanceof fn&&se.code==="NOT_FOUND")return null;throw se}),cd(t).catch(()=>[]),dd(t).catch(()=>[])]);h(A),a(ee),o(_),d(B);const H=Ex(w);m(H)}catch(A){N(A instanceof Error?A.message:"Failed to load backlinks")}finally{q(!1)}},[t,y]);l.useEffect(()=>{k()},[k]),l.useEffect(()=>{if(!u)return;const A=u.id;let ee=!1;const _=async()=>{try{const w=await Or(A);if(ee)return;il(w.status)?(m(null),g(w),await k()):m(H=>H?.id===w.id?{...H,...w}:H)}catch{}},B=window.setInterval(()=>{_()},3e3);return()=>{ee=!0,window.clearInterval(B)}},[u,k]),l.useEffect(()=>{if(!u)return;const A=window.setInterval(()=>x(Date.now()),1e3);return()=>window.clearInterval(A)},[u]),l.useEffect(()=>{if(!b||b.status==="failed")return;const A=window.setTimeout(()=>g(null),1e4);return()=>window.clearTimeout(A)},[b]);async function E(){v(!0),N(null);try{const A=await md(t);m(A)}catch(A){A instanceof fn&&A.code==="MISSING_DEPENDENCY"?N("DuckDB is not installed. Visit the Backlinks admin page to install it."):N(A instanceof Error?A.message:"Failed to trigger extract")}finally{v(!1)}}const O=l.useMemo(()=>i.slice().sort((A,ee)=>A.queriedAt.localeCompare(ee.queriedAt)).map(A=>({date:A.queriedAt,linkingDomains:A.totalLinkingDomains})),[i]),Z=r?.rows??[],U=r?.total??0,F=n?.excludedLinkingDomains??0,z=Math.floor(y/ja)+1;return l.useEffect(()=>{y>0&&y>=U&&P(0)},[y,U]),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"})]})}),j&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:j})}),u&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Km,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(ce,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Dx(u.startedAt??null,u.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",f]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),b&&!u&&e.jsx(pe,{className:`surface-card p-4 mb-4 ${b.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[b.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(_m,{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 ${b.status==="failed"?"text-negative":"text-positive"}`,children:b.status==="failed"?"Extract failed":"Extract complete"}),b.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:ud(b.error)}):b.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),V()]});function V(){return S?e.jsx(pe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):te()}function te(){const A=n!==null&&n.totalLinkingDomains>0,ee=b?.status==="failed",_=n!==null&&n.totalLinkingDomains===0&&!ee,B=c?.status==="ready",w=c?.status==="failed",H=c&&(c.status==="downloading"||c.status==="querying"||c.status==="queued");return A?Y(e.jsxs(e.Fragment,{children:[!ie()&&!s&&e.jsxs(e.Fragment,{children:[e.jsxs(I,{type:"button",variant:"outline",size:"sm",disabled:T||u!==null,onClick:He(E),children:[e.jsx(fl,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":T?"Queuing…":"Re-run extract"]}),e.jsx(pr,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ie()&&!s&&e.jsx(I,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"Open admin"})})]})):e.jsx(pe,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Um,{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."}),!ie()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(I,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"Set up backlinks"})})})]}),H&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",c.status,c.phaseDetail?` — ${c.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!ie()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(I,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"View sync status"})})})]}),w&&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."}),!ie()&&!s&&e.jsx("div",{className:"mt-4",children:e.jsx(I,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"Go to Backlinks admin"})})})]}),B&&!H&&!_&&!ee&&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."]}),!ie()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(I,{type:"button",size:"sm",disabled:T||u!==null,onClick:He(E),children:[e.jsx(Fa,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":T?"Queuing…":"Run extract"]}),e.jsx(pr,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),ee&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!ie()&&!s&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(I,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"Go to Backlinks admin"})})})]}),_&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",n.targetDomain,". Try a newer release or re-run this extract."]}),!ie()&&!s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(I,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(I,{type:"button",variant:"outline",size:"sm",disabled:T||u!==null,onClick:He(E),children:[e.jsx(Fa,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":T?"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:n.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function Y(A){if(!n)return null;const ee="Linking hosts",_="linking hosts",B="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(n.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",n.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",_]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:gr(n.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",_," 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:Lx(n.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",_," 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"})," · ",B," ",e.jsx("code",{className:"text-secondary",children:n.release})," · queried ",qx(n.queriedAt),F>0&&e.jsxs(e.Fragment,{children:[" · ",F," excluded domain",F===1?"":"s"]})]}),O.length>=2&&e.jsxs(pe,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Js,{width:"100%",height:"100%",children:e.jsxs(Xs,{data:O,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:at[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:at[0],stopOpacity:0})]})}),e.jsx(Zs,{dataKey:"date",tick:$t,stroke:cs,tickFormatter:$x}),e.jsx(en,{tick:$t,stroke:cs,allowDecimals:!1}),e.jsx(tn,{contentStyle:es.contentStyle,labelStyle:es.labelStyle,itemStyle:es.itemStyle,labelFormatter:Mx}),e.jsx(Us,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:at[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(pe,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:ee})]})}),e.jsxs("tbody",{children:[Z.map(w=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:w.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:gr(w.numHosts)})]},w.linkingDomain)),Z.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:F>0&&U===0?`Every referring domain in this ${B} was a crawler/proxy host (${F} hidden).`:`No referring domains in this ${B}.`})})]})]})}),e.jsx(Ts,{page:z,pageSize:ja,visibleRows:Z.length,totalRows:U,onPageChange:w=>P((w-1)*ja)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:A})]})}}function Fx({projectName:t}){const s=Ie({...hd({client:Q,path:{name:t}}),staleTime:ai}),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:Zn(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:Ot()?"text-sm text-secondary":"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":Ot()?Ys:"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(Ue,{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(Ue,{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(Gx,{data:n}),e.jsx(Kx,{data:n}),n.competitorGaps.length>0&&e.jsx(Vx,{data:n})]})}function Gx({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(Na,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Na,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Na,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(Na,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function Na({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 Kx({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(_x,{}),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(Tn,{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(yl,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Ux,{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 _x(){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(kn,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(kn,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(kn,{active:!1,tone:"cited"}),e.jsx(kn,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Ux({provider:t}){const s=Bx(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(kn,{active:t.cited,tone:"cited"}),e.jsx(kn,{active:t.mentioned,tone:"mentioned"})]})}function Bx(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 kn({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 Vx({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(Ue,{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(Tn,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const ra="__cited__",ia="__mentioned__",ls="__mentionShare__";function Dl(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Ms(n),end:Ms(a),sweepCount:s.sweepCount??1}}function _a(t){const s=Dl(t);if(!s)return"Sweep date unavailable";const n=Qs(s.start),a=Qs(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function zx(t){const s=Dl(t);return s?Nl(s.start):""}function Ln(t){return t.trim().toLowerCase()}function Vr(t){return Math.round(t*1e3)/10}function zr(t){return t.byProvider??{}}function Qx(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const c=s==="cited"?ra:ia,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(m=>({date:m.startDate,[c]:Vr(m[h])})),series:[c],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(c=>Object.keys(zr(c))))].sort();return{rows:t.buckets.map(c=>{const h={date:c.startDate},u=zr(c);for(const m of i){const b=u[m];h[m]=b?Vr(b[o]):null}return h}),series:i,hasData:a,singleBucket:r}}function Ol(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Hx(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Wx(t){return t.servedModelAttribution??{}}function Yx(t){return t.modelServiceMismatch??{}}function Jx(t){return t.modelPointerChanges??{}}function Xx(t){return t.length>0?t.join(", "):null}function so(t,s){const n=Ln(s);return Object.entries(t).find(([a])=>Ln(a)===n)?.[1]}function ks(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 Zx(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!so(zr(a),s))continue;const r=Ol(a);return r?so(r,s)??null:null}return null}function ep(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 tp(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:ep(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function sp(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 np(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 ap(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[ls]:r?.rate==null?null:Vr(r.rate)}}),n=s.map(a=>a[ls]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[ls],hasData:n.length>0,singleBucket:n.length===1}}function rp(t,s,n){return s==="mentionShare"?ap(t):Qx(t,s,n)}function no(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 ao(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function ro(t){return t>0?`+${t}`:`${t}`}function ip(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${ro(n.delta)} on ${ao(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${ro(s.delta)} on ${ao(s.date)})`}const op=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],io="Measured answers",lp="Close answers",As={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},An="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",Qr=new Intl.NumberFormat("en",{style:"percent",maximumFractionDigits:1});function cp(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function Ns({value:t,unit:s}){return t.rate===null?e.jsx("span",{className:"text-sm text-secondary",children:t.reason==="identity-ambiguous"?Rt.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:Qr.format(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator,s?` ${s}`:""]})]})}const dp={otherQueries:"Other queries"};function up(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(" · ")||dp.otherQueries}return a.sort((r,o)=>r.marketLabel.localeCompare(o.marketLabel)||r.query.localeCompare(o.query))}function oo({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(Vm,{size:16,"aria-hidden":"true"}):e.jsx(yl,{size:16,"aria-hidden":"true"}),n?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Ns,{value:t}),t.reason==="evidence-incomplete"?e.jsx(Ue,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function lo({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 mp({group:t,advanced:s,targetLabels:n,marketHeading:a,onViewAnswers:r}){const o=t.rows[0],i=u=>JSON.stringify([...u.targetKeys].sort()),d=t.rows.every(u=>i(u)===i(o)),c=t.rows.every(u=>u.location===o.location),h=u=>u===null?"No location targeting":`Search location: ${u}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[a?e.jsx("tr",{children:e.jsx("th",{colSpan:4,className:"border-t border-default py-4 text-left",children:e.jsx("h3",{className:"text-base font-semibold text-heading",children:a})})}):null,e.jsx("tr",{className:"measurement-result-heading",children:e.jsxs("th",{scope:"rowgroup",colSpan:4,children:[e.jsx("h3",{className:"break-words text-base font-medium text-heading",children:t.query}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 text-sm font-normal text-secondary",children:[s&&d?e.jsx(lo,{targetKeys:o.targetKeys,labels:n}):null,c?e.jsx("span",{children:h(o.location)}):null]})]})}),t.rows.map(u=>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:ws(u.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:u.model??"Model not recorded"}),s&&!d?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(lo,{targetKeys:u.targetKeys,labels:n})}):null,c?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:h(u.location)})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(oo,{value:u.mentionCoverage,singleAnswer:u.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(oo,{value:u.citationCoverage,singleAnswer:u.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(I,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${u.query} · ${u.provider}`,onClick:m=>r(u,m.currentTarget),children:[u.answerCount===1?"View answer":"View answers",e.jsx(gl,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([u.provider,u.model,u.location])))]})}function hp({population:t}){const s=l.useId();let n=0;const a=t.trend.map((c,h)=>(h>0&&c.continuity.state!=="comparable"&&(n+=1),{createdAt:Date.parse(c.createdAt),[`mentioned-${n}`]:c.mentionCoverage.rate,[`cited-${n}`]:c.citationCoverage.rate})),r=Array.from({length:n+1},(c,h)=>h),o=new Set(t.trend.slice(1).map(c=>c.continuity.state)),i=[...a.length===1?["First measurement. A trend appears after another comparable run."]:[],...o.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...o.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...o.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(c=>c.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[]];if(a.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const d=t.trend.some(c=>c.mentionCoverage.rate!==null||c.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[d?e.jsxs(e.Fragment,{children:[e.jsxs("ul",{"aria-label":"Trend legend",className:"flex gap-5 py-3 text-sm text-secondary",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:at[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:$s.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":`${As[t.queryClass]} mention and citation trend`,children:e.jsx(Js,{width:"100%",height:"100%",children:e.jsxs(Xs,{data:a,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(sa,{stroke:ta,vertical:!1}),e.jsx(Zs,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:$t,tickLine:!1,axisLine:{stroke:cs},tickFormatter:c=>new Date(Number(c)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(en,{domain:[0,1],tick:$t,tickLine:!1,axisLine:!1,width:48,tickFormatter:c=>Qr.format(Number(c))}),e.jsx(tn,{...es,formatter:c=>typeof c=="number"?Qr.format(c):"Not measured",labelFormatter:c=>new Date(Number(c)).toLocaleDateString()}),r.map(c=>e.jsxs(l.Fragment,{children:[e.jsx(Rs,{type:"linear",dataKey:`mentioned-${c}`,name:"Mentioned",stroke:at[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}}),e.jsx(Rs,{type:"linear",dataKey:`cited-${c}`,name:"Cited",stroke:$s.positive,strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}})]},c))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:d?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${As[t.queryClass]} trend data`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"}),e.jsx("th",{children:"Comparison"})]})}),e.jsx("tbody",{children:t.trend.map(c=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(c.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(Ns,{value:c.mentionCoverage})}),e.jsx("td",{children:e.jsx(Ns,{value:c.citationCoverage})}),e.jsx("td",{children:c.continuity.state.replaceAll("-"," ")})]},c.runId))})]})})]})}function Hr(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function ii(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=Hr(a,s)??Hr(t,s),d=t.populations.find(h=>h.queryClass===i?.queryClass);if(d)return d;const c=["non-brand","branded","unknown"].map(h=>t.populations.find(u=>u.queryClass===h));return c.find(h=>h&&(h.summary.queryCount>0||h.trend.some(u=>u.queryCount>0)))??c.find(h=>h!==void 0)??t.populations[0]}function xp({report:t,onSelectionChange:s,queryClass:n=ii(t).queryClass}){const{selection:a,scopeOptions:r,filterOptions:o}=t,i=(d,c,h,u)=>e.jsxs("label",{className:"min-w-0",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:d}),e.jsx("select",{"aria-label":d,className:An,value:h,onChange:m=>s({[c]:m.target.value||void 0,measurementQueryKey:void 0}),children:u.map(m=>e.jsx("option",{value:m.value,children:m.label},m.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(Yo,{options:r,selected:a.scope,marketKey:a.market?.id,onSelect:(d,c)=>{s({measurementScope:d.kind,measurementScopeKey:d.kind==="project"?void 0:d.id,measurementMarketKey:c})}}):null,i("Query type","queryClass",n,[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"},{value:"unknown",label:"Unclassified"}]),i("Answer engine","measurementProvider",a.provider??"",[{value:"",label:"All engines"},...o.providers.map(d=>({value:d,label:d}))]),i("Search location","measurementLocation",a.location.kind==="exact"?a.location.value:a.location.kind==="none"?"none":"",[{value:"",label:"All locations"},...o.locations.filter(d=>d.kind!=="all").map(d=>({value:d.kind==="exact"?d.value:"none",label:d.kind==="exact"?d.value:"No location"}))])]})})}function pp({report:t,isRefreshing:s=!1,onSelectionChange:n,onManageQueries:a,onPage:r,onSearch:o,search:i="",queryKey:d,answerSelection:c,evidenceReport:h,isEvidenceLoading:u=!1,evidenceError:m,onRetryEvidence:b,onEvidencePage:g,renderPropertyLink:f}){const x=l.useRef(null),y=l.useRef(void 0),P=l.useRef(null),S=ii(t,d,c,h),q=h??t,T=q.populations.filter(A=>[...A.queries.items,...A.evidence.items].some(ee=>ee.queryKey===d)),v=c?[c.queryClass]:(T.length?T:u?[]:[S]).map(A=>A.queryClass),j=d?JSON.stringify([c??d,v]):void 0,N=l.useId();l.useEffect(()=>{if(!j){s||(y.current=void 0);return}if(y.current===j)return;const A=x.current?.querySelectorAll(`[aria-label="${io}"]`);if(A?.length){for(const ee of A){const _=ee.closest("details[data-query-results]");_&&(_.open=!0)}A[0].focus({preventScroll:!0}),A[0].scrollIntoView?.({block:"start"}),y.current=j}},[j,s]);const{selection:k,filterOptions:E}=t,O=k.measurement,Z=cp(k.scope),U=new Map(t.scopeOptions.filter(A=>A.kind==="property").map(A=>[A.id,A.label])),F=A=>{const ee=q.populations.find(_=>_.queryClass===A.queryClass)?.evidence;return{items:ee?.items.filter(_=>_.queryKey===d&&(!c||_.provider===c.provider&&_.model===c.model&&_.location===c.location&&(c.runId===null||_.runId===c.runId)))??[],nextCursor:ee?.nextCursor}},z=()=>{y.current=void 0;const A=P.current;A!==null&&A.row.queryKey===d&&(!c||A.row.provider===c.provider&&A.row.model===c.model&&A.row.location===c.location)&&A?.element.isConnected?A.element.focus():x.current?.querySelector(`details[data-query-results="${S.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})},V=(A,ee,_,B,w)=>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:`${N}-${ee}`,className:"text-sm font-medium text-heading",children:A}),e.jsx(Ue,{text:w})]}),e.jsx("select",{id:`${N}-${ee}`,className:An,value:_,onChange:H=>n({[ee]:H.target.value||void 0,measurementQueryKey:void 0}),children:B.map(H=>e.jsx("option",{value:H.value,children:H.label},H.value))})]}),te=a?e.jsx(I,{variant:"outline",onClick:a,children:"Manage queries"}):null,Y=k.mode==="advanced"&&k.scope.kind==="property"?f?.({id:k.scope.id,label:k.scope.label}):null;return e.jsxs("section",{ref:x,className:"visibility-report","aria-label":"AI visibility results",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default pb-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(ce,{tone:O.state==="measured"?"positive":"neutral",children:O.state==="measured"?"Complete":O.state==="partial"?"Partial":"Not measured"}),O.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:new Date(O.completedAt).toLocaleDateString()}):null]}),Y?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[Y,te]}):te]}),k.provenance.kind==="legacy-simple"&&k.queryClass!=="unknown"&&k.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(I,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,e.jsx(xp,{report:t,queryClass:S.queryClass,onSelectionChange:n}),e.jsxs("details",{className:"border-b border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"More filters"}),e.jsxs("div",{className:"flex flex-wrap gap-4 pb-3",children:[e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:"Start date (UTC)"}),e.jsx("input",{type:"date",className:An,value:k.time.from?.slice(0,10)??"",onChange:A=>n({measurementFrom:A.target.value?`${A.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:An,value:k.time.to?.slice(0,10)??"",onChange:A=>n({measurementTo:A.target.value?`${A.target.value}T23:59:59.999Z`:void 0})})]}),V("AI model","measurementModel",k.model??"",[{value:"",label:"All models"},...Array.from(new Set(E.models.filter(A=>!k.provider||A.provider===k.provider).map(A=>A.model))).map(A=>({value:A,label:A}))],"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),V("Results from","measurementRunId",k.run.explicit?k.run.id??"":"",[{value:"",label:"Latest saved sweep"},...[...S.trend].reverse().map(A=>({value:A.runId,label:new Date(A.createdAt).toLocaleString()}))],"Choose a saved AI sweep to view its results. No new sweep starts.")]})]}),[S].map(A=>{const ee=up(A.queries.items,k.scope.kind==="property"&&!k.market&&A.queryClass==="non-brand"?new Map(t.scopeOptions.filter(w=>w.kind==="market").map(w=>[w.id,w.label])):void 0),_=F(A),B=_.items[0]?.query??A.queries.items.find(w=>w.queryKey===d)?.query;return e.jsxs("section",{"aria-label":As[A.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h2",{children:As[A.queryClass]}),e.jsx(Ue,{text:A.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":A.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:k.mode==="advanced"&&k.scope.kind!=="property"?"Answers mentioning a property":"Mentioned answers"}),k.mode==="advanced"?e.jsx(Ue,{text:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned."}):null]}),e.jsx(Ns,{value:A.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:k.mode==="advanced"&&k.scope.kind!=="property"?"Answers citing a property":"Cited answers"}),k.mode==="advanced"?e.jsx(Ue,{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(Ns,{value:A.summary.citationCoverage,unit:"answers"})]}),k.mode==="advanced"&&k.scope.kind!=="property"?e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Properties mentioned"}),e.jsx(Ns,{value:A.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:A.summary.queryCount})]})]}),e.jsx(hp,{population:A}),k.mode==="advanced"?e.jsxs("details",{className:"border-t border-default text-sm text-secondary","aria-label":`${As[A.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(([w,H])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:A.summary.outcomes[w]}),e.jsx("span",{className:"text-sm text-secondary",children:H}),w==="notMeasured"?e.jsx(Ue,{text:"No eligible completed measurement for this selection. This is not the same as a measured answer with neither signal."}):null]},w))})]}):null,k.mode==="advanced"&&k.scope.kind!=="property"&&(A.breakdown.groups.length>0||A.breakdown.properties.length>0)?e.jsx(gp,{population:A,scope:k.scope,scopeOptions:t.scopeOptions,marketKey:k.market?.id,onSelectionChange:n},`${k.scope.kind}:${k.scope.id}`):null,e.jsxs("details",{className:"border-t border-default","data-query-results":A.queryClass,"aria-label":`${As[A.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:[A.queries.total," ",A.queries.total===1?"result":"results"," · ",Z]})]}),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 ${As[A.queryClass]}`,placeholder:"Search queries",className:`${An} max-w-sm`,value:i,onChange:w=>o(w.target.value)}):null,e.jsx(Ue,{text:k.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":`${As[A.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"})})]})}),ee.map((w,H)=>e.jsx(mp,{group:w,marketHeading:w.marketLabel!==ee[H-1]?.marketLabel?w.marketLabel:void 0,advanced:k.mode==="advanced",targetLabels:U,onViewAnswers:(se,oe)=>{P.current={row:se,element:oe},n({measurementQueryKey:se.queryKey,measurementAnswer:JSON.stringify({queryKey:se.queryKey,queryClass:A.queryClass,provider:se.provider,model:se.model,location:se.location,runId:k.run.id,revision:k.revision})})}},w.queryKey))]})}),A.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:[ee.length," ",ee.length===1?"query":"queries"," · ",A.queries.items.length," ",A.queries.items.length===1?"engine result":"engine results"," shown of ",A.queries.total," results"]}),A.queries.nextCursor&&r?e.jsx(I,{variant:"outline",onClick:()=>r(A.queries.nextCursor),children:"Next queries"}):null,d&&v.includes(A.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":io,"aria-busy":u,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("h3",{className:"min-w-0 flex-1 text-base font-semibold text-heading [overflow-wrap:anywhere]",children:B??"Answers"}),e.jsx(I,{variant:"ghost",className:"min-h-11",onClick:z,children:lp})]}),u?e.jsx("p",{role:"status",className:"py-4 text-sm text-secondary",children:"Loading saved answers…"}):m?e.jsxs("div",{role:"alert",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["Saved answers unavailable: ",m]}),b?e.jsx(I,{variant:"outline",onClick:b,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[_.items.map(w=>e.jsxs("article",{className:"border-b border-default py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsx("strong",{className:"text-sm text-heading",children:w.provider}),w.model?e.jsx("span",{className:"text-[13px] text-secondary",children:w.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:w.location??"No location"}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(w.createdAt).toLocaleDateString()}),e.jsx(ce,{tone:"neutral",children:w.mentioned===null?w.mentionUnavailableReason==="identity-ambiguous"?Rt.ambiguous:"Mention not checked":w.mentioned?"Mentioned":"Not mentioned"}),e.jsx(ce,{tone:"neutral",children:w.cited===null?"Citation not checked":w.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Wo,{headingLevel:4,copyable:!!w.answerText?.trim(),children:w.answerText??"Answer text unavailable."})}),w.sources.length>0?e.jsxs("details",{className:"mt-2","data-answer-sources":!0,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[uc," (",w.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:w.sources.map(H=>{const se=Ks(H);return e.jsx("li",{className:"break-all text-sm",children:se?e.jsx("a",{href:se,target:"_blank",rel:"noopener noreferrer",className:"text-link underline",children:H}):e.jsx("span",{className:"text-secondary",children:H})},H)})})]}):null]},w.answerId)),F(A).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:F(A).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,F(A).nextCursor&&g?e.jsx(I,{variant:"outline",onClick:()=>g(F(A).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"border-t border-default","aria-label":`${As[A.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:A.competitorAvailability.state==="unavailable"?"Not available":`${A.competitors.length} measured`})]}),e.jsxs("div",{className:"pb-5",children:[A.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):A.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:A.competitors.map(w=>e.jsxs("tr",{children:[e.jsx("td",{children:w.domain}),e.jsx("td",{children:e.jsx(Ns,{value:w.mentionCoverage})}),e.jsx("td",{children:e.jsx(Ns,{value:w.citationCoverage})})]},w.domain))})]})}),A.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:A.observedCompetitors.map(w=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:w.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[w.answerCount," ",w.answerCount===1?"answer":"answers"]})]},w.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},A.queryClass)})]})}function gp({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const o=new Map(n.filter(m=>m.kind==="group").map(m=>[m.id,m])),i=[...o.values()].some(m=>m.parentGroupIds?.length),d=t.breakdown.groups.filter(m=>{const b=o.get(m.id)?.parentGroupIds??[];return s.kind==="project"?b.length===0:s.kind==="group"&&i?b.includes(s.id):!0}),[c,h]=l.useState(()=>s.kind==="project"&&d.length>0?"groups":"properties"),u=yn({rows:c==="groups"?d:t.breakdown.properties,getSearchText:m=>m.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(m=>e.jsx(I,{variant:c===m?"secondary":"ghost",onClick:()=>{h(m),u.setPage(1)},children:m==="groups"?"Groups":"Properties"},m))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:u.query,onChange:m=>u.setQuery(m.target.value),className:`${An} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:c==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:u.rows.map(m=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("button",{className:"min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>r({measurementScope:c==="groups"?"group":"property",measurementScopeKey:m.id,measurementMarketKey:a}),children:m.label})}),e.jsx("td",{children:m.queryCount}),e.jsx("td",{children:e.jsx(Ns,{value:m.mentionCoverage})}),e.jsx("td",{children:e.jsx(Ns,{value:m.citationCoverage})})]},m.id))})]})}),u.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",c," match this search."]}):null,e.jsx(Ts,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:c,onPageChange:u.setPage})]})}function fp({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,renderPropertyLink:r,fallback:o,showUnmeasuredFallback:i=!1}){const[d,c]=l.useState(),[h,u]=l.useState(""),[m,b]=l.useState(),g=us(),f=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=Ie({...tr({client:Q,path:{name:t},query:{...f,limit:25,cursor:d,search:h||void 0}}),staleTime:gd,retry:!1,placeholderData:si}),y={...f,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},P=JSON.stringify(y),S=Ie({...tr({client:Q,path:{name:t},query:{...y,cursor:m?.selection===P?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&&!Hr(x.data,s.queryKey)&&!S.data)return;const q=ii(x.data,s.queryKey,s.answer,S.data);if(!d&&!h){const{queryKey:T}=tr({client:Q,path:{name:t},query:{...f,queryClass:q.queryClass,limit:25}});g.setQueryData(T,{...x.data,selection:{...x.data.selection,queryClass:q.queryClass},populations:[q]},{updatedAt:x.dataUpdatedAt})}n({queryClass:q.queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}})},[s.queryClass,s.queryKey,s.answer,x.data,x.dataUpdatedAt,x.isPlaceholderData,x.isFetching,x.isError,S.data,n,g,t,f,d,h]),x.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:o});if(i&&x.data?.selection.mode==="simple"&&x.data.selection.measurement.state==="not-measured")return e.jsx(e.Fragment,{children:o});if(x.error){const q=Zn(x.error),T=s.measurementScope!=="project"&&q.includes("scope")&&q.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:T?"This saved group or property filter is unavailable for this measurement. Show the whole site to choose another.":q}),T?e.jsx(I,{variant:"outline",onClick:()=>{c(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:"Show whole site"}):e.jsx(I,{variant:"outline",onClick:()=>{c(void 0),x.refetch()},children:"Retry"})]})}return x.data?e.jsx("div",{"aria-busy":x.isFetching,children:e.jsx(pp,{report:x.data,isRefreshing:x.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:S.data,isEvidenceLoading:S.isFetching||!!s.queryKey&&S.isPending,evidenceError:S.error?Zn(S.error):void 0,onRetryEvidence:()=>{S.refetch()},onEvidencePage:S.isFetching?void 0:q=>b({selection:P,cursor:q}),search:h,onSearch:q=>{u(q),c(void 0)},onPage:x.isFetching?void 0:c,onSelectionChange:q=>{(!("measurementQueryKey"in q)||Object.keys(q).some(T=>T!=="measurementQueryKey"&&T!=="measurementAnswer"))&&c(void 0),b(void 0),n(q)},onManageQueries:a,renderPropertyLink:r})}):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 yp=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],bp=[{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."}],oi=at[2],vp="var(--chart-tooltip-bg)",jp={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function ws(t){const s=Ln(t);return jp[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Bs(t){return Math.round(t*10)/10}function Np(t){return t===ra||t===ia||t===ls}function Fl(t){return t===ra?"Cited":t===ia?"Mentioned":t===ls?"Mention share":ws(t)}function Qn(t,s){return t===ra?$s.positive:t===ia?at[1]:t===ls?oi:Jm(Ln(t),s)}function wp(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Sp(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
|
-
`)}function Qa(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function La(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${Qa(s)}`:"Mention share":"Mentioned"}function na(t){return t==="cited"?"citationRate":"mentionRate"}function Gl(t,s){return s==="cited"?t.cited:t.mentionedCount}function Kl(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 _l(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Wr(t){const s=Ol(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>Ln(a).localeCompare(Ln(r))).map(([a,r])=>`${ws(a)}: ${ks(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function Cp(t){return t.some(({event:s})=>s.to.status==="mixed")?$s.caution:t.some(({event:s})=>s.to.status==="unknown")?$s.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?at[4]:$s.positive}function kp(t,s,n){const a=_l(t,s);return a?_a(a):Qs(Ms(n))}function Ap({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:o,mismatch:i,buckets:d}){const c=l.useId(),h=Object.entries(o).sort(([m],[b])=>m.localeCompare(b)),u=t.buckets.length>0||t.beforeWindow.length>0;return!s||!u?null:e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":c,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:c,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:m,events:b})=>b.map(({provider:g,event:f})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:kp(d,m,f.observedAt)}),e.jsxs("span",{children:[ws(g),": ",ks(f.from)," → ",ks(f.to)]})]},`${g}-${f.observedAt}-${f.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:m,event:b})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Qs(Ms(b.observedAt))]}),e.jsxs("span",{children:[ws(m),": ",ks(b.from)," → ",ks(b.to),b.anchorObservedAt?` (last seen ${ks(b.from)} on ${Qs(Ms(b.anchorObservedAt))})`:""]})]},`before-${m}-${b.observedAt}`))})]}),a.map(m=>e.jsxs("p",{className:"trend-model-evidence-note",children:[ws(m.provider),": showing the most recent ",m.shown," of ",m.total," changes."]},`truncated-${m.provider}`)),r.map(m=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",ws(m)," change."]},`incomplete-${m}`)),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(([m,b])=>{const g=Xx(b.latestServedModelIds),f=i[m];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Qs(Ms(b.latestObservation.observedAt))}),e.jsxs("span",{children:[ws(m),": ",g??ks(b.latestObservation.state),f?` — not the ${ks(f.configured)} you selected`:""]})]},`served-${m}`)})})]})]})}function co(t){return t===null?"no data":`${t}%`}function fr(t){return t==null?"undefined":`${Bs(t*100)}%`}function Pp({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=_l(o,s);if(!i)return null;if(a==="mentionShare"){const c=i.mentionShare.projectMentionSnapshots,h=i.mentionShare.competitorMentionSnapshots,u=c+h,m=i.mentionShare.rate==null?null:Bs(i.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:_a(i)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:oi},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",Qa(i.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:co(m)})]}),u>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",c," / ",u," 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:Wr(i)})]})}const d=r==="byProvider"?(n??[]).filter(c=>c.dataKey!==void 0):[{dataKey:a==="cited"?ra:ia,value:Bs(i[na(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:_a(i)}),d.map((c,h)=>{const u=String(c.dataKey??c.name??""),m=r==="byProvider"?Kl(i,u,a):null,b=m?.count??Gl(i,a),g=m?.total??i.total,f=typeof c.value=="number"?c.value:Bs(m?m.rate*100:i[na(a)]*100),x=c.color??Qn(u,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:x},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Fl(u)}),e.jsx("span",{className:"trend-tooltip-value",children:co(f)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[b," / ",g," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${u}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:Wr(i)})]})}function Rp({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:[La(s,r)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(o=>{let i;if(s==="mentionShare"){const d=o.mentionShare.projectMentionSnapshots,c=o.mentionShare.competitorMentionSnapshots,h=d+c,u=Qa(o.mentionShare.scope);i=h>0?`${fr(o.mentionShare.rate)} mention share for ${u}, ${d} of ${h} brand mentions were you`:`mention share undefined for ${u}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(d=>{const c=Kl(o,d,s);return c?`${ws(d)} ${fr(c.rate)} ${La(s).toLowerCase()}, ${c.count} of ${c.total} snapshots`:`${ws(d)} no data`}).join("; "):i=`${fr(o[na(s)])} ${La(s).toLowerCase()}, ${Gl(o,s)} of ${o.total} snapshots`;return i+=`; ${Wr(o)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:_a(o)}),e.jsx("td",{children:i})]},o.startDate)})})]})}function yr({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const o=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(i=>{const d=s===i.value,c=i.description?`${o}-${i.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":d,"aria-describedby":c,className:`segmented-option ${d?"segmented-option-active":""}`,onClick:()=>n(i.value),children:i.label}),i.description&&e.jsx("span",{id:c,className:"sr-only",children:i.description})]},i.value)})})}function Ip({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[o,i]=l.useState("mentioned"),[d,c]=l.useState("byProvider"),h=l.useMemo(()=>Sp(s),[s]),u=Ie({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>xd(t,a),staleTime:ai}),m=u.data??null,b=u.error,g=o==="mentionShare"?"overall":d,f=l.useMemo(()=>m?rp(m,o,g):null,[m,o,g]),x=m?Hx(m):null,y=l.useMemo(()=>tp(x??{}),[x]),P=l.useMemo(()=>sp(x??{}),[x]),S=l.useMemo(()=>np(x??{}),[x]),q=l.useMemo(()=>Object.entries(x??{}).filter(([,B])=>B.anchorUnavailable).map(([B])=>B).sort(),[x]),T=l.useMemo(()=>m?Wx(m):{},[m]),v=l.useMemo(()=>m?Yx(m):{},[m]),j=l.useMemo(()=>m?pd(Jx(m)):null,[m]),N=o!=="mentionShare"&&g==="byProvider",k=m?.buckets??[],E=k[k.length-1]?.mentionShare.scope??m?.mentionShareScope??"pooled",O=La(o,E),Z=o==="cited"?$s.positive:o==="mentionShare"?oi:at[1],U=N?ds.textDim:Z,F=l.useMemo(()=>{const B=new Map(k.map(w=>[w.startDate,zx(w)]));return w=>B.get(String(w))??""},[k]),z=o==="mentionShare"?f?no(f.rows,ls):null:k.length>0?Bs(k[k.length-1][na(o)]*100):null,V=o==="mentionShare"?f?wp(f.rows,ls):null:k.length>0?Bs(k[0][na(o)]*100):null,te=o==="mentionShare"?f?.rows.filter(B=>typeof B[ls]=="number").length??0:k.length,Y=z!==null&&V!==null&&te>1?Bs(z-V):null,A=s.length,ee=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(Ue,{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."})]})]}),z!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:U},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:O}),N&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[z,"%"]}),Y!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${Y>0?"text-positive-400":Y<0?"text-negative-400":"text-muted"}`,children:[Y>0?"+":"",Y.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(yr,{options:bp,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(yr,{options:yp,value:d,onChange:c,ariaLabel:"Series"}),e.jsx(yr,{options:op,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let _;if(b)_=e.jsx("p",{className:"text-sm text-negative-400",children:Zn(b)});else if(u.isLoading&&!m)_=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(o==="mentionShare"&&A===0)_=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!m||!f)_=null;else{const{rows:B,series:w,hasData:H}=f,se=ip(m.queryChanges);if(!H)_=e.jsx("p",{className:"text-sm text-secondary",children:o==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${Qa(E)} in this window yet.`:Ot()?Ys:"Run a sweep to start tracking citations and mentions over time."});else if(N&&w.length===0)_=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 oe=`${O} rate across ${B.length} ${B.length===1?"sweep":"sweeps"}. Latest ${z}%${Y!==null?`, ${Y>=0?"up":"down"} ${Math.abs(Y).toFixed(1)} points over the period`:""}.`;_=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:oe}),e.jsx(Rp,{buckets:k,metric:o,mode:g,series:w}),N&&w.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:w.map((ne,ye)=>{const W=no(B,ne),ue=Zx(k,ne),ve=x===null?"Attribution unavailable":ue?ks(ue):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:Qn(ne,ye)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:Fl(ne)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),ve]})]}),W!==null&&e.jsxs("span",{className:"trend-legend-value",children:[W,"%"]})]},ne)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${O} trend chart over ${B.length} ${B.length===1?"bucket":"buckets"}`,children:e.jsx(Js,{width:"100%",height:"100%",children:e.jsxs(Xs,{data:B,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(sa,{stroke:ta,vertical:!1}),e.jsx(Zs,{dataKey:"date",tick:$t,tickLine:!1,axisLine:{stroke:cs},tickFormatter:F,minTickGap:24}),e.jsx(en,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:ne=>`${ne}%`,tick:$t,tickLine:!1,axisLine:!1,width:40}),e.jsx(tn,{cursor:{stroke:cs,strokeWidth:1},content:e.jsx(Pp,{metric:o,mode:g,buckets:k})}),y.buckets.map(({bucketStartDate:ne,events:ye})=>e.jsx(nh,{x:ne,stroke:Cp(ye),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${ne}`)),w.map((ne,ye)=>e.jsx(Rs,{type:"monotone",dataKey:ne,name:ne,stroke:Qn(ne,ye),strokeDasharray:ne===ls?"5 4":void 0,strokeWidth:Np(ne)?2.5:2,dot:ne===ls?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:Qn(ne,ye),strokeWidth:1.5}:{r:2.5,fill:Qn(ne,ye),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:vp},connectNulls:ne!==ls,isAnimationActive:!1},ne))]})})}),e.jsx(Ap,{partition:y,available:x!==null,counts:P,truncated:S,incompleteHistory:q,served:T,mismatch:v,buckets:k}),se&&e.jsx("p",{className:"visibility-trend-note",children:se})]})}}return e.jsxs("section",{className:"visibility-trend",children:[ee,_]})}const uo=new Set([Jn.queued,Jn.running]),Tt={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 mo({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:o,scopeError:i,onRetryScope:d,templates:c=[],viewerResearchConfig:h=null}){const u=us(),{account:m,canWrite:b}=vn(),g=m?.role==="viewer"&&h!==null,f=!b,x=Is(),[y,P]=l.useState(""),[S,q]=l.useState(""),[T,v]=l.useState(null),[j,N]=l.useState([]),k=l.useRef(null),E=l.useRef(!1),[O,Z]=l.useState(0),U=Ie({...fd({client:Q,path:{name:t}}),staleTime:6e4}),F=Ie({...yd({client:Q}),enabled:!f&&!x,staleTime:6e4}),z={client:Q,path:{name:t},query:{limit:20}},V=Ho({...bd(z),initialData:void 0,initialPageParam:z,getNextPageParam:K=>K.nextCursor?{path:z.path,query:{...z.query,cursor:K.nextCursor}}:void 0,refetchInterval:K=>K.state.data?.pages.some(xe=>xe.runs.some(we=>uo.has(we.status)))?3e3:!1}),te=V.isError&&!V.isFetchNextPageError,Y=V.data?.pages.at(-1),A=te?[]:[...new Map((V.data?.pages.flatMap(K=>K.runs)??[]).map(K=>[K.id,K])).values()],ee=Y?.access?.canRun??(b||g),_=Y?.access?Y.access.dailyRunLimit:g?h.viewerDailyRunLimit:null;l.useEffect(()=>{!T&&A[0]&&v(A[0].id)},[A,T]);const B=A.find(K=>K.id===T)??null,w=Ie({...vd({client:Q,path:{name:t,runId:T??""}}),enabled:!te&&!!T,refetchInterval:B&&uo.has(B.status)?3e3:!1}),H=te||w.isError?null:w.data??null,se=U.data?.locations??[],oe=l.useMemo(()=>{if(f)return(Y?.providers??[]).map(xe=>({...xe,catalog:xe}));const K=new Map((F.data?.providerCatalog??[]).map(xe=>[xe.name,xe]));return(F.data?.providers??[]).filter(xe=>xe.configured&&K.get(xe.name)?.mode==="api").map(xe=>({...xe,catalog:{...K.get(xe.name),defaultModel:xe.model||K.get(xe.name).defaultModel}}))},[f,Y?.providers,F.data]),ne=!(f?V.isPending:F.isPending)&&oe.length===0,ye=oe.find(K=>K.name===y)??null;l.useEffect(()=>{if(!y&&U.data&&!U.isError&&!F.isError){const K=U.data.providers.find(xe=>oe.some(we=>we.name===xe));P(K??oe[0]?.name??"")}},[y,oe,U.data,U.isError,F.isError]);const W=ye?.catalog.modelConfigurable??!1,ue=f?ye?.catalog.defaultModel:(ye?U.data?.providerModels[ye.name]:"")||ye?.catalog.defaultModel,ve=(W?S.trim():"")||ue,J=ye?[...new Map([{id:ye.catalog.defaultModel,displayName:ye.catalog.defaultModel},...S.trim()?[{id:S.trim(),displayName:S.trim()}]:[],...ye.catalog.knownModels].map(K=>[K.id,K])).values()]:[],me=At({...jd(),onSuccess:async K=>{k.current=null,Z(xe=>xe+1),N(K.runs),v(K.runs[0]?.id??null),await Gp(u),Te({title:"Research batch saved",detail:`${K.runs.length} ${K.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${K.runs.map(xe=>xe.id).join(":")}`,dedupeMode:"replace"})},onError:K=>{Te({title:"Could not start research",detail:K instanceof Error?K.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{E.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[x?e.jsx(pe,{className:"surface-card min-w-0",children:e.jsx("p",{className:"text-sm text-secondary",children:"This public demo shows saved research results. Running research is unavailable."})}):e.jsxs(e.Fragment,{children:[e.jsx(Tp,{projectName:t,canWrite:b,researchAllowed:ee&&!te,limitedAccess:f,isEmbed:ie(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:o,scopeError:i,onRetryScope:d,templates:c,locations:se,defaultLocation:U.data?.defaultLocation??null,providerOptions:oe,provider:y,onProviderChange:K=>{P(K),q("")},resolvedModel:ve,visibilityModel:ue,configurableModel:W,model:S,onModelChange:q,modelOptions:J,settingsReady:f?!V.isPending&&!te:!F.isPending&&!F.isError&&!F.isFetching,projectReady:!U.isPending&&!U.isError&&!U.isFetching,isPending:me.isPending,errorMessage:me.isError?"The request could not be confirmed.":void 0,onSubmit:(K,xe)=>{!ee||te||ie()||E.current||(k.current?.fingerprint!==xe&&(k.current={fingerprint:xe,key:crypto.randomUUID()}),E.current=!0,me.mutate({client:Q,path:{name:t},body:{...K,idempotencyKey:k.current.key}}))}},`${t}:${O}`),_!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",_," destination runs per project per day."]}),!f&&F.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(I,{variant:"outline",onClick:()=>{F.refetch()},children:"Retry providers"})]}):null,U.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(I,{variant:"outline",onClick:()=>{U.refetch()},children:"Retry locations"})]}):null,!(f?te:F.isError)&&ne&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:f?"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."}),j.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",j.map((K,xe)=>e.jsxs("span",{children:[xe>0?", ":"",e.jsxs("a",{href:`#research-run-${K.id}`,className:"text-link underline",onClick:()=>v(K.id),children:[K.scope?.label??"Whole site",K.location?`, ${K.location.label}`:", No location"]})]},K.id))]})]}),e.jsxs(pe,{className:"surface-card min-w-0",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsx("div",{children:e.jsx("h3",{children:Tt.historyTitle})}),V.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),te?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(I,{variant:"outline",onClick:()=>{V.refetch()},children:"Retry history"})]}):V.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):A.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:Tt.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:A.map(K=>e.jsxs("tr",{className:T===K.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>v(K.id),children:Dp(K.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:K.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:K.requestedModel??K.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:K.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:K.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[K.completedQueries+K.failedQueries,"/",K.totalQueries]}),e.jsx("td",{children:e.jsx(ce,{tone:Ul(K.status),children:K.status})})]},K.id))})]})}),V.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:Tt.historyMoreError}),V.hasNextPage&&e.jsx(I,{className:"mt-3",variant:"outline",disabled:V.isFetching,onClick:()=>{V.fetchNextPage()},children:V.isFetchingNextPage?Tt.historyLoading:Tt.historyMore})]})]}),!te&&w.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(I,{variant:"outline",onClick:()=>{w.refetch()},children:"Retry results"})]}):te?null:e.jsx(qp,{detail:H,isLoading:w.isFetching,onReviewForTracking:x?void 0:s})]})}const js="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",Pn="__none__";function Tp(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:o}=t,i=us(),[d,c]=l.useState("once"),[h,u]=l.useState(""),[m,b]=l.useState(""),[g,f]=l.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[x,y]=l.useState(null),[P,S]=l.useState([]),[q,T]=l.useState(""),[v,j]=l.useState({}),[N,k]=l.useState(null),[E,O]=l.useState([]),[Z,U]=l.useState(null),[F,z]=l.useState(!1),[V,te]=l.useState(!1),[Y,A]=l.useState(""),[ee,_]=l.useState(""),B=l.useRef(null),w=l.useRef(!1),H=l.useRef(null),se=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";l.useEffect(()=>{f(se),k(null)},[se]);const oe=t.scopeOptions.filter(C=>C.kind==="market"||C.kind==="property"),ne=d==="markets"?"market":"property",ye=oe.filter(C=>C.kind===ne),W=C=>({kind:C.kind,key:C.id,label:C.label,planRevision:o??t.initialScope?.planRevision??0}),ue=C=>C===Pn?null:n.find(Re=>Re.label===C),ve=x??t.defaultLocation??Pn,J=oe.find(C=>`${C.kind}:${C.id}`===g),me=J?W(J):null,K=d==="once"?[{scope:me,location:ue(ve)}]:d==="locations"?P.map(C=>({scope:null,location:ue(C)})):P.map(C=>ye.find(Re=>`${Re.kind}:${Re.id}`===C)).map(C=>C?{scope:W(C),location:ue(v[`${C.kind}:${C.id}`]??Pn)}:null),xe=[...new Map([...E,...t.templates].map(C=>[C.id,C])).values()],we=N?xe.find(C=>C.id===N.id):null,Se=N!==null&&we?.version!==N.version,Ze=d==="once"?h:m,Be=Ze.split(/\r?\n/).filter(C=>C.trim()),Fe=wi(Be),et=[...new Set([...m.matchAll(/\{([^{}]+)\}/g)].map(C=>C[1]))],Me=/[{}]/.test(m.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),D=[];Be.length||D.push(d==="once"?"Enter at least one query.":"Enter at least one query pattern."),Be.some(C=>C.length>4e3)&&D.push("Keep each query under 4,001 characters."),d!=="once"&&Me&&D.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),K.length||D.push(d==="locations"?"Select at least one location.":"Select at least one destination."),K.some(C=>!C||C.location===void 0)&&D.push("A selected destination or location is no longer available. Update your selection.");const $e=d==="once"&&g!=="project"||d==="markets"||d==="properties";$e&&(t.scopePending||t.scopeError||!o||K.some(C=>!C?.scope))&&D.push("Load the current published markets and properties before running scoped research.");const R=(d==="once"?Fe.length:Be.length)*K.length;if(K.length>ga&&D.push(`Select at most ${ga} destinations.`),R>nr&&D.push(`${R} queries selected. Reduce the selection to ${nr} or fewer.`),Se&&D.push("This saved pattern changed. Select its current version from Saved patterns."),d!=="once"&&!Me){for(const C of K)if(!(!C||C.location===void 0))try{sr(N??{pattern:m,variables:et},C.scope,C.location)}catch{D.push(`Choose a location for {location}, or use only variables available for ${d==="markets"?"markets":d==="properties"?"properties":"locations"}.`);break}}const ge=JSON.stringify({mode:d,source:Ze,contexts:K,provider:a,resolvedModel:r,template:N,...$e?{planRevision:o}:{}}),Ee=Z!==null&&Z.signature!==ge,Qe=d==="once"?Fe.map((C,Re)=>({id:String(Re),query:C,scope:me,location:K[0]?.location??null})):Z?.rows??[],Ge=Lp(Qe),he=[];d!=="once"&&Z&&(Ee&&he.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),Qe.some(C=>!C.query.trim()||C.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(C.query))&&he.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),Qe.some(C=>C.location&&!n.some(Re=>JSON.stringify(Re)===JSON.stringify(C.location)))&&he.push("A preview location changed. Regenerate the preview."),Ge.some(C=>wi(C.queries).length!==C.queries.length)&&he.push("Remove duplicate queries within each destination and location."),Ge.length>ga&&he.push(`The preview exceeds ${ga} runs.`));const ht=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!D.length&&!he.length&&(d==="once"||Z!==null),Ke=()=>({runs:Ge.map(C=>({queries:C.queries,provider:a,model:r,location:C.location,...C.scope?{scope:{kind:C.scope.kind,key:C.scope.key,expectedPlanRevision:C.scope.planRevision}}:{},...C.template?{template:C.template}:{}}))}),De=()=>{if(z(!0),D.length)return;const C=K.flatMap((Re,Ne)=>Be.map((Ve,gt)=>({id:`${Ne}:${gt}`,scope:Re.scope,location:Re.location,...N?{template:{templateId:N.id,templateVersion:N.version,bindingLocation:Re.location}}:{},query:sr({pattern:Ve,variables:[...new Set([...Ve.matchAll(/\{([^{}]+)\}/g)].map(tt=>tt[1]))]},Re.scope,Re.location).output})));U({signature:ge,rows:C})},St=C=>{c(C),S([]),k(null),T(""),z(!1)},Ye=C=>{if(_(""),d==="once")try{u(sr(C,me,ue(ve)).output)}catch{_("Select a matching market, property, or location before using this pattern.");return}else b(C.pattern);k(C)},Ce=C=>{const Re=H.current,Ne=Re?.selectionStart??m.length,Ve=Re?.selectionEnd??Ne;b(`${m.slice(0,Ne)}{${C}}${m.slice(Ve)}`),k(null),requestAnimationFrame(()=>{Re?.focus(),Re?.setSelectionRange(Ne+C.length+2,Ne+C.length+2)})},rt=At({...wd(),onSuccess:async C=>{const Re={id:C.id,version:C.updatedAt,label:C.name,pattern:C.pattern,variables:C.variables};O(Ne=>[...Ne.filter(Ve=>Ve.id!==C.id),Re]),k(Re),te(!1),A(""),_(""),B.current=null,await i.invalidateQueries({queryKey:Nd({client:Q,path:{name:s}})}),Te({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>_("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{w.current=!1}}),pt=()=>{if(!t.canWrite||t.isEmbed||w.current)return;const C=d==="once"?h:m,Re=d==="once"?[]:et;if(!Y.trim()||!C.trim()||C.length>4e3||d!=="once"&&Me){_("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const Ne={name:Y.trim(),pattern:C,variables:Re},Ve=JSON.stringify(Ne);B.current?.fingerprint!==Ve&&(B.current={fingerprint:Ve,id:crypto.randomUUID()}),w.current=!0,rt.mutate({client:Q,path:{name:s,templateId:B.current.id},body:Ne})},Mt=[...new Set([...F||Ze.trim()?D:[],...he])],qe=xe.filter(C=>{const Re=d==="once"?Si(me,ue(ve)):Si(d==="markets"?{kind:"market",label:"Market"}:d==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return C.variables.every(Ne=>Re[Ne]!==void 0)});return e.jsxs(pe,{className:"surface-card min-w-0",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Test queries"}),e.jsx("p",{className:"mt-1 max-w-prose text-sm text-secondary",children:"See how an answer engine responds. Results are saved separately from tracked queries and AI Visibility metrics."})]})}),e.jsxs("fieldset",{"aria-label":"Research setup",className:"mt-5 min-w-0 space-y-5",disabled:t.isPending||rt.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:js,value:d,disabled:t.isPending,onChange:C=>St(C.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!oe.some(C=>C.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!oe.some(C=>C.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),d==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(oe.length>0||g!=="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:js,value:g,onChange:C=>{f(C.target.value),k(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),g!=="project"&&!J&&e.jsx("option",{value:g,disabled:!0,children:"Selected destination unavailable"}),oe.map(C=>e.jsxs("option",{value:`${C.kind}:${C.id}`,children:[C.label," (",C.kind,")"]},`${C.kind}:${C.id}`))]})]}),e.jsx(Yr,{label:"Answer engine location",value:ve,locations:n,onChange:C=>{y(C),k(null)}})]}),d!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:d==="locations"?"Select locations":`Select ${d}`}),e.jsx("p",{className:"text-sm text-secondary",children:"Choose each destination explicitly. Each selected destination gets its own saved research run."}),e.jsx("input",{type:"search","aria-label":"Search destinations",className:js,placeholder:`Search ${d}`,value:q,onChange:C=>T(C.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(d==="locations"?n.map(C=>({key:C.label,label:C.label})):ye.map(C=>({key:`${C.kind}:${C.id}`,label:C.label}))).filter(C=>C.label.toLocaleLowerCase().includes(q.toLocaleLowerCase())).map(C=>{const Re=P.includes(C.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:Re,onChange:()=>S(Ne=>Re?Ne.filter(Ve=>Ve!==C.key):[...Ne,C.key])}),C.label]}),Re&&d!=="locations"&&e.jsx(Yr,{label:`Answer engine location for ${C.label}`,value:v[C.key]??Pn,locations:n,onChange:Ne=>j(Ve=>({...Ve,[C.key]:Ne}))})]},C.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[P.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(I,{variant:"outline",onClick:t.onRetryScope,children:"Retry destinations"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block",htmlFor:"research-query-editor",children:e.jsx("span",{className:"text-sm font-medium text-heading",children:d==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:d==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${d==="markets"?"market":d==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:H,className:`${js} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:Ze,placeholder:d==="once"?Tt.queryPlaceholder:d==="markets"?"Best apartments in {market}":d==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:C=>{d==="once"?u(C.target.value):(b(C.target.value),k(null))}}),d!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(I,{size:"sm",variant:"outline",onClick:()=>Ce(d==="markets"?"market":d==="properties"?"property":"location"),children:["Insert ",d==="markets"?"market":d==="properties"?"property":"location"," name"]}),e.jsx("span",{className:"self-center text-sm text-secondary",children:"One pattern per line."})]}),e.jsxs("p",{id:"research-query-count",className:"mt-2 text-sm text-secondary",children:[R," / ",nr," queries",d==="once"?"":` across ${K.length} destinations`]})]}),d!=="once"&&e.jsxs("details",{className:"border-t border-default pt-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading focus-visible:outline focus-visible:outline-2",children:["Saved patterns ",e.jsx("span",{className:"font-normal text-secondary",children:"(optional)"})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries."}),qe.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:qe.map(C=>e.jsx(I,{size:"sm",variant:"outline",onClick:()=>Ye(C),children:C.label},C.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),N&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",N.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(I,{size:"sm",variant:"outline",onClick:()=>te(!V),children:V?"Cancel save":"Save as a pattern"}),V&&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:js,value:Y,maxLength:120,onChange:C=>A(C.target.value)})]}),e.jsx(I,{size:"sm",disabled:rt.isPending||!Y.trim()||!Ze.trim(),onClick:pt,children:rt.isPending?"Saving…":"Save pattern"})]})]}),ee&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:ee})]})]}),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:js,value:a,onChange:C=>t.onProviderChange(C.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose an answer engine"}),t.providerOptions.map(C=>e.jsx("option",{value:C.name,children:C.displayName??C.name},C.name))]})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Model",t.limitedAccess?e.jsxs("select",{className:js,value:t.model,disabled:!a||!t.configurableModel,onChange:C=>t.onModelChange(C.target.value),children:[e.jsxs("option",{value:"",children:["Use AI Visibility model · ",t.visibilityModel]}),t.modelOptions.map(C=>e.jsx("option",{value:C.id,children:C.displayName},C.id))]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{"aria-label":"Model",className:js,list:"research-known-models",placeholder:r??"Choose an answer engine",value:t.model,disabled:!a||!t.configurableModel,onChange:C=>t.onModelChange(C.target.value)}),e.jsx("datalist",{id:"research-known-models",children:t.modelOptions.map(C=>e.jsx("option",{value:C.id,children:C.displayName},C.id))})]})]})]}),Mt.length>0&&e.jsx(Mp,{errors:Mt}),d!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(I,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:De,children:[e.jsx(ea,{size:14}),Z?Tt.refreshPreview:"Preview queries"]}),Z&&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:[Qe.length," query executions in ",Ge.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx($p,{rows:Qe,locations:n,onChange:(C,Re)=>U(Ne=>Ne&&{...Ne,rows:Ne.rows.map(Ve=>Ve.id===C?{...Ve,...Re}:Ve)})})]})]}),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(I,{size:"sm",disabled:!ht,onClick:()=>{if(ht){const C=Ke();t.onSubmit(C,JSON.stringify({projectName:s,...C}))}},children:[e.jsx(Fa,{size:14}),t.isPending?"Starting…":Tt.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[d==="once"?`${Fe.length} queries`:`${Qe.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function Yr({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:js,value:s,onChange:r=>a(r.target.value),children:[e.jsx("option",{value:Pn,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function $p({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:`${js} 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(Yr,{label:`Location for query ${r+1}`,value:a.location?.label??Pn,locations:s,onChange:o=>n(a.id,{location:s.find(i=>i.label===o)??null})})]},a.id))})}function Mp({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 Lp(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 qp({detail:t,isLoading:s,onReviewForTracking:n}){const[a,r]=l.useState(null);l.useEffect(()=>{r(t?.queries[0]?.id??null)},[t?.id]);const o=t?.queries.find(i=>i.id===a)??t?.queries[0]??null;return e.jsxs(pe,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":Tt.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 ${Op(t.id)}`:Tt.resultsEmpty})]}),t&&e.jsx(ce,{tone:Ul(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:Tt.templateProvenance}),e.jsxs("dl",{className:"mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Saved pattern"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.template})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Names used"}),e.jsx("dd",{children:Object.entries(t.template.bindings).map(([i,d])=>`${i}: ${d}`).join(" · ")||"No variables"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Original resolved text"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.output})]})]}),e.jsx("p",{className:"mt-2",children:"The queries below are the final text sent to the answer engine, including any edits."}),e.jsxs("p",{className:"mt-2 font-mono text-xs",children:[t.template.templateId," · ",t.template.templateVersion]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:Tt.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:Tt.methodology})]})]}),t?e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Class"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Brand-name match"}),e.jsx("th",{children:"Project domain cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:o?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>r(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(ce,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?Tt.brandedQuery:i.queryClass==="non-brand"?Tt.discoveryQuery:Tt.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(ce,{tone:Fp(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(ce,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===gn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===gn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(ce,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===gn.failed?"negative":"caution",children:i.citationState===null?i.status===gn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(Ep,{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 Ep({query:t,isLoading:s,scope:n,onReviewForTracking:a}){return t?e.jsxs("div",{className:"min-w-0 space-y-4 border-t border-default pt-4 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),!ie()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(ze,{type:"button",size:"sm",onClick:()=>a({researchRunQueryId:t.id,scope:n}),children:"Review for tracking"}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Only this saved query text enters tracking review. Its answer remains research evidence."})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("div",{className:"mt-1",children:e.jsx(Wo,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===gn.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=Ks(r.uri),d=r.title||r.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:d}):e.jsx("span",{className:"truncate text-secondary",children:d}),i&&e.jsx(zm,{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 Dp(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 Op(t){return t.length>8?t.slice(0,8):t}function Ul(t){return t===Jn.completed?"positive":t===Jn.partial?"caution":t===Jn.failed?"negative":"neutral"}function Fp(t){return t===gn.completed?"positive":t===gn.failed?"negative":"neutral"}async function Gp(t){await wt(t,"researchRuns")}const Jr=new Set(["queued","seeding","probing"]);function Kp({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:o={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:d,onTrackingQueryIdChange:c}){const{account:h}=vn(),[u,m]=l.useState("tracked"),[b,g]=l.useState("find"),[f,x]=l.useState(null),y=h?.role==="viewer"?Sd():null,P=h?.role!=="viewer"||y!==null,S=s??u,q=S==="research"&&!P?"tracked":S,T=a??b,v=k=>{s===void 0&&m(k),n?.(k)},j=k=>{a===void 0&&g(k),r?.(k)},N=(k,E)=>{const O=E===void 0?{...o}:{...o,measurementScope:E?.kind??"project",measurementScopeKey:E?.key};x({...k,trackingSelection:O}),E!==void 0&&i?.({measurementScope:O.measurementScope,measurementScopeKey:O.measurementScopeKey}),v("tracked")};return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"queries-heading",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"queries-heading",children:"Queries"})}),e.jsxs("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Query workspace",children:[e.jsx(Ua,{active:q==="tracked",label:"Tracked",onClick:()=>v("tracked")}),P?e.jsx(Ua,{active:q==="research",label:"Research",onClick:()=>v("research")}):null]}),e.jsx("div",{className:"mt-4",children:q==="tracked"?e.jsx(cg,{projectName:t,selection:o,onSelectionChange:i,trackingQueryId:d,onTrackingQueryIdChange:c,pendingTrackingSource:f,onPendingTrackingSourceHandled:()=>x(null)}):e.jsx(_p,{projectName:t,selection:o,mode:T,onModeChange:j,onReviewSavedSource:N,onSelectionChange:i,viewerResearchConfig:y})})]})}function Ua({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 _p({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:o}){const{canWrite:i}=vn(),d=!i||n==="test",c=Ie({...ol({client:Q,path:{name:t}}),enabled:d,staleTime:6e4}),h=Ie({...ll({client:Q,path:{name:t}}),enabled:d,staleTime:6e4}),u=l.useMemo(()=>{const g=c.data;if(!g)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const f=new Map(g.targets.map(y=>[y.stableKey,[]]));for(const y of g.groups)for(const P of y.targetKeys)f.get(P)?.push(y.stableKey);const x=new Map(g.markets.map(y=>[y.stableKey,new Set]));for(const y of g.markets)for(const P of y.usageEdges)for(const S of f.get(P.targetKey)??[])x.get(y.stableKey)?.add(S);return[{id:"project",label:"Whole site",kind:"project",targetCount:g.targets.length},...g.groups.map(y=>({id:y.stableKey,label:y.label,kind:"group",targetCount:y.targetKeys.length,...y.parentGroupKey?{parentGroupIds:[y.parentGroupKey]}:{}})),...g.markets.map(y=>{const P=[...x.get(y.stableKey)??[]];return{id:y.stableKey,label:y.label,kind:"market",targetCount:0,...P.length?{parentGroupIds:P}:{}}}),...g.targets.map(y=>({id:y.stableKey,label:y.label,kind:"property",targetCount:1,...f.get(y.stableKey)?.length?{parentGroupIds:f.get(y.stableKey)}:{}}))]},[c.data]),m=l.useMemo(()=>(h.data?.templates??[]).map(g=>({id:g.id,version:g.updatedAt,label:g.name,pattern:g.pattern,variables:g.variables})),[h.data]),b={projectName:t,scopeOptions:u,planRevision:c.data?.active?.revision??null,selectedScope:(()=>{const g=u.find(x=>x.kind===s.measurementScope&&x.id===s.measurementScopeKey),f=c.data?.active?.revision;return g&&f&&(g.kind==="market"||g.kind==="property")?{kind:g.kind,key:g.id,label:g.label,planRevision:f,expectedPlanRevision:f}:(s.measurementScope==="market"||s.measurementScope==="property")&&s.measurementScopeKey?{kind:s.measurementScope,key:s.measurementScopeKey,label:s.measurementScopeKey,planRevision:f??0,expectedPlanRevision:f??0}:null})(),scopePending:c.isPending||c.isFetching,scopeError:c.isError,onRetryScope:()=>{c.refetch()},templates:m};return i?e.jsxs("div",{children:[e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(Ua,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(Ua,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(dg,{projectName:t,onReviewDiscoveryProbe:g=>r({source:"discovery",discoveryProbeId:g})}):e.jsx(mo,{...b,onReviewForTracking:({researchRunQueryId:g,scope:f})=>r({source:"research",researchRunQueryId:g},f??null)})})]}):e.jsx(mo,{...b,viewerResearchConfig:o})}function Up({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:d,preview:c,isPreviewing:h,isCommitting:u,onPreview:m,onCommit:b}){const[g,f]=l.useState(null),[x,y]=l.useState(()=>qa(s)),[P,S]=l.useState(null),q=l.useRef(null),T=l.useRef(null),v=Qp(t,s),j=l.useMemo(()=>Hp(t.tracked,s,t.mode),[s,t.mode,t.tracked]),N=yn({rows:j,getSearchText:V=>`${V.queryText} ${V.provenance?.source??"legacy"} ${V.assignments.map(te=>te.queryClass??"unknown").join(" ")}`});l.useEffect(()=>{if(v)return;if(!a){T.current=null;return}const V=`${a}:${jr(s)}`;if(T.current===V)return;const te=t.tracked.find(Y=>Y.queryId===a);te&&(T.current=V,f({kind:"edit",row:te,audience:t.mode==="advanced"?br(s):void 0,scopeLabel:vr(s,t)}),y(ho(te,s)),S(null))},[s,a,v,t]),l.useEffect(()=>{if(v||!o)return;const V=qa(o.trackingSelection??s);f({kind:"add"}),y(o.source==="research"?{...V,source:"research",researchRunQueryId:o.researchRunQueryId}:{...V,source:"discovery",discoveryProbeId:o.discoveryProbeId}),S(null),i()},[i,o,s,v]),l.useEffect(()=>{v&&(f(null),S(null),a!==void 0&&r?.(void 0))},[r,a,v]),l.useEffect(()=>{if(!g||g.kind==="remove")return;const V=q.current;V&&(V.scrollIntoView?.({block:"start"}),V.focus({preventScroll:!0}))},[g]);function k(V="manual"){f({kind:"add"}),y({...qa(s),source:V}),S(null),r?.(void 0)}function E(V){T.current=`${V.queryId}:${jr(s)}`,f({kind:"edit",row:V,audience:t.mode==="advanced"?br(s):void 0,scopeLabel:vr(s,t)}),y(ho(V,s)),S(null),r?.(V.queryId)}function O(V){T.current=`${V.queryId}:${jr(s)}`,f({kind:"remove",row:V,audience:t.mode==="advanced"?br(s):void 0,scopeLabel:vr(s,t)}),S(null),r?.(V.queryId)}function Z(){f(null),S(null),r?.(void 0)}const U=g?Bp(g,x,t.mode):null,F=g!==null&&g.kind==="add"&&t.mode==="advanced"&&!li(x),z=U!==null&&(!F||x.contexts.length>0)&&!h;return v?e.jsx("div",{className:"query-tracking-workspace space-y-4",children:e.jsxs("section",{"aria-label":"Tracked queries",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["This saved ",s.measurementScope," filter is unavailable in the current measurement."]}),e.jsx(I,{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(Yp,{workspace:t,selection:s,onSelectionChange:n}),t.mode==="advanced"?e.jsx(Wp,{selection:s,onSelectionChange:n}):null,e.jsx(zs,{value:N.query,onChange:N.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!ie()&&e.jsxs(ze,{type:"button",size:"sm",onClick:()=>k(),children:[e.jsx(Qm,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[N.totalRows.toLocaleString("en-US")," saved query ",N.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."}),N.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:N.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:N.rows.map(V=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:V.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(Xp,{row:V,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(eg,{row:V})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:Jp(V)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(tg,{row:V,outsidePlan:t.mode==="advanced"&&V.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!ie()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(ze,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${V.queryText}`,onClick:()=>E(V),children:[e.jsx(Hm,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(ze,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${V.queryText}`,onClick:()=>O(V),children:[e.jsx(bl,{"aria-hidden":"true",size:13})," Remove"]})]})})]},V.queryId))})]})}),e.jsx(Ts,{page:N.page,pageSize:N.pageSize,visibleRows:N.rows.length,totalRows:N.totalRows,itemLabel:"queries",onPageChange:N.setPage})]}),g&&!ie()&&e.jsx(sg,{workspace:t,templates:d,action:g,draft:x,onDraftChange:V=>{y(V),S(null)},onClose:Z,canReview:z,isPreviewing:h,editorHeadingRef:q,onReview:()=>{U&&(S(U),m(U))}}),c&&P&&g&&e.jsx(ig,{preview:c,workspace:t,isCommitting:u,onConfirm:()=>{b({...P,expectedWorkspaceVersion:c.workspaceVersion,previewToken:c.previewToken,reviewedAt:c.reviewedAt})}})]})}function qa(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 ho(t,s){return{...qa(s),text:t.queryText,queryClass:"keep"}}function Bp(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=Vp(s);if(!a||Xr(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=zp(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!li(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function Vp(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 zp(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 li(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function Xr(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function br(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 Qp(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 vr(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 ci(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 Hp(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=>ci(r,s)))}function Wp({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 jr(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function Yp({workspace:t,selection:s,onSelectionChange:n}){const a=l.useMemo(()=>{const o=new Map(t.targets.map(i=>[i.stableKey,[]]));for(const i of t.groups)for(const d of i.targetKeys)o.get(d)?.push(i.stableKey);return[{id:"project",label:"Whole site",kind:"project",targetCount:t.targets.length},...t.groups.map(i=>({id:i.stableKey,label:i.label,kind:"group",targetCount:i.targetKeys.length,...i.parentGroupKey?{parentGroupIds:[i.parentGroupKey]}:{}})),...t.markets.map(i=>({id:i.stableKey,label:i.label,kind:"market",targetCount:new Set(i.usageEdges.map(d=>d.targetKey)).size,...i.groupKey?{parentGroupIds:[i.groupKey]}:{}})),...t.targets.map(i=>({id:i.stableKey,label:i.label,kind:"property",targetCount:1,...o.get(i.stableKey)?.length?{parentGroupIds:o.get(i.stableKey)}:{}}))]},[t.groups,t.markets,t.targets]),r=a.find(o=>o.kind===s.measurementScope&&(o.kind==="project"||o.id===s.measurementScopeKey))??a[0];return e.jsx(Yo,{options:a,selected:r,onSelect:o=>{n?.({measurementScope:o.kind,measurementScopeKey:o.kind==="project"?void 0:o.id})}})}function Jp(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 Bl(t,s,n){const a=new Map(s.targets.map(x=>[x.stableKey,x.label])),r=new Map(s.groups.map(x=>[x.stableKey,x.label])),o=new Map(s.markets.map(x=>[x.stableKey,x.label])),i=new Set(t.assignments.map(x=>x.targetKey));if(i.size===0)return"Whole site";const d=n?t.assignments.filter(x=>ci(x,n)):t.assignments,c=new Set(d.map(x=>x.targetKey));if(n?.measurementScope==="group"){const x=c.size,y=Math.max(0,i.size-x);return[`${x} ${x===1?"property":"properties"} in this group`,...y?[`Shared with ${y} other ${y===1?"property":"properties"}`]:[]].join(" · ")}const h=new Set,u=new Set;for(const x of d)x.groupKeys.forEach(y=>h.add(y)),x.marketKeys.forEach(y=>u.add(y));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"}`]:c.size===1?[a.get([...c][0])??[...c][0]]:[`${c.size} properties`],g=h.size===1?r.get([...h][0])??[...h][0]:null,f=u.size===1?o.get([...u][0])??[...u][0]:null;return g&&f&&g===f?b.push(`${g} (group and market)`):(g?b.push(`Group: ${g}`):h.size>1&&b.push(`${h.size} groups`),f?b.push(`Market: ${f}`):u.size>1&&b.push(`${u.size} markets`)),b.join(" · ")}function Xp({row:t,workspace:s,selection:n}){const a=Zp(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:Bl(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 Zp(t,s,n){const a=new Map(s.targets.map(c=>[c.stableKey,c.label])),r=new Map(s.groups.map(c=>[c.stableKey,c.label])),o=new Map(s.markets.map(c=>[c.stableKey,c.label])),d=t.assignments.filter(c=>ci(c,n)).map(c=>{const h=a.get(c.targetKey)??c.targetKey??"Whole site",u=n.measurementScope==="group"&&n.measurementScopeKey?c.groupKeys.filter(b=>b===n.measurementScopeKey).map(b=>r.get(b)??b):c.groupKeys.map(b=>r.get(b)??b),m=n.measurementScope==="market"&&n.measurementScopeKey?c.marketKeys.filter(b=>b===n.measurementScopeKey).map(b=>o.get(b)??b):c.marketKeys.map(b=>o.get(b)??b);return[h,u.length?`Groups: ${u.join(", ")}`:null,m.length?`Markets: ${m.join(", ")}`:null].filter(b=>b!==null).join(" · ")});return[...new Set(d)].length?[...new Set(d)]:["Whole site"]}function eg({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(ce,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function tg({row:t,outsidePlan:s=!1}){return s?e.jsx(ce,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(ce,{tone:"positive",children:"Measured"}):e.jsx(ce,{tone:"caution",children:"Awaiting sweep"})}function sg({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:o,canReview:i,isPreviewing:d,editorHeadingRef:c,onReview:h}){const u=s.length>0;return n.kind==="remove"?e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Remove query"}),e.jsxs("p",{className:"mt-1 text-sm leading-6 text-secondary",children:["Remove “",n.row.queryText,"” from future tracking?"]}),e.jsxs("p",{className:"mt-1 text-sm leading-5 text-secondary",children:[n.audience?`Only assignments in ${n.scopeLabel} will be removed.`:"All assignments will be removed."," Earlier results stay unchanged."]})]})}),e.jsx(Nr,{canReview:i,isPreviewing:d,onCancel:o,onReview:h})]}):n.kind==="edit"?e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:c,tabIndex:-1,children:"Edit query"}),e.jsx(I,{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:m=>r({...a,text:m.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:m=>r({...a,queryClass:m.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(Nr,{canReview:i,isPreviewing:d,onCancel:o,onReview:h})]}):e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:c,tabIndex:-1,children:"Add query"}),e.jsx(I,{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:m=>r({...a,text:m.target.value})})]}):null,a.source==="template"?e.jsx(ng,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(xo,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(m=>({id:m.researchRunQueryId,label:m.queryText,detail:m.researchRunId})),onChange:m=>r({...a,researchRunQueryId:m})}):null,a.source==="discovery"?e.jsx(xo,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(m=>({id:m.discoveryProbeId,label:m.queryText,detail:m.discoverySessionId})),onChange:m=>r({...a,discoveryProbeId:m})}):null,e.jsxs("label",{className:"block",htmlFor:"tracking-query-source",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Query source"}),e.jsxs("select",{id:"tracking-query-source","aria-describedby":u?void 0:"tracking-query-source-no-templates",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.source,onChange:m=>r({...a,source:m.target.value}),children:[e.jsx("option",{value:"manual",children:"Write a question"}),u?e.jsx("option",{value:"template",children:"Saved template"}):null,e.jsxs("option",{value:"research",disabled:t.savedSources.research.length===0,children:["Saved research",t.savedSources.research.length===0?" (none available)":""]}),e.jsxs("option",{value:"discovery",disabled:t.savedSources.discovery.length===0,children:["Discovery result",t.savedSources.discovery.length===0?" (none available)":""]})]})]}),u?null:e.jsx("p",{id:"tracking-query-source-no-templates",className:"text-sm leading-6 text-secondary",children:"No saved templates are set up for this portfolio. Write a question, or use saved research or a discovery result."})]}),e.jsx(rg,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!li(a)?e.jsx("div",{className:"mt-4",children:e.jsx(ag,{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:m=>r({...a,queryClass:m.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(Nr,{canReview:i,isPreviewing:d,onCancel:o,onReview:h})]})}function ng({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":Xr(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]}),Xr(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 xo({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 di(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function Hn(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 Vl(t){return[...new Map(t.map(s=>[Hn(s),s])).values()]}function ui(t){const s=t.providers.map(n=>{const a=t.models[n];return a?`${n} (${a})`:n}).join(", ");return`${t.location??"No location"} · ${s}`}function ag({workspace:t,draft:s,onDraftChange:n}){const a=l.useMemo(()=>Vl([...t.defaultContexts.map(di),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?Hn(s.contexts[0]):s.contexts.length>1?"__existing__":"";return e.jsxs("label",{className:"block",htmlFor:"tracking-query-context",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location and engines"}),e.jsxs("select",{id:"tracking-query-context","aria-label":"Location and engines",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:r,onChange:o=>{const i=a.find(c=>Hn(c)===o.target.value),d=o.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:d})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(o=>e.jsx("option",{value:Hn(o),children:ui(o)},Hn(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 rg({workspace:t,draft:s,onDraftChange:n}){const[a,r]=l.useState(""),[o,i]=l.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),d=l.useMemo(()=>[...t.targets.map(g=>({kind:"target",key:g.stableKey,label:g.label,detail:"Property"})),...t.groups.map(g=>({kind:"group",key:g.stableKey,label:g.label,detail:"Group"})),...t.markets.map(g=>({kind:"market",key:g.stableKey,label:g.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),c=a.trim().toLocaleLowerCase(),h=c?d.filter(g=>`${g.label} ${g.detail}`.toLocaleLowerCase().includes(c)):d,u=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function m(g,f,x){const y=g==="target"?"targetKeys":g==="group"?"groupKeys":"marketKeys",P=s[y];n({...s,wholeSite:!1,[y]:x?[...P,f]:P.filter(S=>S!==f)})}function b(g,f){return(g==="target"?s.targetKeys:g==="group"?s.groupKeys:s.marketKeys).includes(f)}if(!o){const g=t.targets.find(f=>f.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: ",g?.label??s.targetKeys[0]]}),e.jsx(I,{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:g=>{n({...s,wholeSite:g.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),"Whole site"]}),!s.wholeSite&&!u?e.jsx("p",{role:"status",className:"mt-2 text-sm text-caution",children:"Choose Whole site or at least one property, group, or market."}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:"Group: properties grouped together. Market: search context."}),e.jsx(zs,{value:a,onChange:r,label:"Filter assignments",placeholder:"Search Properties, Groups, Markets",className:"mt-3"}),e.jsx("div",{className:"mt-3 max-h-64 space-y-1 overflow-y-auto pr-1",children:h.length===0?e.jsx("p",{className:"px-1 py-2 text-sm text-muted",children:"No assignment matches that search."}):h.map(g=>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":`${g.label}, ${g.detail}`,checked:b(g.kind,g.key),onChange:f=>m(g.kind,g.key,f.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:g.label}),e.jsx("span",{className:"text-xs text-muted",children:g.detail})]},`${g.kind}:${g.key}`))})]})}function Nr({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(ze,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(I,{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 ig({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=l.useRef(null);l.useEffect(()=>{const d=r.current;d&&(typeof d.scrollIntoView=="function"&&d.scrollIntoView({block:"start"}),d.focus({preventScroll:!0}))},[t]);const o=!t.diff.noOp,i=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(d=>d.rows.length>0);return e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{ref:r,tabIndex:-1,children:o?"Confirm tracked query changes":"No tracking changes"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:o?"Changes apply to future sweeps. Earlier results stay unchanged.":"This request leaves tracking unchanged."})]}),e.jsx(ce,{tone:o?"caution":"neutral",children:o?"Ready to confirm":"No-op"})]}),i.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:i.map(d=>e.jsx(po,{label:d.label,rows:d.rows,workspace:s,tracked:t.tracked},d.label))}):null,t.diff.unchanged.length>0?e.jsxs("details",{className:"mt-4 border-t border-default pt-2 text-sm text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3",children:[t.diff.unchanged.length," unchanged ",t.diff.unchanged.length===1?"query":"queries"]}),e.jsx(po,{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(ze,{type:"button",size:"sm",disabled:!o||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function po({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`:lg(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(og,{row:a.find(o=>o.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function og({row:t,workspace:s}){if(!t?.assignments.length)return null;const n=new Set(t.assignments.map(a=>a.targetKey)).size;return e.jsxs("details",{className:"mt-2 text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:["Classifications · ",n," ",n===1?"property":"properties"]}),e.jsx("ul",{className:"mt-1 max-h-40 space-y-1 overflow-y-auto",children:t.assignments.map((a,r)=>{const o=s.targets.find(c=>c.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",d=a.contexts.map(c=>ui(di(c))).join("; ");return e.jsx("li",{children:[o,i,d].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function lg(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=Vl(a.assignments.flatMap(i=>i.contexts).map(di)),o=r.length===1?ui(r[0]):r.length>1?`${r.length} contexts`:null;return[Bl(a,n),o].filter(i=>i!==null).join(" · ")}function cg({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i}){const d=us(),[c,h]=l.useState(null),u=Ie({...ol({client:Q,path:{name:t}})}),m=Ie({...ll({client:Q,path:{name:t}}),staleTime:6e4}),b=At({...kd(),onSuccess:f=>h(f),onError:async f=>{h(null),await d.invalidateQueries({queryKey:Cd({client:Q,path:{name:t}})}),Te({title:"Could not review tracking changes",detail:f instanceof Error?f.message:"Update the draft and review it again.",tone:"negative"})}}),g=At({...Ad(),onSuccess:async f=>{h(null),r?.(void 0),await Ci(d,t),Te({title:f.committed?"Tracked queries updated":"No tracked-query change",detail:f.active?`Measurement revision ${f.active.revision}.`:"No measurement revision is published yet.",tone:f.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async f=>{h(null),await Ci(d,t),Te({title:"Could not confirm tracking changes",detail:f instanceof Error?f.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return u.isLoading?e.jsx(pe,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):u.isError||!u.data?e.jsxs(pe,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(I,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{u.refetch()},children:"Try again"})]}):e.jsx(Up,{workspace:u.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:m.data?.templates??[],preview:c,isPreviewing:b.isPending,isCommitting:g.isPending,onPreview:f=>{h(null),b.mutate({client:Q,path:{name:t},body:{...f,expectedWorkspaceVersion:u.data.workspaceVersion}})},onCommit:f=>g.mutate({client:Q,path:{name:t},body:f})})}function dg({projectName:t,onReviewDiscoveryProbe:s}){const n=us(),[a,r]=l.useState(null),[o,i]=l.useState(""),[d,c]=l.useState("100"),h=Ie({...Pd({client:Q,path:{name:t},query:{limit:"10"}}),refetchInterval:S=>S.state.data?.some(T=>Jr.has(T.status))?3e3:!1}),u=h.data??[];l.useEffect(()=>{!a&&u[0]&&r(u[0].id)},[a,u]);const m=u.find(S=>S.id===a)??null,b=Ie({...Rd({client:Q,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:m&&Jr.has(m.status)?3e3:!1}),g=b.data??null,f=At({mutationFn:()=>{const S={},q=o.trim();q&&(S.icpDescription=q);const T=Number.parseInt(d,10);return Number.isFinite(T)&&T>0&&(S.maxProbes=T),Id(t,S)},onSuccess:async S=>{r(S.sessionId),i(""),await xg(n,t,S.sessionId),Te({title:"Discovery started",detail:`Run ${wr(S.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${S.sessionId}`,dedupeMode:"replace"})},onError:S=>{Te({title:"Discovery failed to start",detail:S instanceof Error?S.message:"Could not start discovery.",tone:"negative"})}}),x=g??m,y=l.useMemo(()=>(g?.probes??[]).slice(0,30),[g?.probes]);async function P(){try{const S=await h.refetch();if(S.error)throw S.error;const q=S.data?.length??0;Te({title:"Discovery sessions refreshed",detail:`${q} recent session${q===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(S){Te({title:"Discovery refresh failed",detail:S instanceof Error?S.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:ie()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(I,{type:"button",variant:"outline",size:"sm",disabled:h.isFetching,onClick:()=>{P()},children:[e.jsx(ea,{className:`size-3.5 ${h.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(ce,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:o,onChange:S=>i(S.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:d,onChange:S=>c(S.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!ie()&&e.jsxs(ze,{type:"button",size:"sm",disabled:f.isPending,onClick:()=>f.mutate(),children:[e.jsx(Fa,{size:14}),f.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),h.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),u.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:u.map(S=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===S.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(S.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:wr(S.id)}),e.jsx(ce,{tone:go(S.status),children:S.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",S.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",S.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",S.wastedCount??0]})]})]},S.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:x?wr(x.id):"No run selected"})]}),x&&e.jsx(ce,{tone:go(x.status),children:x.status})]}),x?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(wa,{label:"Questions tested",value:x.probeCount??0}),e.jsx(wa,{label:"Cited queries",value:x.citedCount??0,tone:"positive"}),e.jsx(wa,{label:"Worth tracking",value:x.aspirationalCount??0,tone:"caution"}),e.jsx(wa,{label:"Skip",value:x.wastedCount??0,tone:"negative"})]}),x.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:x.error}),x.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:x.warning}),x.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:x.icpDescription})]}),x.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:x.competitorMap.slice(0,8).map(S=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[S.domain," ",e.jsx("span",{className:"text-muted",children:S.hits})]},S.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),x?.status==="completed"&&e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Review a discovery question for tracking"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:"Choose a Cited query or Worth tracking result below. Tracking opens with the saved discovery source, where you choose its scope and review the exact next-sweep change."})]})}),e.jsx("p",{className:"mt-3 text-xs leading-5 text-muted",children:"Discovery remains research. This review does not add competitors or start a sweep."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),b.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),y.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:y.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.query}),e.jsx("td",{children:e.jsx(ce,{tone:ug(S.bucket),children:hg(S.bucket)})}),e.jsx("td",{className:"text-secondary",children:S.citedDomains.length>0?S.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!ie()&&s&&(S.bucket==="cited"||S.bucket==="aspirational")&&e.jsx(ze,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(S.id),children:"Review for tracking"})})]},S.id))})]})})]})]})]})]})}function wa({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 go(t){return t==="completed"?"positive":t==="failed"?"negative":Jr.has(t)?"caution":"neutral"}function ug(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const mg={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function hg(t){return t?mg[t]:"Not classified"}function wr(t){return t.length>8?t.slice(0,8):t}async function xg(t,s,n){await Promise.all([wt(t,"discovery"),t.invalidateQueries({queryKey:Td({client:Q})})])}function fo(t){return`${(t*100).toFixed(1)}%`}function pg({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),d=Ie({...$d({client:Q,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=Ie({...Md({client:Q,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(c.data??[]).filter(y=>(y.status==="completed"||y.status==="partial")&&y.trigger!=="probe").reverse(),u=o??h[0]?.id??"",m=a??h.find(y=>y.id!==u)?.id??"",b=!!(m&&u&&m!==u),g=Ie({...Ld({client:Q,path:{name:t},query:{run1:m,run2:u}}),enabled:s==="compare"&&b}),f=d.data??[],x=g.data?.diff.filter(y=>y.changed||y.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(([y,P])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===y,className:`filter-chip ${s===y?"filter-chip-active":""}`,onClick:()=>n(y),children:P},y))}),s==="changes"?e.jsx(ah,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),d.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!d.isLoading&&f.length===0?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:Ot()?Ys:"Complete an answer visibility sweep to create the first snapshot."})]}):null,f.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"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:f.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(y.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[y.mentionedPairs,"/",y.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:fo(y.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[y.citedPairs,"/",y.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:fo(y.overallCitedRate)})]},y.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:m,onChange:y=>r(y.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(y=>e.jsx("option",{value:y.id,children:new Date(y.createdAt).toLocaleString()},y.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:u,onChange:y=>i(y.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(y=>e.jsx("option",{value:y.id,children:new Date(y.createdAt).toLocaleString()},y.id))})]})]}),c.isLoading||g.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!c.isLoading&&h.length<2?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:Ot()?Ys:"Run another answer visibility sweep before comparing historical evidence."})]}):null,g.data&&x.length===0?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,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:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:x.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:y.query??"Archived query"}),e.jsx("td",{children:e.jsxs(ce,{tone:y.changed?"caution":"neutral",children:[y.run1State??"none"," → ",y.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(ce,{tone:y.visibilityChanged?"caution":"neutral",children:[y.run1MentionState??"none"," → ",y.run2MentionState??"none"]})})]},y.queryId??y.query??"unknown"))})]})}):null]}):null]})}const yo={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},gg={contract:null,assessment:null,googleAds:yo,gtm:yo,snapshots:[]};function fg(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":jg(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function yg(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 bg(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 vg(t){switch(t.gtm.state){case"not-connected":return{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."};case"selection-required":return{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."};case"stale":return{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."};default:return null}}function zl(t){return t.googleAds.state==="not-connected"?{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."}:t.googleAds.state==="unavailable"||t.gtm.state==="unavailable"?{id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."}:t.googleAds.state==="selection-required"?{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."}:t.googleAds.state==="stale"?{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."}:t.gtm.state==="not-connected"?{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."}:t.gtm.state==="selection-required"?{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."}:t.gtm.state==="stale"?{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."}:t.contractSelectionRequired?{id:"select-contract",label:"Select conversion",detail:"Choose the declared conversion Canonry should assess."}:t.contract?t.assessmentState==="loading"?{id:"waiting-for-integrity",label:"Checking configuration…",detail:"Canonry is loading the selected conversion assessment."}:t.assessmentState==="unavailable"?{id:"retry-integrity",label:"Retry assessment",detail:"Retry the selected conversion assessment before acting on its evidence."}:t.assessment?.status==="runtime-unverified"?{id:"review-runtime-verification",label:"Review runtime verification",detail:"Static configuration is aligned. Verify a real browser event separately."}:t.assessment?.status==="configured"&&Ng(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 jg(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Ng(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Ql(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 wg(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 Sg(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 cn(t){return t.length<=12?t:`…${t.slice(-10)}`}function Cg(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 kg(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 Sr={"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 bo(t){return t.outcome==="pass"?{label:Sr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Sr[t.code],tone:"negative",outcome:"Fail"}:{label:Sr[t.code],tone:"caution",outcome:"Unknown"}}function Ag(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Pg(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 Rg(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function vo({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=Ql(s.state),i=s.snapshotState==="loading"?"Loading stored snapshots":s.snapshotState==="unavailable"?"Stored snapshots unavailable":s.snapshotCount===0?"No stored snapshots":null;return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:t}),e.jsx("td",{children:e.jsx(ce,{tone:o.tone,children:o.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),i?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:i}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Ht(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(ze,{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 Ig="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.",Tg="Available once Google Ads and Tag Manager are connected.",$g="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 Mg({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:o}){const i=t.googleAds.state==="connected",d=t.gtm.state==="connected",c=t.googleAds.state==="unavailable",h=t.gtm.state==="unavailable",u=c||h||t.gtm.state==="unavailable",m={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},b=!i&&!d,g=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:c?m:bg(t)},{title:"Tag Manager",state:t.gtm.state,ready:d,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?m:vg(t)}],f=i&&d&&!u?zl(t):null;return e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("h2",{id:"conversion-integrity-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx(Ue,{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:$g}):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(Ue,{text:Ig})]}),f&&s?e.jsx(ze,{type:"button",disabled:r,onClick:()=>s(f.id),children:r?"Working…":f.label}):e.jsx("p",{className:"text-sm text-secondary",children:Tg})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:g.map(x=>{const y=x.ready?{label:"Ready",tone:"positive"}:Ql(x.state),P=x.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:x.title}),e.jsx(ce,{tone:y.tone,children:y.label}),x.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:x.summary}):null,P&&s?P.id==="retry-connection-status"?e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(P.id),children:r?"Working…":P.label}):e.jsx(ze,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(P.id),children:r?"Working…":P.label}):null,x.summary&&x.onChange?e.jsx(ze,{type:"button",variant:"ghost",size:"sm","aria-label":x.changeLabel,disabled:r,onClick:x.onChange,children:"Change"}):null]},x.title)})}),o?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:o}):null]})]})}function Lg({workspace:t=gg,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:o=null,onSelectContract:i,contractError:d=null,onRetryContracts:c,onRetryEvidence:h,onChangeGoogleAdsSelection:u,onChangeGtmSelection:m,onAddContract:b}){const g=fg(t),f=yg(g),x=zl(t),y=t.assessment?.findings??[],P=y.filter(v=>v.outcome!=="pass"),S=y.filter(v=>v.outcome==="pass"),q=P.some(v=>v.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&d===null?e.jsx(Mg,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:u,onChangeGtmSelection:m,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ce,{tone:f.tone,children:f.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Ht(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:f.detail}),t.assessmentEvidenceSnapshots?.length?e.jsxs("details",{className:"inline-disclosure mt-3 max-w-2xl",children:[e.jsx("summary",{children:"Evidence used for this assessment"}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm leading-6 text-secondary",children:t.assessmentEvidenceSnapshots.map(v=>e.jsxs("li",{className:"break-words",children:[Rg(v)," ",v.kind,", captured ",Ht(v.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",v.id,")"]})]},v.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?x.id==="review-findings"||x.id==="review-runtime-verification"||x.id==="retry-connection-status"||x.id==="select-contract"||x.id==="retry-integrity"||x.id==="waiting-for-integrity"?e.jsx(I,{type:"button",disabled:n||x.id==="waiting-for-integrity",onClick:()=>s(x.id),children:n?"Working…":x.label}):e.jsx(ze,{type:"button",disabled:n,onClick:()=>s(x.id),children:n?"Working…":x.label}):x.id==="review-findings"?e.jsx(I,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):g==="runtime-unverified"?e.jsx(I,{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:x.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(ze,{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:v=>i?.(v.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(v=>e.jsx("option",{value:v.id,children:v.name},v.id))]})]}):null,t.contract?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Website event"}),e.jsx("dd",{className:"mt-1 text-sm font-medium text-heading",children:t.contract.eventName})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Google Ads goal"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:Cg(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:kg(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:cn(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:cn(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:cn(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:cn(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),d?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:d}),c?e.jsx(I,{type:"button",variant:"outline",onClick:c,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),P.length>0?e.jsxs("section",{id:"conversion-integrity-findings",tabIndex:-1,className:"page-section-divider","aria-labelledby":"conversion-integrity-findings-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Assessment findings"}),e.jsx("h3",{id:"conversion-integrity-findings-title",className:"text-base font-semibold text-heading",children:"Checks to review"})]}),e.jsxs(ce,{tone:q,children:[P.length," ",P.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:P.map(v=>{const j=bo(v);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:j.label}),e.jsx(ce,{tone:j.tone,children:j.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",v.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",v.code]}),v.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",v.evidenceIds.join(", ")]}):null]},`${v.code}:${v.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(Ue,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(v=>{const j=wg(v.key,g);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:v.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:v.detail}),e.jsx(ce,{tone:j,children:Sg(v.key,g)})]},v.key)})})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-connections-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection evidence"}),e.jsx("h3",{id:"conversion-integrity-connections-title",className:"text-base font-semibold text-heading",children:"Google Ads and Tag Manager"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads and Tag Manager connection and stored evidence state"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Connection"}),e.jsx("th",{scope:"col",children:"Selection"}),e.jsx("th",{scope:"col",children:"Stored evidence"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsxs("tbody",{children:[vo({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:u}:{},actionPending:n}),vo({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:m}:{},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(I,{type:"button",variant:"outline",className:"mt-3",onClick:h,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:v.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:v.kind}),e.jsx("td",{className:"text-secondary",children:Ht(v.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:cn(v.id)})]},v.id))})]})})]}):null,S.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[S.length," ",S.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:S.map(v=>{const j=bo(v);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: ",v.code]}),v.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",v.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(ce,{tone:j.tone,children:j.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:v.subject})]},`${v.code}:${v.subject}`)})})]})})]}):null,g==="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 ",Ag(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:cn(t.contract.gtm.tagId)})," fires with ",Pg(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:cn(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const dn=3e4,jo={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},It="mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",os="text-sm font-medium text-secondary";function No(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:bt(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function Sa(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function qg(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 Eg(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Dg(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:Eg(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 Og(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:Sa(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:Sa(t.triggerIds),variableIds:Sa(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:Sa(t.productionHosts)}}}function wo(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 Ca(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 ka(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Aa({id:t,label:s,value:n,onChange:a,children:r,disabled:o=!1}){return e.jsxs("label",{htmlFor:t,className:os,children:[s,e.jsx("select",{id:t,className:It,value:n,onChange:i=>a(i.target.value),disabled:o,children:r})]})}function wn({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 So({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[d,c]=l.useState(null),h=l.useRef(null),u=l.useRef(null),m=l.useRef(!1);l.useEffect(()=>{const x=m.current;m.current=a,a?u.current?.focus():x&&h.current?.querySelector("button")?.focus()},[a]);function b(){c(null),r(!0)}function g(){c(null),r(!1)}async function f(){i(!0),c(null);try{await n()}catch(x){c(bt(x)),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(I,{ref:u,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:o,onClick:g,children:"Keep connected"}),e.jsx(ze,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||o,onClick:()=>{f()},children:o?"Disconnecting…":`Disconnect ${t}`})]}),d?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:d}):null]}):e.jsxs(ze,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:b,children:["Disconnect ",t]})})}function Co({id:t,label:s,options:n,synced:a,loading:r,failed:o,onRetry:i,emptyHint:d,value:c,onChange:h}){const u=n.some(x=>x.id===c),[m,b]=l.useState(!1),g=m||c!==""&&!u&&n.length>0,f=e.jsx("label",{htmlFor:t,className:os,children:s});return r?e.jsxs("div",{children:[f,e.jsx("select",{id:t,className:It,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):o?e.jsxs("div",{children:[f,e.jsx("input",{id:t,required:!0,className:It,value:c,onChange:x=>h(x.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:[f,e.jsx("input",{id:t,required:!0,className:It,value:c,onChange:x=>h(x.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":d})]}):e.jsxs("div",{children:[f,g?e.jsx("input",{id:t,required:!0,className:It,value:c,onChange:x=>h(x.target.value)}):e.jsxs("select",{id:t,required:!0,className:It,value:c,onChange:x=>h(x.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(x=>e.jsxs("option",{value:x.id,children:[x.name,x.detail?` (${x.detail})`:"",x.active?"":" — inactive"]},x.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{b(!g),h("")},children:g?"Choose from synced list":"Enter an ID manually"})]})}function Fg({projectId:t,projectName:s}){const n=vn(),[a,r]=l.useState(null),[o,i]=l.useState(null),[d,c]=l.useState(!1),[h,u]=l.useState(""),[m,b]=l.useState(null),[g,f]=l.useState(!1),[x,y]=l.useState(!1),[P,S]=l.useState(""),[q,T]=l.useState(""),[v,j]=l.useState(""),[N,k]=l.useState(""),[E,O]=l.useState(""),[Z,U]=l.useState(!1),[F,z]=l.useState(jo),[V,te]=l.useState(null),Y=l.useRef(null),A=Ie({...qd({client:Q,path:{name:s}}),staleTime:dn}),ee=Ie({...Ed({client:Q,path:{name:s}}),staleTime:dn}),_=Ie({...Dd({client:Q,path:{name:s}}),staleTime:dn}),B=Ie({...Od({client:Q,path:{name:s}}),staleTime:dn}),w=B.data,H=Ie({...Fd({client:Q,path:{name:s},query:{limit:5}}),staleTime:dn}),se=Ie({...Gd({client:Q,path:{name:s},query:{limit:5}}),staleTime:dn}),oe=_.data??[],ye=(V?oe.find(L=>L.id===V)??null:null)??(oe.length===1?oe[0]??null:null),W=oe.length>1&&!ye,ue=Ie({...Kd({client:Q,path:{name:s,contractId:ye?.id??""}}),enabled:!!ye,staleTime:dn}),ve=Ie({..._d({client:Q,path:{name:s}}),enabled:m==="google-ads"&&A.data?.connected===!0,staleTime:0}),J=Ie({...Ud({client:Q,path:{name:s}}),enabled:m==="gtm"&&ee.data?.connected===!0,staleTime:0}),me=Ie({...Bd({client:Q,path:{name:s,accountId:v}}),enabled:m==="gtm"&&!!v,staleTime:0}),K=Ie({...Vd({client:Q,path:{name:s,accountId:v,containerId:N}}),enabled:m==="gtm"&&!!v&&!!N,staleTime:0}),xe=At(zd({client:Q})),we=At(Qd({client:Q})),Se=At(Hd({client:Q})),Ze=At(Wd({client:Q})),Be=At(Yd({client:Q})),Fe=At(Jd({client:Q})),et=At(Xd({client:Q})),Me=At(Zd({client:Q})),D=At(eu({client:Q}));l.useEffect(()=>{if(m!=="google-ads"||g||!A.isSuccess)return;const L=A.data.connection?.selection;S(L?.customerId??""),T(L?.loginCustomerId??""),f(!0)},[g,A.data,A.isSuccess,m]),l.useEffect(()=>{if(m!=="gtm"||x||!ee.isSuccess)return;const L=ee.data.selection;j(L?.accountId??""),k(L?.containerId??""),O(L?.workspaceId??""),y(!0)},[x,ee.data,ee.isSuccess,m]),l.useEffect(()=>{!V||!_.data||_.data.some(L=>L.id===V)||te(null)},[_.data,V]);const $e=l.useMemo(()=>{const L=H.data?.snapshots??[],fe=se.data?.snapshots??[],nt=[...L.map(mt=>({id:mt.id,provider:"google-ads",kind:mt.kind,capturedAt:mt.capturedAt})),...fe.map(mt=>({id:mt.id,provider:"gtm",kind:mt.kind,capturedAt:mt.capturedAt}))].sort((mt,Ls)=>Ls.capturedAt.localeCompare(mt.capturedAt)).slice(0,5),jt=[],ns=ue.data?.googleAdsSnapshot,_e=ue.data?.gtmSnapshot;return ns&&jt.push({id:ns.id,provider:"google-ads",kind:ns.kind,capturedAt:ns.capturedAt}),_e&&jt.push({id:_e.id,provider:"gtm",kind:_e.kind,capturedAt:_e.capturedAt}),{contract:ue.data?.assessment.contract??ye,assessment:ue.data?.assessment??null,contractSelectionRequired:W,assessmentState:ye?ue.isError?"unavailable":ue.isLoading?"loading":void 0:void 0,assessmentError:ue.isError?bt(ue.error):null,googleAds:qg(A.data,No(H.data?.total??0,H.isLoading,H.isError,H.error),A.isError),gtm:Dg(ee.data,No(se.data?.total??0,se.isLoading,se.isError,se.error),ee.isError),snapshots:nt,assessmentEvidenceSnapshots:jt}},[ye,W,H.data,H.error,H.isError,H.isLoading,A.data,A.isError,se.data,se.error,se.isError,se.isLoading,ee.data,ee.isError,ue.data,ue.error,ue.isError,ue.isLoading]),R=l.useSyncExternalStore(rl,Ea,Ea),ge=Object.values(R.runs).some(L=>L.projectId===t&&(L.kind===Ws["google-ads-sync"]||L.kind===Ws["gtm-sync"])),Ee=xe.isPending||we.isPending||Se.isPending||Ze.isPending||Be.isPending||Fe.isPending||et.isPending||Me.isPending||D.isPending||ge;async function Qe(){await Promise.all([A.refetch(),ee.refetch(),_.refetch(),H.refetch(),se.refetch(),B.refetch(),ye?ue.refetch():Promise.resolve()])}async function Ge(L){await Qe();for(let fe=0;fe<10&&!L();fe+=1)await new Promise(nt=>setTimeout(nt,1500)),await Qe()}function he(){const L=document.activeElement;Y.current=L instanceof HTMLElement?L:null}function ht(L){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(L);return}globalThis.setTimeout(L,0)}function Ke(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function De(L){if(!L)return;!L.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!L.hasAttribute("tabindex")&&(L.tabIndex=-1),L.focus({preventScroll:!0})}function St(L,fe=L){const nt=document.getElementById(L);nt instanceof HTMLDetailsElement&&(nt.open=!0);const jt=nt?.scrollIntoView;typeof jt=="function"&&jt.call(nt,{behavior:Ke()?"auto":"smooth",block:"start"}),De(document.getElementById(fe)??nt)}function Ye(L,fe){he(),ht(()=>St(L,fe))}function Ce(){const L=Y.current;Y.current=null,L&&ht(()=>{L.isConnected&&L.focus({preventScroll:!0})})}function rt(){r(null),c(!1),Ce()}function pt(){r(null),b(null),Ce()}function Mt(){r(null),U(!1),Ce()}function qe(){r(null),b(null),c(!0),Ye("google-ads-connect-panel","google-ads-connect-title")}function C(){r(null),S(""),T(""),f(!1),b("google-ads"),c(!1),Ye("google-ads-selection-panel","google-ads-selection-title")}function Re(){r(null),j(""),k(""),O(""),y(!1),b("gtm"),c(!1),Ye("gtm-selection-panel","gtm-selection-title")}function Ne(){r(null),U(!0),Ye("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Ve(L,fe){al({id:L.id,projectId:L.projectId,kind:L.kind,projectLabel:s,sourceAction:fe}),Te({title:fe==="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:${L.id}`,dedupeMode:"replace"})}async function gt(){bs(n),r(null);try{const L=await xe.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});u(""),c(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),wo(L.authorizationUrl,()=>{Qe(),i(null),Ce()})}catch(L){r(bt(L))}}async function tt(){bs(n),r(null);try{const L=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."),wo(L.authorizationUrl,()=>{Qe(),i(null),Ce()})}catch(L){r(bt(L))}}async function Pt(){if(bs(n),!P){r("Select a Google Ads customer before saving.");return}r(null);try{await Se.mutateAsync({path:{name:s},body:{customerId:P,...q.trim()?{loginCustomerId:q.trim()}:{}}}),b(null),Ce(),await Ge(()=>A.data?.selectedCustomer!=null)}catch(L){r(bt(L))}}async function We(){if(bs(n),!v||!N){r("Select a Tag Manager account and container before saving.");return}r(null);try{await Ze.mutateAsync({path:{name:s},body:{accountId:v,containerId:N,...E?{workspaceId:E}:{}}}),b(null),Ce(),await Ge(()=>ee.data?.status==="connected")}catch(L){r(bt(L))}}async function X(){bs(n),r(null),await et.mutateAsync({path:{name:s}}),b(null),c(!1),S(""),T(""),f(!1),i(null),await Qe(),Te({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),Y.current=null,ht(()=>De(document.getElementById("conversion-integrity-title")))}async function Le(){bs(n),r(null),await Me.mutateAsync({path:{name:s}}),b(null),j(""),k(""),O(""),y(!1),i(null),await Qe(),Te({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),Y.current=null,ht(()=>De(document.getElementById("conversion-integrity-title")))}async function Ae(){bs(n),r(null);try{const L=await Be.mutateAsync({path:{name:s}});Ve(L,"google-ads-sync")}catch(L){r(bt(L))}}async function ke(){bs(n),r(null);try{const L=await Fe.mutateAsync({path:{name:s}});Ve(L,"gtm-sync")}catch(L){r(bt(L))}}async function Wt(){bs(n),r(null);try{const L=await Promise.allSettled([Be.mutateAsync({path:{name:s}}),Fe.mutateAsync({path:{name:s}})]),[fe,nt]=L;fe.status==="fulfilled"&&Ve(fe.value,"google-ads-sync"),nt.status==="fulfilled"&&Ve(nt.value,"gtm-sync");const jt=L.find(ns=>ns.status==="rejected");if(jt?.status==="rejected")throw jt.reason}catch(L){r(bt(L))}}async function Yt(){bs(n);const L=A.data?.connection?.selection.customerId,fe=ee.data?.selection;if(!L||!fe?.accountId||!fe.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const nt=await D.mutateAsync({path:{name:s},body:Og(F,L,{accountId:fe.accountId,containerId:fe.containerId})});z(jo),U(!1),Ce(),(await _.refetch()).data?.some(ns=>ns.id===nt.id)&&te(nt.id)}catch(nt){r(bt(nt))}}function Gt(L){switch(L){case"connect-google-ads":qe();return;case"connect-gtm":he(),tt();return;case"select-google-ads":C();return;case"select-gtm":Re();return;case"sync-google-ads":Ae();return;case"sync-gtm":ke();return;case"sync-static-evidence":Wt();return;case"declare-contract":Ne();return;case"review-findings":Ye("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":Ye("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Qe();return;case"select-contract":Ye("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ue.refetch();return;case"waiting-for-integrity":return}}const ft=ve.data?.customers??[],it=J.data?.accounts??[],Kt=me.data?.containers??[],ts=K.data?.workspaces??[],_t=!!P&&!ft.some(L=>L.customerId===P),Ut=!!v&&!it.some(L=>L.id===v),dt=!!N&&!Kt.some(L=>L.id===N),ss=!!E&&!ts.some(L=>L.id===E),Je=_t&&ve.isSuccess&&ve.data.truncated===!1,Lt=Ut&&J.isSuccess&&J.data.truncated===!1,Bt=dt&&me.isSuccess&&me.data.truncated===!1,ps=ss&&K.isSuccess&&K.data.truncated===!1,ms=Lt||Bt||ps,Vt=Lt?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Bt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":ps?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,gs=ka(Je,ve.data,ve.isError),Jt=ka(Lt,J.data,J.isError),vt=ka(Bt,me.data,me.isError),Xt=ka(ps,K.data,K.isError),yt=ve.isError?bt(ve.error):null,Zt=J.isError?bt(J.error):me.isError?bt(me.error):K.isError?bt(K.error):null,fs=m==="google-ads"?yt:m==="gtm"?Zt:null,G=Ca("customer",ve.data,ft.length),ae=Ca("account",J.data,it.length),be=Ca("container",me.data,Kt.length),le=Ca("draft workspace",K.data,ts.length),je=J.isError||me.isError||K.isError&&!!E,Oe=d||m!==null||Z;function ut(){ve.refetch()}function ot(){if(J.isError){J.refetch();return}if(me.isError){me.refetch();return}K.isError&&K.refetch()}return A.isLoading||ee.isLoading||_.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(L=>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"})]},L))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):_.isError&&!_.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: ",bt(_.error)]}),e.jsx(I,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{_.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Lg,{workspace:$e,onPrimaryAction:Gt,actionPending:Ee,actionError:Oe?null:a,contracts:oe,selectedContractId:ye?.id??null,onSelectContract:L=>te(L||null),contractError:_.isError?bt(_.error):null,onRetryContracts:()=>{_.refetch()},onRetryEvidence:()=>{Promise.all([H.refetch(),se.refetch()])},onChangeGoogleAdsSelection:C,onChangeGtmSelection:Re,onAddContract:()=>Gt("declare-contract")}),o?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:o}):null,d?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:He(async L=>{L.preventDefault(),await gt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:os,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:L=>u(L.target.value),className:It,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(ze,{type:"submit",disabled:xe.isPending,children:xe.isPending?"Starting…":"Continue to Google"}),e.jsx(I,{type:"button",variant:"outline",onClick:rt,children:"Cancel"})]})]})]}):null,m==="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"})]})}),fs?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:fs}),e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:ut,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Je?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(Aa,{id:"google-ads-customer",label:"Customer account",value:P,onChange:L=>{f(!0),S(L);const fe=ft.find(nt=>nt.customerId===L);T(fe?.parentCustomerId??"")},disabled:ve.isLoading,children:[e.jsx("option",{value:"",children:ve.isLoading?"Loading accessible customers…":"Select a customer"}),_t?e.jsxs("option",{value:P,disabled:Je,children:["Saved customer ",P," (",gs,")"]}):null,ft.map(L=>e.jsx("option",{value:L.customerId,children:L.descriptiveName??`Customer ${L.customerId}`},L.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:os,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:It,value:q,onChange:L=>{f(!0),T(L.target.value)},placeholder:"Use only when a manager context is required"})]})]}),G?e.jsx("p",{role:"status",className:`mt-3 text-sm ${ve.data?.truncated?"text-caution":"text-secondary"}`,children:G}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(ze,{type:"button",disabled:Se.isPending||ve.isLoading||ve.isError||Je||!P,onClick:He(Pt),children:Se.isPending?"Saving…":"Save customer selection"}),e.jsx(I,{type:"button",variant:"outline",onClick:pt,children:"Cancel"})]}),A.data?.connected?e.jsx(So,{providerLabel:"Google Ads",disabled:Ee,onDisconnect:X}):null]}):null,m==="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"})]})}),fs?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:fs}),e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:ot,children:J.isError?"Retry account list":me.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Vt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Vt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Aa,{id:"gtm-account",label:"Account",value:v,onChange:L=>{y(!0),L!==v&&(k(""),O("")),j(L)},disabled:J.isLoading,children:[e.jsx("option",{value:"",children:J.isLoading?"Loading accounts…":"Select an account"}),Ut?e.jsxs("option",{value:v,disabled:Lt,children:["Saved account ",v," (",Jt,")"]}):null,it.map(L=>e.jsx("option",{value:L.id,children:L.name},L.id))]}),e.jsxs(Aa,{id:"gtm-container",label:"Container",value:N,onChange:L=>{y(!0),L!==N&&O(""),k(L)},disabled:!v||me.isLoading,children:[e.jsx("option",{value:"",children:me.isLoading?"Loading containers…":"Select a container"}),dt?e.jsxs("option",{value:N,disabled:Bt,children:["Saved container ",N," (",vt,")"]}):null,Kt.map(L=>e.jsx("option",{value:L.id,children:L.name},L.id))]}),e.jsxs(Aa,{id:"gtm-workspace",label:"Draft workspace (optional)",value:E,onChange:L=>{y(!0),O(L)},disabled:!N||K.isLoading,children:[e.jsx("option",{value:"",children:K.isLoading?"Loading workspaces…":"No draft workspace"}),ss?e.jsxs("option",{value:E,disabled:ps,children:["Saved draft workspace ",E," (",Xt,")"]}):null,ts.map(L=>e.jsx("option",{value:L.id,children:L.name},L.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[ae?e.jsx("p",{role:"status",className:J.data?.truncated?"text-caution":"text-secondary",children:ae}):null,be?e.jsx("p",{role:"status",className:me.data?.truncated?"text-caution":"text-secondary",children:be}):null,le?e.jsx("p",{role:"status",className:K.data?.truncated?"text-caution":"text-secondary",children:le}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(ze,{type:"button",disabled:Ze.isPending||J.isLoading||me.isLoading||K.isLoading&&!!E||je||ms||!v||!N,onClick:He(We),children:Ze.isPending?"Saving…":"Save container selection"}),e.jsx(I,{type:"button",variant:"outline",onClick:pt,children:"Cancel"})]}),ee.data?.connected?e.jsx(So,{providerLabel:"Tag Manager",disabled:Ee,onDisconnect:Le}):null]}):null,Z?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:He(async L=>{L.preventDefault(),await Yt()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:os,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:It,value:F.name,onChange:L=>z(fe=>({...fe,name:L.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:os,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:It,value:F.eventName,onChange:L=>z(fe=>({...fe,eventName:L.target.value})),placeholder:"booking_complete"})]}),e.jsx(Co,{id:"contract-conversion-action",label:"Google Ads conversion action",options:w?.googleAds.conversionActions??[],synced:w?.googleAds.syncedAt!=null,loading:B.isLoading,failed:B.isError,onRetry:()=>{B.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:F.conversionActionId,onChange:L=>z(fe=>({...fe,conversionActionId:L}))}),e.jsx(Co,{id:"contract-gtm-tag",label:"Tag Manager tag",options:w?.gtm.tags??[],synced:w?.gtm.syncedAt!=null,loading:B.isLoading,failed:B.isError,onRetry:()=>{B.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:F.tagId,onChange:L=>z(fe=>({...fe,tagId:L}))})]}),e.jsxs("details",{className:"inline-disclosure mt-5 max-w-3xl",children:[e.jsx("summary",{children:"Additional matching rules"}),e.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-conversion-id",className:os,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:It,value:F.conversionId,onChange:L=>z(fe=>({...fe,conversionId:L.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:os,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:It,value:F.conversionLabel,onChange:L=>z(fe=>({...fe,conversionLabel:L.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:os,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:It,value:F.triggerIds,onChange:L=>z(fe=>({...fe,triggerIds:L.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:os,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:It,value:F.variableIds,onChange:L=>z(fe=>({...fe,variableIds:L.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:os,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:It,value:F.campaignIds,onChange:L=>z(fe=>({...fe,campaignIds:L.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:os,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:It,value:F.productionHosts,onChange:L=>z(fe=>({...fe,productionHosts:L.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(wn,{id:"contract-primary-action",checked:F.requirePrimaryAction,onChange:L=>z(fe=>({...fe,requirePrimaryAction:L})),children:"Google Ads action is primary"}),e.jsx(wn,{id:"contract-biddable-goal",checked:F.requireBiddableGoal,onChange:L=>z(fe=>({...fe,requireBiddableGoal:L})),children:"Google Ads goal is biddable"}),e.jsx(wn,{id:"contract-runtime-verification",checked:F.verificationRequired,onChange:L=>z(fe=>({...fe,verificationRequired:L})),children:"Runtime proof is required"}),e.jsx(wn,{id:"contract-transaction-id",checked:F.requireTransactionId,onChange:L=>z(fe=>({...fe,requireTransactionId:L})),children:"Transaction ID is required"}),e.jsx(wn,{id:"contract-value",checked:F.requireValue,onChange:L=>z(fe=>({...fe,requireValue:L})),children:"Conversion value is required"}),e.jsx(wn,{id:"contract-currency",checked:F.requireCurrency,onChange:L=>z(fe=>({...fe,requireCurrency:L})),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(ze,{type:"submit",disabled:D.isPending,children:D.isPending?"Saving…":"Save conversion contract"}),e.jsx(I,{type:"button",variant:"outline",onClick:Mt,children:"Cancel"})]})]})]}):null]})}const Gg=6e4,Kg=["7d","14d","30d"],mi="not available",_g='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%.',Ug="No Google Ads snapshot stored yet",Bg="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.",Vg="No closed days yet",zg="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.",Qg={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},Gs=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),Cr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Hl=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),Hg=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Sn(t,s){return t===null||!Number.isFinite(t)?mi:s===null?Hg.format(t/1e6):fh(t,s)}function kr(t){if(t===null||!Number.isFinite(t))return mi;const s=t*100;return s>0&&s<.1?"<0.1%":`${Hl.format(s)}%`}function Wg(t,s){if(t===null||!Number.isFinite(t))return`${mi} 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%":`${Hl.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function Yg(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function Jg(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function Xg(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 Zg({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=Ie({...tu({client:Q,path:{name:t},query:{window:s}}),staleTime:Gg}),i=o.data,d=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Ue,{text:_g})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Ft(i.startDate)," to ",Ft(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(za,{windows:Kg,value:s,onChange:n,label:"Google Ads time period"})]});if(o.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[d,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(v=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-20"}),e.jsx("div",{className:"skeleton-text-sm w-28"})]},v))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(o.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[d,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",bt(o.error)]}),e.jsx(I,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{o.refetch()},children:"Retry performance"})]});const{totals:c,daily:h,campaigns:u,comparison:m,comparisonUnavailableReason:b,source:g}=i;if(!g){const v=b==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[d,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:v?Vg:Ug}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:v?zg:Bg})]})]})}const f=g.currencyCode,x=g.campaignsInInventory>0&&g.campaignsQueried<g.campaignsInInventory?{queried:g.campaignsQueried,inInventory:g.campaignsInInventory}:null,y=c.costMicros>0&&c.conversions===0,P=[{key:"spend",comparable:!0,label:"Spend",value:Sn(c.costMicros,f),change:m?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:Cr.format(c.conversions),change:m?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:y?"no conversions":Sn(c.costPerConversionMicros,f),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:kr(c.conversionRate),change:m?.change.conversionRate??null,direction:"up-good",seriesKey:null}],S=[{key:"clicks",label:"Clicks",value:Gs.format(c.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:Gs.format(c.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:kr(c.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:Sn(c.cpcMicros,f),seriesKey:null}],q={costMicros:{label:"Spend",color:at[1],axisId:"spend",formatValue:v=>Sn(v,f)},conversions:{label:"Conversions",color:at[0],axisId:"conversions",formatValue:v=>Cr.format(v)},clicks:{label:"Clicks",color:at[2],axisId:"clicks",formatValue:v=>Gs.format(v)},impressions:{label:"Impressions",color:at[3],axisId:"impressions",formatValue:v=>Gs.format(v)}},T=[...a].map(v=>({dataKey:v,...q[v]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[d,x!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",Gs.format(x.queried)," of"," ",Gs.format(x.inInventory)," campaigns, so they are a subset of the account."]}):null,g.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,!m&&b==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:Qg["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:P.map(v=>{const j=v.seriesKey!==null&&a.has(v.seriesKey),N=j&&a.size===1,k=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[v.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:j?q[v.seriesKey].color:"var(--color-mono-600)"}}):null,v.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:v.value}),m&&v.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${Xg(v.change,v.direction)}`,children:Wg(v.change,m.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:v.comparable?`no prior ${s} period stored`:" "})]});return v.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:k},v.key):e.jsx("button",{type:"button","aria-pressed":j,disabled:N,onClick:()=>r(E=>{const O=new Set(E);return O.has(v.seriesKey)?O.delete(v.seriesKey):O.add(v.seriesKey),O.size===0?E:O}),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"} ${N?"cursor-default":""}`,children:k},v.key)})}),e.jsx("dl",{className:"mt-2 flex flex-wrap gap-x-6 gap-y-1 rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:S.map(v=>{const j=v.seriesKey!==null&&a.has(v.seriesKey),N=j&&a.size===1,k=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[v.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:j?q[v.seriesKey].color:"var(--color-mono-600)"}}):null,v.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:v.value})]});return v.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:k},v.key):e.jsx("button",{type:"button","aria-pressed":j,disabled:N,onClick:()=>r(E=>{const O=new Set(E);return O.has(v.seriesKey)?O.delete(v.seriesKey):O.add(v.seriesKey),O.size===0?E:O}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${N?"cursor-default":"hover:bg-surface-hover"}`,children:k},v.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(jl,{data:h,xKey:"date",series:T,xTickFormatter:bn,labelFormatter:Ft}),e.jsx("ul",{className:"sr-only",children:h.map(v=>e.jsxs("li",{children:[Ft(v.date),":"," ",T.map(j=>`${j.label} ${q[j.dataKey].formatValue(v[j.dataKey])}`).join(", "),v.origin==="filled"?", no delivery reported":""]},v.date))})]}),e.jsxs("div",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"By campaign"}),e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Campaign performance"})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads campaign performance for the selected window"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Campaign"}),e.jsx("th",{className:"text-left",children:"Status"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Clicks"}),e.jsx("th",{className:"text-right",children:"Spend"}),e.jsx("th",{className:"text-right",children:"Conversions"}),e.jsx("th",{className:"text-right",children:"CTR"}),e.jsx("th",{className:"text-right",children:"Cost / conv."})]})}),e.jsx("tbody",{children:u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):u.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:v.name??v.campaignId,children:v.name??e.jsx("span",{className:"font-mono text-secondary",children:v.campaignId})}),e.jsx("td",{children:e.jsx(ce,{tone:Yg(v.status),children:Jg(v.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Gs.format(v.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Gs.format(v.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Sn(v.totals.costMicros,f)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Cr.format(v.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:kr(v.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:v.totals.costMicros>0&&v.totals.conversions===0?e.jsx(ce,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:Sn(v.totals.costPerConversionMicros,f)})})]},v.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Qs(Ms(g.capturedAt))," · ","customer ",g.customerId," · ","latest closed day ",Ft(g.asOfDate),g.openDate?e.jsxs(e.Fragment,{children:[" · ",Ft(g.openDate)," still open, excluded"]}):null,g.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",g.timeZone]}):null]})]})]})}const Ar=20,Ps=50,ef=50,tf=50;function hi(t){return t==="viewer"}function xi(t){return t?.status==="unavailable"}function Wl(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Yl(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 Pa(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 sf(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 Pr(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 ko(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Ao(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 Ra(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 Zr(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Rr(t){return Zr(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ei({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[o,i]=l.useState(""),[d,c]=l.useState(!1),h=o.trim().toLocaleLowerCase(),u=h?t.filter(f=>f.label.toLocaleLowerCase().includes(h)):t,m=d?u:u.slice(0,ef),b=m.length<u.length;function g(){const f=new Set([...s,...m.map(x=>x.id)]);n(t.filter(x=>f.has(x.id)).map(x=>x.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:f=>i(f.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(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:m.length===0,onClick:g,children:"Select all shown"}),e.jsx(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),u.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",m.length," of ",u.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:m.map(f=>{const x=s.includes(f.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 ${f.label}`,checked:x,type:"checkbox",onChange:y=>n(Wl(s,f.id,y.currentTarget.checked))}),e.jsx("span",{children:f.label})]}),f.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[f.urlCount," URLs"]})]},f.id)})}),b?e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>c(!0),children:"Show all Properties"}):null]})]})}function pi(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(ce,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function gi({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function nf({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,i]=l.useState(null),d=t.preview,c=d?.counts.needsAttention??0,h=d?.rows.filter(N=>N.status==="matched")??[],u=d?.rows??[],m=u.filter(N=>N.status!=="matched"),b=Math.max(1,Math.ceil(u.length/Ps)),g=Math.min(s,b-1),f=u.slice(g*Ps,(g+1)*Ps),x=Math.max(1,Math.ceil(m.length/Ps)),y=Math.min(a,x-1),P=m.slice(y*Ps,(y+1)*Ps),S=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,q=h.length>0&&!t.isApplying,T=d!==null&&o===d.previewChecksum,v=m.length>0&&y===x-1;l.useEffect(()=>{n(0),r(0),i(null)},[d?.previewChecksum]);async function j(N){if(N)try{t.onCsvChange(await N.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:N=>{j(N.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:N=>t.onCsvChange(N.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(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!S,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),d?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[d.counts.matchedRows," matched · ",d.counts.groupsReady," group",d.counts.groupsReady===1?"":"s"," ready",c>0?` · ${c} need${c===1?"s":""} attention`:""]}),d.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:d.groupChanges.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:N.label}),e.jsx("td",{className:"text-secondary",children:N.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:N.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[N.addedTargetKeys.length,N.unchangedTargetKeys.length>0?` · ${N.unchangedTargetKeys.length} already members`:""]})]},N.groupKey))})]})}):null,d.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",d.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:f.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:N.dataRow}),e.jsx("td",{className:"text-heading",children:N.property}),e.jsx("td",{className:"text-secondary",children:N.group}),e.jsxs("td",{children:[e.jsx(ce,{tone:ko(N.status),children:Ao(N.status)}),Ra(N)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Ra(N)}):null]})]},N.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",g+1," of ",b," · ",d.rows.length," rows"]}),e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:g===0,onClick:()=>n(N=>Math.max(0,N-1)),children:"Previous 50 rows"}),e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:g===b-1,onClick:()=>n(N=>Math.min(b-1,N+1)),children:"Next 50 rows"})]})]}):null,c>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",c," row",c===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:P.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:N.dataRow}),e.jsx("td",{className:"text-heading",children:N.property}),e.jsx("td",{className:"text-secondary",children:N.group}),e.jsxs("td",{children:[e.jsx(ce,{tone:ko(N.status),children:Ao(N.status)}),Ra(N)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Ra(N)}):null]})]},N.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 ",y+1," of ",x]}),e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:y===0,onClick:()=>r(N=>Math.max(0,N-1)),children:"Previous 50 exceptions"}),e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:y===x-1,onClick:()=>r(N=>Math.min(x-1,N+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:T,disabled:t.isApplying||!v,onChange:N=>i(N.currentTarget.checked?d.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",c," row",c===1?"":"s"," will be skipped."]}),e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!q||!T,onClick:()=>{t.onApply(h.map(N=>N.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(I,{type:"button",className:"mt-3 min-h-11",disabled:!q,onClick:()=>{t.onApply(h.map(N=>N.dataRow))},children:t.isApplying?"Creating groups…":`Create ${d.counts.groupsReady} group${d.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const af="—";function rf({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:o=!1,isBusy:i=!1,canContinue:d=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:h,onClearQueryAssignments:u,onRemoveQuery:m,onCreateQueries:b,onCreateAndPairQuestions:g,isCreatingQueries:f=!1,createQueriesError:x=null,onManageProjectQueries:y,groups:P,audience:S,onAudienceChange:q,assignmentImpact:T=null,isPreviewingAssignmentImpact:v=!1,assignmentImpactError:j=null,onRetryAssignmentImpact:N,assignmentNotice:k=null,onReplaceAssignments:E,isReplacingAssignments:O=!1,onBack:Z,onContinue:U}){const[F,z]=l.useState(""),[V,te]=l.useState(!1),[Y,A]=l.useState(!1),[ee,_]=l.useState(""),[B,w]=l.useState(""),[H,se]=l.useState(null);if(xi(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(gi,{message:s.message})});const oe=hi(t),ne=S,ye=q,W=Pa(ne,n,P),ue=W.length,ve=ue>0&&r.length>0&&!o&&!i&&!v&&T!==null&&j===null,J=u??m,me=F.trim().toLocaleLowerCase(),K=me?a.filter(R=>Rr(R).toLocaleLowerCase().includes(me)):a,xe=K.filter(R=>(R.propertyIds?.length??0)===0),we=Y?xe:K,Se=V?we:we.slice(0,tf),Ze=Se.filter(R=>!Zr(R)),Be=[...new Set(ee.split(`
|
|
4
|
-
`).map(R=>R.trim()).filter(Boolean))],Fe=[...B.matchAll(/\{([a-z][\w-]*)\}/gi)].map(R=>R[1]),et=n.filter(R=>W.includes(R.id)),Me=Fe.length===0||B.trim()===""?[]:et.map(R=>({propertyId:R.id,text:Fe.reduce((ge,Ee)=>ge.replaceAll(`{${Ee}}`,R.label),B.trim())})),D=[...new Set(Me.map(R=>R.text))];function $e(){const R=new Set([...r,...Ze.map(ge=>ge.id)]);c(a.filter(ge=>R.has(ge.id)).map(ge=>ge.id))}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-queries-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-queries-title",children:"Queries"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose queries, then apply them to Properties."})]})}),oe?e.jsx(pi,{}):null,oe?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:ne.kind==="all"?"all":ne.kind==="specific"?"specific":`group:${ne.groupIds[0]??""}`,onChange:R=>{const ge=R.currentTarget.value;ge==="all"?ye({kind:"all"}):ge==="specific"?ye({kind:"specific",propertyIds:[]}):ge.startsWith("group:")&&ye({kind:"groups",groupIds:[ge.slice(6)]})},className:"block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsxs("option",{value:"all",children:["All Properties · ",n.length]}),P.length>0?e.jsx("optgroup",{label:"Groups",children:P.map(R=>{const ge=Pa({kind:"groups",groupIds:[R.id]},n,P).length;return e.jsx("option",{value:`group:${R.id}`,disabled:ge===0,children:Pr(R,n)},R.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),ne.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:ne.groupIds.map(R=>{const ge=P.find(Ee=>Ee.id===R);return ge?e.jsxs("span",{className:"inline-flex min-h-11 items-center gap-1 rounded-md border border-default bg-surface px-2 text-sm text-primary",children:[Pr(ge,n),e.jsx("button",{type:"button","aria-label":`Remove ${ge.name}`,className:"-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>{const Ee=ne.groupIds.filter(Qe=>Qe!==ge.id);ye(Ee.length>0?{kind:"groups",groupIds:Ee}:{kind:"all"})},children:"×"})]},ge.id):null})}),P.some(R=>!ne.groupIds.includes(R.id)&&Pa({kind:"groups",groupIds:[R.id]},n,P).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:R=>{R.currentTarget.value&&ye({kind:"groups",groupIds:[...ne.groupIds,R.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"}),P.filter(R=>!ne.groupIds.includes(R.id)).map(R=>{const ge=Pa({kind:"groups",groupIds:[R.id]},n,P).length;return e.jsx("option",{value:R.id,disabled:ge===0,children:Pr(R,n)},R.id)})]})]}):null,ue===0?e.jsx("p",{role:"alert",className:"text-sm text-caution",children:"This group has no included Properties. Add Properties to the group, then try again."}):null]}):null,ne.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(ei,{legend:"Specific Properties",properties:n,selectedPropertyIds:ne.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:R=>{ye({kind:"specific",propertyIds:R})}})}):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."})]}),oe||!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:ee,onChange:R=>_(R.currentTarget.value),placeholder:`best apartments in dallas
|
|
5
|
-
luxury apartments atlanta
|
|
6
|
-
pet friendly apartments austin`}),x?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:x}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Be.length===0||f||i,onClick:()=>{Promise.resolve(b(Be)).then(()=>_(""),()=>{})},children:f?"Adding…":`Add ${Be.length||""} ${Be.length===1?"query":"queries"}`.replace(" "," ")}),y?e.jsx(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:y,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:B,onChange:R=>w(R.target.value),placeholder:"apartments near {property}"}),B.trim()===""?null:Fe.length===0?e.jsxs("p",{className:"mt-2 text-sm text-caution",children:["Add ","{property}"," to the pattern, or use the box above for a single query."]}):et.length===0?e.jsx("p",{className:"mt-2 text-sm text-caution",children:"Select at least one Property to write queries for."}):e.jsxs("div",{className:"mt-2 rounded-md border border-base bg-bg-elevated p-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:[D.length," ",D.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:D.slice(0,3).map(R=>e.jsx("li",{className:"text-sm text-strong",children:R},R))}),D.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",D.length-3," more"]}):null]}),e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Me.length===0||f||i||!g,onClick:()=>{g&&Promise.resolve(g(Me)).then(()=>w(""),()=>{})},children:f?"Adding…":`Add ${Me.length||""} ${Me.length===1?"query":"queries"}`.replace(" "," ")}),Me.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"," ",Me.length," assignment",Me.length===1?"":"s","."]}):null]})]})]}),oe?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(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:Ze.length===0,onClick:$e,children:"Select all shown queries"}),e.jsx(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>c([]),children:"Clear query selection"}),e.jsx(I,{type:"button",size:"sm",className:"min-h-11",disabled:!ve,onClick:()=>{h({queryIds:r,propertyIds:W,...ne.kind==="groups"?{groupIds:ne.groupIds}:{}})},children:o?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${sf(ne,P,ue)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[v?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,T?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",T.assignmentCount," Property assignment",T.assignmentCount===1?"":"s"," · ",T.addedAssignments," new, ",T.alreadyPresentAssignments," already assigned"," · ",T.fullRunProviderCalls," provider request",T.fullRunProviderCalls===1?"":"s"," per full run"," · ",T.addedProviderCalls," new",ne.kind==="groups"?` · ${T.resolvedPropertyCount} unique ${T.resolvedPropertyCount===1?"Property":"Properties"}${T.overlapCount>0?`, ${T.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}),N?e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:N,children:"Retry impact"}):null,Z?e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:Z,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",ue," Properties = ",r.length*ue," assignments"]})]}),k?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:k}):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:F,onChange:R=>{z(R.currentTarget.value),te(!1)},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400",placeholder:"Query text"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:["Showing ",Se.length," of ",we.length," queries,"," ",K.length-xe.length," of ",K.length," applied"]}),oe||xe.length===0?null:e.jsx(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{A(R=>!R),te(!1)},children:Y?"Show all queries":`Show the ${xe.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:[oe?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),oe?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:Se.map(R=>{const ge=Zr(R),Ee=Rr(R),Qe=r.includes(R.id),Ge=(R.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[oe?null:ge?e.jsx("td",{"aria-hidden":"true"}):e.jsx("td",{className:"p-0",children:e.jsx("label",{className:"flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{"aria-label":`Select query ${Ee}`,checked:Qe,type:"checkbox",onChange:he=>c(Wl(r,R.id,he.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:Ee})}),e.jsx("td",{className:"text-secondary",children:Yl(R.propertyIds??[],n)}),oe?null:e.jsx("td",{className:"text-right",children:Ge?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[E?e.jsx(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||O,onClick:()=>se({queryId:R.id,propertyIds:[...R.propertyIds??[]]}),"aria-label":`Replace query assignments for ${Ee}`,children:"Replace assignments"}):null,e.jsx(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{J(R.id)},"aria-label":`Clear query assignments for ${Ee}`,children:"Clear assignments"})]}):null})]},R.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,oe||!H?null:(()=>{const R=a.find(Qe=>Qe.id===H.queryId),ge=R?Rr(R):"this query",Ee=H.propertyIds.filter(Qe=>n.some(Ge=>Ge.id===Qe));return e.jsxs("section",{"aria-labelledby":"advanced-measurement-replace-assignments-title",className:"border-y border-default py-4",children:[e.jsx("h4",{id:"advanced-measurement-replace-assignments-title",className:"text-sm font-medium text-heading",children:"Replace assigned Properties"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:["This replaces every Property assigned to “",ge,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(ei,{legend:"Properties for this query",properties:n,selectedPropertyIds:Ee,onSelectedPropertyIdsChange:Qe=>se(Ge=>Ge&&{...Ge,propertyIds:[...Qe]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:O||i,onClick:()=>se(null),children:"Keep current assignments"}),e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ee.length===0||O||i||!E,onClick:()=>{E&&Promise.resolve(E({queryId:H.queryId,propertyIds:Ee}))},children:O?"Replacing assignments…":`Replace with ${Ee.length} ${Ee.length===1?"Property":"Properties"}`})]})]})})(),Se.length<we.length?e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>te(!0),children:"Show all queries"}):null,oe?null:e.jsxs(e.Fragment,{children:[d?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${Z?"justify-between":"justify-end"}`,children:[Z?e.jsx(I,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:Z,children:"Back"}):null,e.jsx(I,{type:"button",variant:ve?"outline":"default",className:"min-h-11",disabled:!d||i,onClick:U,children:"Continue"})]})]})]})}function of({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:o=!1,onGroupDraftChange:i,onSaveGroup:d,onEditGroup:c,onRemoveGroup:h,onClearGroupDraft:u,membershipImport:m,onBack:b,onContinue:g}){if(xi(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(gi,{message:s.message})});const f=hi(t),x=r.name.trim().length>0&&r.propertyIds.length>0&&!o,y=n.filter(T=>r.propertyIds.includes(T.id)).length,P=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,S=!f&&(c!==void 0||h!==void 0);function q(){if(u){u();return}i({name:"",propertyIds:[],competitorDomains:""})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-groups-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-groups-title",children:"Groups"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Use groups to assign queries by market and compare competitors."})]})}),f?e.jsx(pi,{}):null,f||!m?null:e.jsx(nf,{value:m}),f?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:T=>i({...r,name:T.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:[y," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(ei,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:T=>i({...r,propertyIds:T})})})]}),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:T=>i({...r,competitorDomains:T.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!x,onClick:()=>{d(r)},children:o?"Saving group…":"Save group"}),e.jsx(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!P,onClick:q,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."})]}),P?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"}),S?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(T=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:T.name}),e.jsx("td",{className:"text-secondary",children:Yl(T.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:T.competitors.length>0?T.competitors.join(", "):"None"}),S?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[c?e.jsx(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${T.name}`,onClick:()=>c(T),children:"Edit"}):null,h?e.jsx(I,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${T.name}`,onClick:()=>{h(T.id)},children:"Remove"}):null]})}):null]},T.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,f?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${b?"justify-between":"justify-end"}`,children:[b?e.jsx(I,{type:"button",variant:"outline",className:"min-h-11",onClick:b,children:"Back"}):null,e.jsx(I,{type:"button",className:"min-h-11",disabled:P,onClick:g,children:a.length===0&&!P?"Continue without groups":"Continue"})]})]})}function lf({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:o,onReviewChanges:i,isReviewing:d=!1,canReviewChanges:c=!0,reviewedChanges:h,reviewChangesError:u,canPublish:m,isPublishing:b=!1,onPublish:g}){const[f,x]=l.useState(Ar),[y,P]=l.useState(Ar),[S,q]=l.useState(Ar);if(xi(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(gi,{message:s.message})});const T=hi(t),v=r?.items??[],j=r?.coverageItems??[],N=v.slice(0,f),k=j.slice(0,y),E=a.slice(0,S),O=i!==void 0,Z=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."})]})}),T?e.jsx(pi,{}):null,r?e.jsx("section",{"aria-labelledby":"advanced-measurement-sitemap-review-title",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:e.jsxs("div",{className:"max-w-2xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{id:"advanced-measurement-sitemap-review-title",className:"text-sm font-medium text-heading",children:"Sitemap changes need review"}),r.exceptionCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.exceptionCount," sitemap ",r.exceptionCount===1?"entry needs":"entries need"," review."]}):null,r.coverageReviewCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.coverageReviewCount," ",r.coverageReviewCount===1?"Property has":"Properties have"," URL coverage changes."]}):null]}),r.exceptionCount>0?e.jsxs("details",{className:"border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["URLs not added to Properties (",r.exceptionCount,")"]}),v.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:N.map(U=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:U.url}),e.jsx("p",{className:"mt-1 text-secondary",children:U.reason})]},`${U.url}-${U.reason}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected sitemap URLs before confirming."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",N.length," of ",v.length]}),N.length<v.length?e.jsx(I,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>x(U=>U+Ps),children:"Show next 50 URLs"}):null]})]}):null,T?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,")"]}),k.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[k.map(U=>e.jsxs("section",{"aria-label":`${U.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:U.property}),e.jsxs("div",{className:"mt-2 grid gap-3 text-sm md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Saved URLs"}),e.jsx("ul",{className:"mt-1 space-y-1",children:U.savedUrls.map(F=>e.jsx("li",{className:"break-all text-secondary",children:F},F))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),U.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:U.currentSitemapUrls.map(F=>e.jsx("li",{className:"break-all text-secondary",children:F},F))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},U.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",k.length," of ",j.length]}),k.length<j.length?e.jsx(I,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>P(U=>U+Ps),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(I,{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??af})]})})]})}),n.providerCalls===void 0?e.jsx("p",{className:"supporting-copy",children:"Review changes to see how many provider requests one run will make."}):null,n.assignments!==void 0&&n.assignments>n.queries?e.jsxs("p",{className:"supporting-copy",children:[n.queries," ",n.queries===1?"query":"queries"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a query aimed at a market is measured on every Property in it."]}):null,h?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:h.title}),h.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:h.items.map((U,F)=>e.jsx("li",{children:U},`${U}-${F}`))}):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(U=>e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-heading",children:U.title}),U.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:U.detail}):null]}),e.jsx(ce,{tone:U.tone??"caution",children:"Needs attention"})]},U.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",E.length," of ",a.length]}),E.length<a.length?e.jsx(I,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>q(U=>U+Ps),children:"Show next 50 exceptions"}):null]})]})]}),T?null:e.jsxs(e.Fragment,{children:[O&&u?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:u}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${o?"justify-between":"justify-end"}`,children:[o?e.jsx(I,{type:"button",variant:"outline",className:"min-h-11",onClick:o,children:"Back"}):null,i!==void 0&&!Z?e.jsx(I,{type:"button",className:"min-h-11",disabled:d||!c,onClick:()=>{i()},children:d?"Reviewing changes…":"Review changes"}):e.jsx(I,{type:"button",className:"min-h-11",disabled:!m||b,onClick:()=>{g()},children:b?"Publishing setup…":"Publish setup"})]})]})]})}const cf={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function df(t){return t.trim().toLocaleLowerCase()}function uf(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function mf({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 hf({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const o=!t||r==="reviewing",i=o||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function d(c,h){n({...s,[c]:h})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":r==="reviewing",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-import-heading",className:"text-lg font-semibold text-heading",children:"Import Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review sitemap entries before choosing the Properties to measure."})]}),t?null:e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm text-secondary",children:[e.jsx(ce,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:c=>{c.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:o,onChange:c=>d("sitemapUrl",c.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:o,onChange:c=>d("examplePropertyUrl",c.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:o,onChange:c=>d("preferredHost",c.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:o,onChange:c=>d("propertyPathPattern",c.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:o,onChange:c=>d("additionalHost",c.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:o,onChange:c=>d("additionalPathPattern",c.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:o,onChange:c=>d("excludedPaths",c.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(I,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function xf({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:o,onSelectedPropertyIdsChange:i,onContinue:d,isContinuing:c=!1,onRetryProperties:h,onReturnToImport:u,maxVisibleProperties:m,onShowAllProperties:b}){const g=df(a),f=s.filter(E=>uf(E,g)),x=Math.max(1,m??f.length),y=f.slice(0,x),P=new Set(o),S=s.filter(E=>P.has(E.id)).map(E=>E.id),q=y.length<f.length;function T(E){const O=new Set(E);i(s.filter(Z=>O.has(Z.id)).map(Z=>Z.id))}function v(E,O){if(!t||c)return;const Z=new Set(S);O?Z.add(E):Z.delete(E),T(Z)}function j(){!t||c||T([...S,...y.map(E=>E.id)])}function N(){!t||c||i([])}function k(){!t||c||S.length===0||d(S)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||c,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(I,{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(I,{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(I,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):null,n==="ready"&&s.length>0?e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:a,disabled:c,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(I,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:j,children:"Select all shown"}),e.jsx(I,{type:"button",variant:"ghost",size:"sm",disabled:c||S.length===0,onClick:N,children:"Clear selection"})]}):null]}),f.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(I,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:u,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",y.length," of ",f.length," Properties"]}),e.jsxs("p",{children:[S.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:y.map(E=>{const O=cf[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(mf,{property:E})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(ce,{tone:O.tone,children:O.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:S.includes(E.id),disabled:c,onChange:Z=>v(E.id,Z.target.checked),className:"size-6 accent-accent"})})}):null]},E.id)})})]})}),q&&b?e.jsx(I,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:c,onClick:b,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(I,{type:"button",variant:"ghost",disabled:c,onClick:u,children:"Back"}),e.jsx(I,{type:"button",disabled:c||S.length===0,onClick:k,children:c?"Saving Properties…":"Continue"})]}):null]}):null]})}function pf(t){return t.activeStep==="import"?e.jsx(hf,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(xf,{...t})}const gf=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function ff({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:o}){const i=l.useRef(null),d=l.useRef(null),c=l.useRef(null),h=l.useRef(null),u=l.useRef(!1),[m,b]=l.useState(!1);return l.useEffect(()=>{s||b(!1)},[s]),l.useEffect(()=>{const g=u.current;u.current=m,m?c.current?.focus():g&&h.current?.focus()},[m]),l.useEffect(()=>{const g=i.current;if(i.current=t,g===null||g===t)return;const f=d.current?.querySelector('h1, h2, h3, [role="heading"]');f&&(f.tabIndex=-1,f.focus())},[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 w-full sm:flex-1",children:[e.jsx("h2",{children:"Advanced measurement setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties and queries you want to measure."})]}),s?e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end",children:[e.jsx(ce,{tone:"caution",children:"Unpublished changes"}),n&&a?m?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(I,{ref:c,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>b(!1),children:"Keep editing"}),e.jsx(I,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(I,{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:gf.map(g=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===g.id?"step":void 0,onClick:()=>r(g.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===g.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:g.label}):e.jsx("span",{"aria-current":t===g.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===g.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:g.label})},g.id))})}),e.jsx("div",{ref:d,children:o})]})}function yf(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(pf,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(rf,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(of,{...t.groups,access:s}):"review"in t?e.jsx(lf,{...t.review,access:s}):null}function Ia(t){return e.jsx(ff,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:yf(t)})}function Jl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Et(t){return{"If-Match":t,"Idempotency-Key":Jl()}}function un(t){return t instanceof fn&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function is(t,s){return t instanceof fn?s:(t instanceof Error?t.message.trim():"")||s}function bf(t){const s="Could not calculate assignment impact.";if(!(t instanceof fn)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const vf={loadSetup:t=>xt(()=>wu({client:Q,path:{name:t}})),loadDraft:t=>xt(()=>Nu({client:Q,path:{name:t}})),createDraft:(t,s)=>xt(()=>ju({client:Q,path:{name:t},headers:{"Idempotency-Key":Jl()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>xt(()=>vu({client:Q,path:{name:t},headers:Et(s),body:n})),applySitemapSelection:(t,s,n,a)=>xt(()=>bu({client:Q,path:{name:t},headers:Et(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>xt(()=>yu({client:Q,path:{name:t},body:s})),applyAssignments:(t,s,n)=>xt(()=>fu({client:Q,path:{name:t},headers:Et(s),body:n})),replaceAssignments:(t,s,n)=>xt(()=>gu({client:Q,path:{name:t},headers:Et(s),body:n})),applyPairedAssignments:(t,s,n)=>xt(()=>pu({client:Q,path:{name:t},headers:Et(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>xt(()=>xu({client:Q,path:{name:t},headers:Et(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>xt(()=>hu({client:Q,path:{name:t},headers:Et(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>xt(()=>mu({client:Q,path:{name:t},headers:Et(s),body:{target:n}})),upsertGroup:(t,s,n)=>xt(()=>uu({client:Q,path:{name:t},headers:Et(s),body:{group:n}})),removeGroup:(t,s,n)=>xt(()=>du({client:Q,path:{name:t},headers:Et(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>xt(()=>cu({client:Q,path:{name:t},headers:Et(s),body:n})),removeCompetitor:(t,s,n,a)=>xt(()=>lu({client:Q,path:{name:t},headers:Et(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>xt(()=>ou({client:Q,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>xt(()=>iu({client:Q,path:{name:t},headers:Et(s),body:n})),compilePreview:t=>xt(()=>ru({client:Q,path:{name:t}})),diffPreview:t=>xt(()=>au({client:Q,path:{name:t}})),publish:(t,s,n)=>xt(()=>nu({client:Q,path:{name:t},headers:Et(s),body:n})),discard:(t,s)=>xt(()=>su({client:Q,path:{name:t},headers:Et(s)}))},Po={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},Vn={name:"",propertyIds:[],competitorDomains:""},Ro=50;function Wn(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function jf(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 Io(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 Nf(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,d=i.startsWith("*"),c=i.endsWith("*"),h=i.slice(d?1:0,c?-1:void 0).trim();if(!h)throw new Error("Ignored URL patterns must include text besides *.");const u=d&&c?"contains":d?"suffix":c?"prefix":"exact",m=`${u}:${h}`;n.has(m)||(n.add(m),s.push({kind:u,value:h}))}return s}function wf(t){const s=jf(t.sitemapUrl),n=t.examplePropertyUrl.trim()?Wn(t.examplePropertyUrl):null,a=Wn(t.preferredHost)??n??Wn(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=Wn(t.additionalHost),o=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(o!==i||o&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const d=Nf(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:Io(t)},...r?{aliases:[{host:r,pathTemplate:Io({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...d.length>0?{excludedSlugPatterns:d}:{}}}}function Sf(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 Cf(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 To(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function kf(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Ir(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function ti(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function $o(t){return Wn(t)}function Xl(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 Zl(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 ec(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function tc(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Af(t,s){const n=Xl(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 Pf(t,s){const n=Zl(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=tc(t.authoring,n.targetKeys[r]);return`${n.label} — ${o}`}return n.label}function Rf(t,s){const n=ec(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${tc(t.authoring,n.targetKey)} — ${a}`}function If(t,s){return s.path[0]==="identities"?"Project domain":Af(t,s)??Pf(t,s)??Rf(t,s)}function Mo(t,s,n){const a=ec(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 Tf(t,s){const n=If(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,Mo(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,Mo(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 Ta(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function sc(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 $f(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${Ta(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${Ta(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${Ta(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${Ta(n,"item")} need review.`:s}})()}${sc(a)}`}function Mf(t,s){const n=new Map;for(const a of t){const r=Tf(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:$f(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 $r(t,s,n){const a=Xl(n,t.path),r=Zl(n,t.path),o=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=o?n?.targets.find(u=>u.stableKey===o):void 0,d=a?.label??r?.label,c=sc(d?[d]:[]),h={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...h,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${c}`};case"excluded-target-has-assignments":return{...h,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${c}`};case"group-unknown-target":return{...h,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${c}`};case"measurement.discovery.proposed_new_target":{const u=Tr(a)??"the proposed Property";return{...h,title:"Review a new Property",detail:`Review ${u}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const u=Tr(a)??"the proposed Property",m=i?.label??"an existing Property";return{...h,title:"Review a moved Property",detail:`Review ${u}. It may be the same Property as ${m}.`}}case"measurement.discovery.rebind_ambiguous":{const u=Tr(a)??"the proposed Property",m=i?.label??"an existing Property";return{...h,title:"Choose an existing Property",detail:`Review ${u}. It may match ${m}; 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 Lf(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 vs(t){return[...new Set(t)]}function Vs(t){return vs(t).sort()}function qf(t,s,n){return t.kind==="groups"?{groupKeys:Vs(t.groupIds),queryIds:Vs(n)}:{targetKeys:Vs(t.kind==="all"?s:t.propertyIds),queryIds:Vs(n)}}function Ef(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 Lo(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function Df(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(Lo).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(Lo).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:ti(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function Of({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:o,canEdit:i=!0,onCreateQueries:d,onManageProjectQueries:c,onPublished:h,service:u=vf}){const[m,b]=l.useState(null),[g,f]=l.useState(null),[x,y]=l.useState("import"),[P,S]=l.useState(!0),[q,T]=l.useState(null),[v,j]=l.useState(null),[N,k]=l.useState([]),[E,O]=l.useState({...Po}),[Z,U]=l.useState("idle"),[F,z]=l.useState(""),[V,te]=l.useState(Ro),[Y,A]=l.useState([]),[ee,_]=l.useState([]),[B,w]=l.useState({kind:"all"}),[H,se]=l.useState(null),[oe,ne]=l.useState(null),[ye,W]=l.useState(!1),[ue,ve]=l.useState(null),[J,me]=l.useState(0),[K,xe]=l.useState(null),[we,Se]=l.useState({...Vn}),[Ze,Be]=l.useState(null),[Fe,et]=l.useState(""),[Me,D]=l.useState(null),[$e,R]=l.useState(!1),[ge,Ee]=l.useState(!1),[Qe,Ge]=l.useState(null),[he,ht]=l.useState(null),[Ke,De]=l.useState(null),[St,Ye]=l.useState(null),[Ce,rt]=l.useState(null),pt=l.useRef(0),Mt=l.useRef(0),qe=g?.draft??null,C=g?.etag??null,Re=l.useMemo(()=>!i&&o?{baseActiveRevision:o.revision,authoring:Df(o)}:null,[i,o]),Ne=qe??Re;async function Ve(G){const ae=++pt.current;S(!0),T(null);try{let[be,le]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);if(!le.draft&&G&&i&&(await u.createDraft(t,be.activeRevision),[be,le]=await Promise.all([u.loadSetup(t),u.loadDraft(t)])),ae!==pt.current)return;b(be),f(le),y(Sf(le.draft));const je=Ir(le.draft);A(je)}catch(be){if(ae!==pt.current)return;T(is(be,"Could not load advanced measurement setup."))}finally{ae===pt.current&&S(!1)}}l.useEffect(()=>(Ve(!0),()=>{pt.current+=1}),[t,i,u]),l.useEffect(()=>{!P&&!qe&&Re&&y("properties")},[qe,P,Re]);async function gt(){const G=await u.loadDraft(t);return f(G),G}async function tt(G){rt(null);try{const[ae,be]=await Promise.all([u.loadSetup(t),u.loadDraft(t)]);b(ae),f(be);const le=Ir(be.draft);A(le),y(je=>Cf(be.draft,je)),j(G)}catch(ae){j(is(ae,G))}}async function Pt(G,ae,be,le={}){const{preserveBusyAction:je=!1}=le;if(!i||!C||Ke&&!je)return null;je||De(G),j(null),rt(null);try{const Oe=await ae(C),ut=await gt();return k((Oe.warnings??[]).map((ot,ys)=>$r(ot,ys,ut.draft?.authoring))),ut}catch(Oe){return un(Oe)?await tt("This setup changed in another session. The latest draft is loaded; review your changes again."):j(is(Oe,be)),null}finally{je||De(null)}}const We=l.useMemo(()=>(Ne?.authoring.targets??[]).map(G=>{const ae=To(G);return{id:G.stableKey,name:G.label,url:ae[0]??"No URL",urls:ae,state:kf(G.status)}}),[Ne]),X=l.useMemo(()=>Ne?.authoring.targets.filter(G=>G.status==="included")??[],[Ne]),Le=l.useMemo(()=>X.map(G=>({id:G.stableKey,label:G.label,urlCount:To(G).length})),[X]),Ae=Ne?.authoring.assignments.length??0,ke=l.useMemo(()=>{if(!Ne)return[];const G=new Set(s.map(le=>le.id)),ae=s.map(le=>({id:le.id,text:le.query,source:"saved-project-queries",propertyIds:vs(Ne.authoring.assignments.filter(je=>je.queryId===le.id).map(je=>je.targetKey))})),be=vs(Ne.authoring.assignments.map(le=>le.queryId).filter(le=>!G.has(le))).map(le=>({id:le,source:"unavailable-tracked-query",state:"missing",propertyIds:vs(Ne.authoring.assignments.filter(je=>je.queryId===le).map(je=>je.targetKey))}));return[...ae,...be]},[s,Ne]),Wt=l.useMemo(()=>(Ne?.authoring.groups??[]).map(G=>({id:G.stableKey,name:G.label,propertyIds:G.targetKeys,competitors:G.competitors.map(ae=>ae.domain)})),[Ne]),Yt=l.useMemo(()=>{if(ee.length===0)return null;const G=qf(B,Le.map(be=>be.id),ee);return(G.groupKeys?.length??G.targetKeys?.length??0)>0?G:null},[B,Le,ee]),Gt=Yt?JSON.stringify(Yt):"";l.useEffect(()=>{const G=Yt,ae=++Mt.current;if(!i||!qe||!C||!G){se(null),ne(null),ve(null),W(!1);return}se(null),ne(null),ve(null),W(!0);const be=window.setTimeout(()=>{u.previewAssignments(t,G).then(le=>{if(ae===Mt.current){if(le.draftEtag!==C){se(null),ne(null),ve("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}se(le),ne(Gt)}}).catch(le=>{ae===Mt.current&&(se(null),ne(null),ve(bf(le)))}).finally(()=>{ae===Mt.current&&W(!1)})},250);return()=>{window.clearTimeout(be),Mt.current+=1}},[Yt,Gt,J,i,qe,C,t,u]);const ft=l.useMemo(()=>[...Ae===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"}]:[],...Ne?.authoring.assignments.some(G=>G.queryClass==="unclassified")&&!(Re&&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"}]:[],...N],[Ae,Re,o,N,Ne]),it=n?{status:"unavailable",message:"Tracked queries are loading."}:a?{status:"unavailable",message:"Tracked queries could not be loaded. Retry before assigning Properties."}:{status:"available"};async function Kt(G){let ae;try{ae=wf(G)}catch(le){j(is(le,"Check the sitemap details and try again."));return}O(G),U("reviewing");const be=await Pt("import",le=>u.importSitemap(t,le,ae),"Could not review this sitemap.");if(be?.draft){const le=be.draft.authoring.targets.filter(Oe=>Oe.status==="proposed").map(Oe=>Oe.stableKey),je=be.draft.authoring.targets.filter(Oe=>Oe.status==="included").map(Oe=>Oe.stableKey);A([...je,...le]),z(""),te(Ro),y("properties"),U("idle")}else U("error")}async function ts(G){if(!d||G.length===0||Ke)return[];De("create-queries"),Ye(null);try{return await d(G)}catch(ae){throw Ye(bt(ae)),ae}finally{De(null)}}async function _t(G){if(!qe||!C||Ke)return;const ae=new Set(G),le=qe.authoring.targets.filter(Oe=>Oe.status==="proposed"&&Oe.discoveryIdentity).map(Oe=>({discoveryIdentity:Oe.discoveryIdentity,action:ae.has(Oe.stableKey)?"create":"ignore"})),je=le.length>0||qe.authoring.targets.some(Oe=>Oe.status!=="proposed"&&Oe.status==="included"!==ae.has(Oe.stableKey));De("properties"),j(null),rt(null);try{if(!je){A([...ae]),w({kind:"all"}),y("groups");return}await u.applySitemapSelection(t,C,le,[...ae]);const Oe=await gt(),ut=Ir(Oe.draft);A(ut),w({kind:"all"}),y("groups")}catch(Oe){un(Oe)?await tt("This setup changed in another session. The latest Properties are loaded."):j(is(Oe,"Could not save the selected Properties."))}finally{De(null)}}async function Ut(G){const ae=G.groupIds&&G.groupIds.length>0?{groupKeys:Vs(G.groupIds),queryIds:Vs(G.queryIds)}:{targetKeys:Vs(G.propertyIds),queryIds:Vs(G.queryIds)};if(!H||oe!==JSON.stringify(ae)||!C||H.draftEtag!==C){j("Review the latest assignment impact before assigning queries.");return}await Pt("assignments",le=>u.applyAssignments(t,le,ae),"Could not apply these queries.")&&(_([]),xe(`${H.assignments.added} new assignment${H.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function dt(G){if(G.propertyIds.length===0)return;await Pt("replace-assignments",be=>u.replaceAssignments(t,be,{targetKeys:vs(G.propertyIds),queryIds:[G.queryId]}),"Could not replace this query assignment.")&&(_(be=>be.filter(le=>le!==G.queryId)),xe("Query assignments replaced."))}async function ss(G,ae=!1){if(G.length===0)return;if(!await Pt("paired-assignments",le=>u.applyPairedAssignments(t,le,[...G]),"Could not assign these queries.",{preserveBusyAction:ae}))throw new Error("Could not assign these queries.")}async function Je(G){if(!(!i||!d||G.length===0||Ke)){De("create-and-pair-questions"),Ye(null);try{let ae;try{ae=await d(vs(G.map(je=>je.text)))}catch(je){throw Ye(bt(je)),je}const be=new Map(ae.map(je=>[je.query,je.id])),le=G.map(je=>({targetKey:je.propertyId,queryId:be.get(je.text)})).filter(je=>je.queryId!==void 0);if(le.length!==G.length){const je=new Error("The created queries could not be matched to their Properties.");throw Ye("The queries were added, but could not be paired with every Property. Try again to pair them."),je}try{await ss(le,!0)}catch(je){throw Ye("The queries were added, but could not be assigned to their Properties. Try again to pair them."),je}}finally{De(null)}}}async function Lt(G){if(!qe)return;const ae=vs(qe.authoring.assignments.filter(le=>le.queryId===G).map(le=>le.targetKey));if(ae.length===0)return;await Pt(`remove-${G}`,le=>u.removeAssignment(t,le,ae,G),"Could not clear this query assignment.")&&_(le=>le.filter(je=>je!==G))}async function Bt(G){if(!qe||!C||Ke)return;const ae=G.name.trim();if(!ae)return;const be=Ze??ti(ae,"group"),le=qe.authoring.groups.find(ot=>ot.stableKey===be);if(le&&Ze===null){j(`A group named "${le.label}" already exists. Edit it or choose a different name.`);return}const je=G.competitorDomains.split(/[\s,]+/).map(ot=>ot.trim()).filter(Boolean),Oe=je.find(ot=>$o(ot)===null);if(Oe){j(`"${Oe}" is not a valid competitor domain.`);return}const ut=vs(je.map(ot=>$o(ot)));De("group"),j(null),rt(null);try{const ot=await u.upsertGroup(t,C,{stableKey:be,label:ae,targetKeys:vs(G.propertyIds),competitors:ut.map(L=>le?.competitors.find(fe=>fe.domain===L)??{stableKey:ti(L,"competitor"),label:L,domain:L,aliases:[]})}),ys=await gt();k(ot.warnings.map((L,fe)=>$r(L,fe,ys.draft?.authoring))),Se({...Vn}),Be(null)}catch(ot){un(ot)?await tt("This setup changed in another session. The latest groups are loaded."):j(is(ot,"Could not save this group."))}finally{De(null)}}function ps(G){const ae=qe?.authoring.groups.find(be=>be.stableKey===G);ae&&(Be(G),Se({name:ae.label,propertyIds:[...ae.targetKeys],competitorDomains:ae.competitors.map(be=>be.domain).join(", ")}))}async function ms(G){await Pt("remove-group",be=>u.removeGroup(t,be,G),"Could not remove this group.")&&(w(be=>be.kind==="groups"&&be.groupIds.includes(G)?{kind:"all"}:be),Ze===G&&(Be(null),Se({...Vn})))}function Vt(G){et(G),D(null),Ge(null),ht(null)}async function gs(){if(!(!i||!Fe.trim()||$e||ge)){R(!0),Ge(null),ht(null);try{D(await u.previewGroupMembership(t,{csv:Fe}))}catch(G){D(null),Ge(is(G,"Could not review this CSV."))}finally{R(!1)}}}async function Jt(G){if(!(!i||!C||!Me||G.length===0||Ke)){if(Me.draftEtag!==C){Ge("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}Ee(!0),De("group-import"),Ge(null),ht(null),rt(null);try{const ae=await u.applyGroupMembership(t,C,{csv:Fe,sourceChecksum:Me.sourceChecksum,previewChecksum:Me.previewChecksum,acceptedRows:vs(G.map(String)).map(Number)}),be=await gt();k(ae.warnings.map((le,je)=>$r(le,je,be.draft?.authoring))),et(""),D(null),ht(`${ae.addedMemberships} membership${ae.addedMemberships===1?"":"s"} added${ae.unchangedMemberships>0?`; ${ae.unchangedMemberships} already present`:""}.`)}catch(ae){un(ae)?(await tt("This setup changed in another session. The latest draft is loaded; review the CSV again."),Ge("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Ge(is(ae,"Could not apply this CSV."))}finally{De(null),Ee(!1)}}}async function vt(){if(!(!qe||!C||Ke||Ae===0)){De("review"),j(null),rt(null);try{const[G,ae]=await Promise.all([u.compilePreview(t),u.diffPreview(t)]),be=[...G.checks,...ae.checks],le=be.some(je=>je.ruleId==="active-revision-schema-v1");if(k(Mf(be.filter(je=>je.ruleId!=="active-revision-schema-v1"),{authoring:Ne?.authoring,queries:s})),!G.ok||!ae.ok)return;if(ae.diff.activeRevision!==qe.baseActiveRevision){await tt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(G.compiledChecksum!==ae.compiledChecksum){j("The setup changed while it was being reviewed. Review the latest changes again.");return}rt({etag:C,baseActiveRevision:qe.baseActiveRevision,compiledChecksum:G.compiledChecksum,changes:Lf(ae.diff,le),providerCalls:G.plan.executionNodes.reduce((je,Oe)=>je+Oe.expectedSnapshots,0)})}catch(G){j(is(G,"Could not review this setup."))}finally{De(null)}}}async function Xt(){if(!(!qe||!C||!Ce||Ke)){if(C!==Ce.etag||qe.baseActiveRevision!==Ce.baseActiveRevision){rt(null),j("The setup changed after review. Review the latest changes before publishing.");return}De("publish"),j(null);try{await u.publish(t,C,{expectedActiveRevision:Ce.baseActiveRevision,expectedCompiledChecksum:Ce.compiledChecksum}),f({draft:null,etag:null}),rt(null),h?.()}catch(G){un(G)?await tt("The setup changed before it could be published. Review the latest draft and publish again."):j(is(G,"Could not publish this setup."))}finally{De(null)}}}async function yt(){if(!(!C||Ke)){De("discard"),j(null);try{await u.discard(t,C),f({draft:null,etag:null}),rt(null),h?.()}catch(G){un(G)?await tt("This setup changed in another session. The latest draft is loaded."):j(is(G,"Could not discard these changes."))}finally{De(null)}}}async function Zt(){if(!(!qe||!C||!m||Ke)){De("restart"),j(null),rt(null);try{await u.discard(t,C),await u.createDraft(t,m.activeRevision),O({...Po}),z(""),A([]),_([]),w({kind:"all"}),se(null),ve(null),xe(null),Se({...Vn}),Be(null),et(""),D(null),Ge(null),ht(null),await Ve(!1)}catch(G){un(G)?await tt("The setup changed again. Reloaded the latest draft and published setup."):j(is(G,"Could not restart this setup."))}finally{De(null)}}}if(P)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(q)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:q}),e.jsx(I,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Ve(!0)},children:"Try again"})]})]});if(!Ne||i&&!C)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&&qe&&m&&qe.baseActiveRevision!==m.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(I,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:Ke==="restart",onClick:()=>{Zt()},children:Ke==="restart"?"Restarting…":"Discard draft and restart"})]}),v?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:v}):null]});const fs=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(I,{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:[m?.mode==="active-v1"?e.jsx("p",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-3 text-sm text-secondary",children:"Review and publish this setup to enable class-filtered reporting."}):null,v?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:v}):null,fs,x==="import"||x==="properties"?e.jsx(Ia,{currentStep:x,hasDraft:qe!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{yt()},importProperties:{importDraft:E,onImportDraftChange:G=>{O(G),U("idle"),j(null)},onReviewSitemap:G=>{Kt(G)},reviewState:Z,properties:We,propertiesState:"ready",propertiesSearch:F,onPropertiesSearchChange:z,maxVisibleProperties:V,onShowAllProperties:()=>te(We.length),selectedPropertyIds:Y,onSelectedPropertyIdsChange:G=>A([...G]),onContinue:G=>{_t(G)},isContinuing:Ke==="properties",onRetryProperties:()=>{gt()},onReturnToImport:()=>y("import")}}):x==="queries"?e.jsx(Ia,{currentStep:"queries",hasDraft:qe!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{yt()},onManageProjectQueries:c,queries:{onCreateQueries:d?G=>ts(G):void 0,isCreatingQueries:Ke==="create-queries"||Ke==="create-and-pair-questions",isBusy:Ke!==null,createQueriesError:St,availability:it,properties:Le,queries:ke,selectedQueryIds:ee,isApplying:Ke==="assignments"||Ke==="paired-assignments",onSelectedQueryIdsChange:G=>_([...G]),onApplySelectedQueries:G=>Ut(G),groups:Wt,audience:B,onAudienceChange:G=>{w(G),xe(null)},assignmentImpact:H&&oe===Gt&&H.draftEtag===C?Ef(H):null,isPreviewingAssignmentImpact:ye,assignmentImpactError:ue,onRetryAssignmentImpact:()=>me(G=>G+1),assignmentNotice:K,onReplaceAssignments:dt,isReplacingAssignments:Ke==="replace-assignments",onCreateAndPairQuestions:i&&d?Je:void 0,onClearQueryAssignments:Lt,onRemoveQuery:Lt,canContinue:Ae>0,onBack:()=>y("groups"),onContinue:()=>y("review")}}):x==="groups"?e.jsx(Ia,{currentStep:"groups",hasDraft:qe!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{yt()},groups:{properties:Le,groups:Wt,groupDraft:we,isSaving:Ke==="group",onGroupDraftChange:Se,onSaveGroup:Bt,onEditGroup:G=>ps(G.id),onRemoveGroup:ms,onClearGroupDraft:()=>{Be(null),Se({...Vn})},membershipImport:{csv:Fe,preview:Me,isReviewing:$e,isApplying:ge,error:Qe,notice:he,onCsvChange:Vt,onReview:gs,onApply:Jt},onBack:()=>{y("properties")},onContinue:()=>y("queries")}}):e.jsx(Ia,{currentStep:"review",hasDraft:qe!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{yt()},review:{counts:{properties:X.length,queries:new Set(Ne.authoring.assignments.map(G=>G.queryId)).size,groups:Ne.authoring.groups.length,assignments:Ne.authoring.assignments.length,providerCalls:Ce?.providerCalls},flaggedExceptions:ft,reviewedChanges:Ce?.changes,isReviewing:Ke==="review",canReviewChanges:Ae>0&&!Ke,onReviewChanges:vt,onBack:()=>y("queries"),canPublish:Ce!==null&&!Ke,isPublishing:Ke==="publish",onPublish:Xt}})]})}const Ff=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function qo(t){return t.label!=="Complete"}const mn="__all_properties__",Gf=50,nc=50,Kf=20,_f=50,Uf=250,Bf=5,Vf=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],zf={"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"},ac={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."},Qf={numerator:null,denominator:null,reason:"plan_v1"};function Xn(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 Hf(t){return Xn(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function rc(t){if(Xn(t))return"";const s=t.reason??"unavailable";return ac[s]??s}function Eo(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 Wf(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function Yf(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function Jf(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function Yn({metric:t,compact:s=!1}){const n=s?Xn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Xn(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",...Xn(t)?{}:{title:rc(t)},children:e.jsx("span",{className:n,children:Hf(t)})})}function fi({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(I,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Do({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,o]=l.useState(nc),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((d,c)=>e.jsx("li",{className:a,children:d},`${d}:${c}`))}),e.jsx(fi,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>o(Number.MAX_SAFE_INTEGER)})]})]})}function Xf({evidence:t,state:s="ready",onRetry:n}){const[a,r]=l.useState(nc),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(I,{type:"button",size:"sm",variant:"outline",onClick:n,children:"Retry evidence"}):null]}):t.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"No source evidence is available."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[640px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children:o.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(ce,{tone:i.tone,children:zf[i.kind]}),i.historical?e.jsx(ce,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:i.query}),i.provider||i.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[i.provider,i.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:i.url})]},i.id))})]})}),e.jsx(fi,{shown:o.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function Zf({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Do,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Do,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(Xf,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function ey({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(Yn,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function Oo({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function o(i){if(r)return;const d=n.findIndex(u=>u.value===s);let c=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?c=(d+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?c=(d-1+n.length)%n.length:i.key==="Home"?c=0:i.key==="End"&&(c=n.length-1),c===null)return;i.preventDefault();const h=n[c];a(h.value),i.currentTarget.querySelectorAll('[role="radio"]')[c].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:o,children:n.map(i=>{const d=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":d,tabIndex:d?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${d?"segmented-option-active":""}`,children:i.label},i.value)})})}function ty({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(Ue,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function sy({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:o=!1,isViewLoading:i=!1,isLoadingMore:d=!1,isLoadMoreError:c=!1,viewSearch:h,onViewChange:u,onLoadMore:m,onPropertyExpand:b,onRetryEvidence:g,renderPropertyLink:f}){const x=t.currentView!=null,y=t.classReporting==="available"&&(x||t.classScopes!=null),[P,S]=l.useState(t.currentView?.queryClass??"all"),[q,T]=l.useState(t.currentView?.scope.key??mn),[v,j]=l.useState(h??""),[N,k]=l.useState(Gf),[E,O]=l.useState(Kf),[Z,U]=l.useState(t.currentView?.sort??"label-asc"),[F,z]=l.useState(null),V=l.useRef(h??""),te=y&&!x&&P!=="all"?P==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,Y=x?{aggregate:t.currentView.aggregate,groups:[]}:te,A=l.useCallback(D=>{if(!x||!u)return;const $e=D.scope??(q===mn?"all":"group"),R=D.search??v;V.current=R,u({scope:$e,...$e==="group"?{groupKey:D.groupKey??q}:{},queryClass:D.queryClass??P,...R?{search:R}:{},...D.sort?{sort:D.sort}:{}})},[u,v,P,q,x]);l.useEffect(()=>{!t.currentView||i||(S(t.currentView.queryClass),T(t.currentView.scope.key??mn),t.currentView.sort&&U(t.currentView.sort))},[i,t.currentView]),l.useEffect(()=>{h!==void 0&&(V.current=h,j(D=>D.trim()===h.trim()?D:h))},[h]),l.useEffect(()=>{if(!x||!u||v===V.current)return;const D=window.setTimeout(()=>A({search:v}),Uf);return()=>window.clearTimeout(D)},[u,A,v,x]);const ee=t.availableGroups??Y.groups;l.useEffect(()=>{q===mn||ee.some(D=>D.id===q)||T(mn)},[ee,q]);const _=x?void 0:Y.groups.find(D=>D.id===q),B=_?.aggregate??Y.aggregate,w=D=>y?D:Qf,H=Z,se=v.trim().toLocaleLowerCase(),oe=l.useMemo(()=>!x&&se?B.properties.filter(D=>D.name.toLocaleLowerCase().includes(se)):B.properties,[B.properties,se,x]),ne=x?oe:oe.slice(0,N),ye=(x?t.currentView?.scope.kind==="group":_!=null)&&P==="non-brand"&&y&&(x||_.confirmedCompetitorCount>0)&&(B.shareOfVoice?.length??0)>0,W=y?B.unavailablePropertyCount??0:0,ue=t.flaggedResults.reduce((D,$e)=>D+($e.count??1),0),ve=t.flaggedResultsTotal??ue,J=[w(B.metrics.propertiesMentioned),w(B.metrics.mentionCoverage),w(B.metrics.citationCoverage)].map(rc).find(Boolean),me=y?t.nextActionText??J??(W>0?`${W} ${W===1?"property is":"properties are"} unavailable.`:ve>0?`${ve} flagged ${ve===1?"result needs":"results need"} review.`:null):ac.plan_v1,we=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?Wf(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Se=Yf(t.latestMeasurement.date),Ze=[{value:mn,label:"All properties"},...ee.map(D=>({value:D.id,label:D.label}))],Be=ee.length>Bf;function Fe(D){T(D),A(D===mn?{scope:"all"}:{scope:"group",groupKey:D})}function et(D){S(D),A({queryClass:D})}function Me(D){const $e=F!==D;z($e?D:null),$e&&b?.(D)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":i,className:"space-y-5",children:[e.jsx("header",{className:"border-b border-default pb-4",children:e.jsx("div",{role:"status","aria-label":"Measurement status and next action",className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:i?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(ce,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(ce,{tone:"caution",children:"Includes historical data"}):null,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,me?e.jsx("span",{className:"text-sm text-secondary",children:me}):null,s&&y&&n?e.jsx(I,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!y?e.jsx(I,{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:Be?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),Be?e.jsx("select",{id:"advanced-measurement-group",value:q,onChange:D=>Fe(D.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:Ze.map(D=>e.jsx("option",{value:D.value,children:D.label},D.value))}):e.jsx(Oo,{ariaLabelledBy:"advanced-measurement-group-label",value:q,options:Ze,onChange:Fe})]}),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(Oo,{ariaLabelledBy:"advanced-measurement-class-label",value:P,options:Vf,onChange:et,disabled:!y})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:v,onChange:D=>j(D.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&&ye?e.jsx(ey,{values:B.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(Ue,{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??oe.length," ",(t.currentView?.propertyTotal??oe.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(ty,{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:[Ff.map(D=>{const $e=H.startsWith(`${D.key}-`),R=$e&&H.endsWith("-desc")?"descending":$e?"ascending":"none";return e.jsx("th",{"aria-sort":R,className:(D.numeric,void 0),children:u?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const ge=`${D.key}-${$e&&H.endsWith("-asc")?"desc":"asc"}`;U(ge),A({sort:ge})},"aria-label":`Sort by ${D.label.toLowerCase()}`,children:[D.label,e.jsx($n,{className:`h-3 w-3 transition-transform ${$e?"opacity-100":"opacity-0"} ${R==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):D.label},D.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[ne.map(D=>{const $e=F===D.id;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:R=>{Jf(R.target)||Me(D.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[f?f({id:D.id,name:D.name}):D.name,qo(D.status)||D.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[qo(D.status)?e.jsx(ce,{tone:D.status.tone,children:D.status.label}):null,D.historical?e.jsx(ce,{tone:"caution",children:"Historical"}):null]}):null,Eo(D)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Eo(D)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(Yn,{metric:D.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Yn,{metric:D.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(I,{size:"icon",variant:"ghost","aria-expanded":$e,"aria-label":$e?`Hide details for ${D.name}`:`Show details for ${D.name}`,onClick:()=>Me(D.id),children:e.jsx($n,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${$e?"rotate-180":""}`,"aria-hidden":"true"})})})]},D.id),$e?(D.providers??[]).map(R=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:R.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(Yn,{metric:R.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Yn,{metric:R.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${D.id}:${R.provider}`)):null,$e?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(Zf,{property:D,onRetryEvidence:g})})},`${D.id}:details`):null]},D.id)}),ne.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]})]})}),x&&t.currentView.nextCursor&&m?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",ne.length," of ",t.currentView.propertyTotal]}),c?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(I,{size:"sm",variant:"outline",disabled:d,onClick:()=>m(t.currentView.nextCursor),children:d?"Loading…":c?"Retry loading more properties":"Show 50 more"})]}):x?ne.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",ne.length," of ",t.currentView.propertyTotal]}):null:e.jsx(fi,{shown:ne.length,total:oe.length,itemLabel:"properties",onShowAll:()=>k(Number.MAX_SAFE_INTEGER)})]}),!i&&!se&&ve>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 (",ve,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,E).map(D=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(ce,{tone:D.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:D.property}),e.jsx("span",{className:"text-secondary",children:D.summary})]},D.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((D,$e)=>D+($e.count??1),0)," of ",ve," flagged results"]}),e.jsx(I,{size:"sm",variant:"outline",onClick:()=>O(D=>Math.min(t.flaggedResults.length,D+_f)),children:"Show 50 more"})]}):ue<ve?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",ue," of ",ve," flagged results"]}),x&&t.currentView.nextCursor&&m?e.jsx(I,{size:"sm",variant:"outline",disabled:d,onClick:()=>m(t.currentView.nextCursor),children:d?"Loading…":c?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function ic(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function ny(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 ay({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:o,onRunMeasurement:i,onRetryReport:d,onViewChange:c,onLoadMore:h,onPropertyExpand:u,onRetryEvidence:m,renderPropertyLink:b,isRunningMeasurement:g,isOpeningSetup:f,isViewLoading:x,isLoadingMore:y,isLoadMoreError:P,viewSearch:S}){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(I,{type:"button",size:"sm",disabled:f,onClick:o,children:f?"Opening setup…":ic(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,r==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):r==="error"&&!a?e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load the advanced measurement report."}),d?e.jsx(I,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:d,children:"Retry report"}):null]}):a?e.jsx(sy,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:o,onViewChange:c,onLoadMore:h,onPropertyExpand:u,onRetryEvidence:m,renderPropertyLink:b,isRunningMeasurement:g,isRepublishingSetup:f,isViewLoading:x,isLoadingMore:y,isLoadMoreError:P,viewSearch:S}):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 Cn={numerator:null,denominator:null,reason:"plan_v1"};function ry(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Fo(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function iy(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function oy(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function ly(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 cy(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function dy(t){const s=new Map;for(const n of t){const a=cy(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function uy(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(f=>[f.stableKey,f])),r=new Map(n.querySnapshots.map(f=>[f.queryId,f.queryText])),o=new Map;for(const f of n.targetQuerySelections){const x=o.get(f.targetKey)??[];x.push(...f.queryIds.map(y=>r.get(y)).filter(y=>!!y)),o.set(f.targetKey,[...new Set(x)])}const i=dy(s.evidence),d=n.executionNodes.reduce((f,x)=>f+x.expectedSnapshots,0),c=s.run?.status==="completed"&&d>0,h=c?d:0,u=c?d:0,m=s.targets.map(f=>{const x=a.get(f.id),y=i.get(f.id)??[],P=y.map(T=>({id:`${T.observationId}:${T.usageEdgeId}:${T.sourceUrl}`,kind:iy(T.classification),query:T.queryText,url:T.sourceUrl,tone:oy(T.classification),historical:T.historical||T.bridged})),S=y.some(T=>T.historical||T.bridged),q=s.run?f.completeness.complete?x?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${f.completeness.executed} of ${f.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:f.id,name:f.label,mentionCoverage:Fo(f.mentionCoverage),citationCoverage:Fo(f.citationCoverage),status:q,assignedQueries:o.get(f.id)??[],urls:x?.urls.map(ry)??[],evidence:P,historical:S}}),b=new Map(m.map(f=>[f.id,f])),g=new Map(n.groups.map(f=>[f.stableKey,f]));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:u,date:ly(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Cn,mentionCoverage:Cn,citationCoverage:Cn},properties:m},groups:s.groups.map(f=>({id:f.id,label:f.label,confirmedCompetitorCount:g.get(f.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Cn,mentionCoverage:Cn,citationCoverage:Cn},properties:f.targetIds.map(x=>b.get(x)).filter(x=>!!x)}}))},flaggedResults:[]}}function my({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":Rt.title,children:[e.jsx("h2",{className:"text-xl font-semibold text-heading",children:Rt.title}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:t.selection.mode==="advanced"?Rt.description:Rt.simpleDescription}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:Su(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:[Rt.queryType,Rt.queries,Rt.answers,Rt.mentioned,Rt.cited].map(a=>e.jsx("th",{children:a},a))})}),e.jsx("tbody",{children:s.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:ki(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:Ai(r)}),e.jsx("p",{className:"text-xs text-secondary",children:Pi(r)})]},o))]},a.queryClass))})]})}),e.jsxs("details",{className:"mt-4",children:[e.jsx("summary",{className:"cursor-pointer text-sm text-secondary",children:Cu(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:[Rt.date,Rt.queryType,Rt.mentioned,Rt.cited,Rt.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:ki(a.queryClass)}),[r.mentionCoverage,r.citationCoverage].map((o,i)=>e.jsxs("td",{children:[Ai(o),e.jsx("p",{className:"text-xs text-secondary",children:Pi(o)})]},i)),e.jsx("td",{children:ku(r.continuity.state,r.continuity.comparedRunId!==null&&!a.trend.some(o=>o.runId===r.continuity.comparedRunId))})]},`${a.queryClass}:${r.runId}`)))})]})})]})]})}const hy={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function Nt(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 xy(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 py(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function gy({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[o,i]=l.useState(Au),d=Ie({...Pu({client:Q,path:{name:t},query:{period:o}}),placeholderData:si});async function c(){n(!0),r(null);try{await Tu(t,"client",o)}catch(u){const m=u instanceof fn||u instanceof Error?u.message:"Download failed";r(m)}finally{n(!1)}}if(d.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(d.error){const u=d.error instanceof Error?d.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-negative-400",children:u})})}const h=d.data;return h?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:h.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[h.meta.project.canonicalDomain," · ",h.meta.project.country," / ",h.meta.project.language.toUpperCase(),h.visibility?.selection.mode==="advanced"?` · ${Ru(h.visibility)}`:h.meta.location?` · Location: ${py(h.meta.location)}`:" · No location set"," · ","Last ",h.meta.periodDays," days"," · ","Generated ",xy(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(yy,{period:o,onChange:i}),e.jsxs(I,{variant:"secondary",size:"sm",onClick:He(c),disabled:s,children:[e.jsx(fl,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),h.visibility?e.jsx(my,{visibility:h.visibility}):e.jsx(Cy,{report:h}),h.visibility?.selection.mode!=="advanced"&&e.jsx(fy,{report:h}),!h.visibility&&e.jsx(Ty,{report:h,audience:"client"}),e.jsx(jy,{report:h}),e.jsx(Py,{report:h,audience:"client",projectName:t}),e.jsx(Ry,{report:h})]}):null}function fy({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:$u(n.percent,n.queryClass,n)}),n.reason?e.jsx("p",{children:Xo(n.reason)}):null]},n.queryClass):null)})}function yy({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:Iu.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 Go="AI Visibility — Server-Side",Ko="AI engine attention",by=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,vy="Live telemetry from your server logs.";function jy({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(aa,{eyebrow:Ko,title:Go,subtitle:vy}),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:lh(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=`${Nt(s.verifiedCrawlerHits.current)} verified · ${Nt(s.unverifiedCrawlerHits.current)} unverified${o?` · ${o}`:""}`,d=ir(s.aiUserFetchHits,"requests",r),c=ir(s.referralArrivals,"sessions",r),h=s.referralRedirects>0?`${Nt(s.referralRedirects)} blocked by redirects`:"",u=[c,s.referralArrivalsClassSummary,h].filter(Boolean).join(" · "),m=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(aa,{eyebrow:Ko,title:Go,subtitle:by(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(qr,{label:"AI bot requests observed",value:Nt(n.current),subtitle:i}),e.jsx(qr,{label:"AI user-fetch requests",value:Nt(s.aiUserFetchHits.current),subtitle:d||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(qr,{label:"AI referral sessions",value:Nt(s.referralArrivals.current),subtitle:u})]}),m.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:m.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:b.operator}),e.jsx("td",{children:Nt(b.verifiedHits+b.unverifiedHits)}),e.jsx("td",{children:Nt(b.userFetchHits)}),e.jsx("td",{children:Nt(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 Ny(t,s){return t.audience==="both"||t.audience===s}const wy={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Ba(t){return wy[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Sy(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 Cy({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=Sy(t.whatsChanged.mentionRate),d=n.providers.length>0?n.providers.map(Ba).join(", "):`${Nt(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(Mr,{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(Mr,{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(Mr,{label:"AI tools tested",value:Nt(s.providerCount),subtitle:d})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-bg/40 px-4 py-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-semibold text-strong",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-strong",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-strong",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Customer queries we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["These are the ",n.queries.length," ",n.queries.length===1?"query we asked":"queries we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((c,h)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-bg/40 px-3 py-2 text-sm text-strong",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-muted",children:String(h+1).padStart(2,"0")}),e.jsxs("span",{children:['"',c,'"']})]},h))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"How often each AI tool mentions you"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Higher is better. Each bar shows the share of customer queries where the AI named you in the answer."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(c=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:Ba(c.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-positive-500/70",style:{width:`${Math.max(c.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[c.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",c.mentionedCount,"/",c.totalCount,")"]})]})]},c.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((c,h)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:c},h))})]})}function Mr({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 ky(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function Ay(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function Py({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(m=>Ny(m,s)),r=xh(t,a),o=s==="client",i=Mu(),[d,c]=l.useState(new Set),h=d.size>0?r.filter(m=>!m.targetRef||!d.has(m.targetRef)):r,u=m=>{if(!m.targetRef)return;const b=m.targetRef;c(g=>new Set(g).add(b)),i.mutate({projectName:n,body:{targetRef:b}},{onSuccess:()=>{Te({tone:"positive",title:`Dismissed "${m.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:g=>{Te({tone:"negative",title:`Couldn't dismiss "${m.title}"`,detail:String(g)}),c(f=>{const x=new Set(f);return x.delete(b),x})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(aa,{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(vi,{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((m,b)=>{const g=m.evidence.length>0?m.evidence:m.why,f=m.why.length>0||m.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(ce,{tone:qu(m),children:o?ky(m.horizon):Lu(m.horizon)}),!o&&e.jsx(ce,{tone:"neutral",children:Eu(m.category)}),e.jsx(ce,{tone:"neutral",children:o?Ay(m.confidence):`${Du(m.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:m.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:m.action}),e.jsx($y,{items:g,limit:3,className:"mt-3"}),f&&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"}),m.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:m.why.map((x,y)=>e.jsx("li",{children:x},y))})]}),m.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:m.evidence.map((x,y)=>e.jsx("li",{children:x},y))})]})]}),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:"})," ",m.successMetric]}),m.targetRef&&!ie()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>u(m),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"})})]},`${m.priority}-${m.title}`)})})]})}function _o({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 Ry({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=ph(t).slice(0,5),o=s.length>0?Math.max(...s.map(c=>c.count)):0,i=n?Math.max(...n.topQueries.slice(0,5).map(c=>c.impressions),1):0,d=s.length>0||n!==null||a!==null||r.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(aa,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),d?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"The websites AI tools cited most often when answering customer queries about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(c=>e.jsx(_o,{label:c.domain+(c.isCompetitor?" (competitor)":""),value:c.count,displayValue:`${Nt(c.count)}×`,max:o,barClass:"bg-mono-400/70"},c.domain))})]}),a&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${a.indexedPct>=90?"text-positive-400":a.indexedPct>=70?"text-caution-400":"text-negative-400"}`,children:[a.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[Nt(a.indexed)," of ",Nt(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:Nt(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:Nt(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:Nt(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(c=>e.jsx(_o,{label:c.query,value:c.impressions,displayValue:`${Nt(c.impressions)} ${c.impressions===1?"search":"searches"}`,max:i,barClass:"bg-info-500/70"},c.query))})]}),r.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Customer queries where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:r.map((c,h)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:c.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[Ou(c.action),c.winnabilityClass==="ceded"&&e.jsx(ce,{tone:"caution",children:"Ceded surface"})]})]},h))})]})]}):e.jsx(vi,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function yi(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function bi(t){return t==="up"?"↑":t==="down"?"↓":"→"}function Lr({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=yi(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}%`:ch(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:bi(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function Uo({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=yi(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=dh(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:[Nt(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:bi(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function Iy({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=yi(r.direction),d=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?Ba(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:d,children:[o,r.deltaAbs.toFixed(1),"% ",bi(r.direction)]})]},r.provider)})})]})})]})}function Bo({insights:t,heading:s,emptyMessage:n,audience:a}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-surface p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-muted",children:n})]});const r=a==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:s}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!r&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:r?"What changed":"Title"}),e.jsx("th",{children:r?"Customer query":"Query"}),e.jsx("th",{children:r?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(o=>e.jsxs("tr",{children:[!r&&e.jsxs("td",{children:[e.jsx(ce,{tone:hy[o.severity],children:Fu(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?Ba(o.provider):o.provider})]},o.id))})]})})]})}function Ty({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(aa,{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(vi,{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(Lr,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(Lr,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(Lr,{label:a?"Queries AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(Uo,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(Uo,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(Iy,{movements:n.providerMovements,audience:s}),e.jsx(Bo,{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(Bo,{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 qr({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 aa({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 $y({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 vi({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function My({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[d,c]=l.useState(null),[h,u]=l.useState(t.displayName),[m,b]=l.useState(t.canonicalDomain),[g,f]=l.useState(t.country),[x,y]=l.useState(t.language),[P,S]=l.useState(t.ownedDomains??[]),[q,T]=l.useState(""),[v,j]=l.useState(t.aliases??[]),[N,k]=l.useState(""),[E,O]=l.useState(null),[Z,U]=l.useState(!1),[F,z]=l.useState(!1),[V,te]=l.useState(""),[Y,A]=l.useState(""),[ee,_]=l.useState(""),[B,w]=l.useState(""),[H,se]=l.useState(""),[oe,ne]=l.useState(null),[ye,W]=l.useState(null);l.useEffect(()=>{a||(u(t.displayName),b(t.canonicalDomain),f(t.country),y(t.language),S(t.ownedDomains??[]),j(t.aliases??[]))},[t,a]);function ue(){r(!1),c(null),u(t.displayName),b(t.canonicalDomain),f(t.country),y(t.language),S(t.ownedDomains??[]),j(t.aliases??[]),T(""),k("")}function ve(){const R=q.trim();R&&(P.includes(R)||S([...P,R]),T(""))}function J(R){S(P.filter(ge=>ge!==R))}function me(){const R=N.trim();if(!R)return;const ge=R.toLowerCase();v.some(Ee=>Ee.toLowerCase()===ge)||j([...v,R]),k("")}function K(R){j(v.filter(ge=>ge!==R))}async function xe(){if(!(!h.trim()||!m.trim()||!g.trim()||!x.trim())){i(!0),c(null);try{await s(t.name,{displayName:h.trim(),canonicalDomain:m.trim(),ownedDomains:P,aliases:v,country:g.trim(),language:x.trim()}),r(!1),Te({title:"Project settings saved",detail:`${h.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(R){c(R instanceof Error?R.message:"Failed to save")}finally{i(!1)}}}async function we(){const R=V.trim(),ge=Y.trim(),Ee=ee.trim(),Qe=B.trim();if(!(!R||!ge||!Ee||!Qe)){U(!0),O(null);try{const Ge={label:R,city:ge,region:Ee,country:Qe};H.trim()&&(Ge.timezone=H.trim()),await _u(t.name,Ge),n(),te(""),A(""),_(""),w(""),se(""),z(!1),Te({title:"Location added",detail:`${R} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${R}`,dedupeMode:"drop"})}catch(Ge){O(Ge instanceof Error?Ge.message:"Failed to add location")}finally{U(!1)}}}async function Se(R){U(!0),O(null);try{await Ku(t.name,R),n(),Te({title:"Location removed",detail:`${R} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${R}`,dedupeMode:"drop"})}catch(ge){O(ge instanceof Error?ge.message:"Failed to remove location")}finally{U(!1)}}async function Ze(R){U(!0),O(null);try{await Gu(t.name,R),n(),Te({title:"Default location updated",detail:`${R} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(ge){O(ge instanceof Error?ge.message:"Failed to set default location")}finally{U(!1)}}async function Be(R){ne(R),W(null);try{await Uu(t.name,R),Te({title:`${R.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(ge){W(ge instanceof Error?ge.message:"Could not download tracking results.")}finally{ne(null)}}const Fe=h!==t.displayName||m!==t.canonicalDomain||g!==t.country||x!==t.language||JSON.stringify(P)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(v)!==JSON.stringify(t.aliases??[]),et=!ie()&&!Is(),Me="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",D="mb-1 block text-sm font-medium text-secondary",$e=V.trim()&&Y.trim()&&ee.trim()&&B.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),et&&!a&&e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),d&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[d,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>c(null),children:"×"})]}),et&&a?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:D,children:"Display name"}),e.jsx("input",{className:Me,type:"text",value:h,onChange:R=>u(R.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:D,children:"Canonical domain"}),e.jsx("input",{className:Me,type:"text",value:m,onChange:R=>b(R.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:D,children:"Country"}),e.jsx("input",{className:Me,type:"text",value:g,onChange:R=>f(R.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:D,children:"Language"}),e.jsx("input",{className:Me,type:"text",value:x,onChange:R=>y(R.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:D,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:P.map(R=>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:[R,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>J(R),"aria-label":`Remove ${R}`,children:"×"})]},R))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Me} flex-1`,type:"text",placeholder:"docs.example.com",value:q,onChange:R=>T(R.target.value),onKeyDown:R=>R.key==="Enter"&&(R.preventDefault(),ve())}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:!q.trim(),onClick:ve,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:D,children:"Aliases"}),e.jsx("p",{className:"mb-1.5 text-sm text-secondary",children:"Other brand names that may appear in answers."}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:v.map(R=>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:[R,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>K(R),"aria-label":`Remove ${R}`,children:"×"})]},R))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Me} flex-1`,type:"text",placeholder:"Facebook",value:N,onChange:R=>k(R.target.value),onKeyDown:R=>R.key==="Enter"&&(R.preventDefault(),me())}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:!N.trim(),onClick:me,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(I,{type:"button",disabled:o||!Fe||!h.trim()||!m.trim(),onClick:He(xe),children:o?"Saving...":"Save changes"}),e.jsx(I,{type:"button",variant:"outline",disabled:o,onClick:ue,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-default bg-surface overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(R=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:R},R))}):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(R=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:R},R))}):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:()=>O(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(R=>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 ${R.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[R.label,R.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:R.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:R.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:R.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:R.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[et&&R.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:Z,onClick:()=>{Ze(R.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${R.label} as default location`,children:"Set default"}),et&&e.jsx("button",{type:"button",disabled:Z,onClick:()=>{Se(R.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${R.label}`,children:"Remove"})]})})]},R.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),et?F?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:Me,type:"text",value:V,onChange:R=>te(R.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:Me,type:"text",value:Y,onChange:R=>A(R.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:Me,type:"text",value:ee,onChange:R=>_(R.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:Me,type:"text",value:B,onChange:R=>w(R.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:Me,type:"text",value:H,onChange:R=>se(R.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(I,{type:"button",size:"sm",disabled:Z||!$e,onClick:He(we),children:Z?"Adding...":"Add location"}),e.jsx(I,{type:"button",size:"sm",variant:"outline",disabled:Z,onClick:()=>{z(!1),O(null)},children:"Cancel"})]})]}):e.jsx(I,{type:"button",size:"sm",variant:"outline",onClick:()=>z(!0),children:"+ Add location"}):null]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted",children:"Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"max-w-xl text-xs leading-5 text-muted",children:"Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:oe!==null,onClick:He(()=>Be("csv")),children:oe==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:oe!==null,onClick:He(()=>Be("json")),children:oe==="json"?"Preparing JSON...":"Download JSON"})]})]}),ye&&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:ye})]})]})]})}function zn(t){return{...t??{}}}function Ly(t,s){const n=Object.entries(t).sort(([r],[o])=>r.localeCompare(o)),a=Object.entries(s).sort(([r],[o])=>r.localeCompare(o));return n.length===a.length&&n.every(([r,o],i)=>{const d=a[i];return d?.[0]===r&&d[1]===o})}function qy({project:t,onSave:s}){const{isAdmin:n}=vn(),a=Ie({queryKey:["settings"],queryFn:nl,staleTime:6e4,enabled:n&&!ie()}),[r,o]=l.useState(t.providers.length===0),[i,d]=l.useState(t.providers),[c,h]=l.useState(()=>zn(t.providerModels)),[u,m]=l.useState({providers:t.providers,providerModels:zn(t.providerModels)}),[b,g]=l.useState(!1),[f,x]=l.useState(!1),[y,P]=l.useState(null),[S,q]=l.useState(null),T=l.useRef(null),v=a.data?.providerCatalog??[],j=l.useMemo(()=>new Set((a.data?.providers??[]).filter(z=>z.configured).map(z=>z.name)),[a.data]),N=l.useMemo(()=>{const z=new Map(a.data?.providers.map(te=>[te.name,te.model])),V=new Map(v.map(te=>[te.name,{...te,defaultModel:z.get(te.name)||te.defaultModel}]));for(const te of Object.keys(c))V.has(te)||V.set(te,{name:te,displayName:te,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...V.values()].sort((te,Y)=>te.displayName.localeCompare(Y.displayName))},[v,c,a.data?.providers]),k=!Ly(c,u.providerModels);l.useEffect(()=>{if(b||f)return;const z={providers:t.providers,providerModels:zn(t.providerModels)};m(z),o(z.providers.length===0),d(z.providers),h(z.providerModels)},[t]);function E(){x(!0),o(!1),i.length===0&&d([...j])}function O(z,V,te=!1){x(!0),h(Y=>{const A={...Y};return V==="__inherit__"?delete A[z]:V==="__custom__"?A[z]=te?"":A[z]??"":A[z]=V,A}),V==="__custom__"&&queueMicrotask(()=>T.current?.focus())}function Z(z,V){x(!0),d(te=>V?[...new Set([...te,z])]:te.filter(Y=>Y!==z))}function U(){x(!1),o(u.providers.length===0),d(u.providers),h(zn(u.providerModels)),P(null),q(null)}async function F(){if(!(a.isError||a.isLoading||!r&&i.length===0)){g(!0),P(null),q(null);try{const z=Object.fromEntries(Object.entries(c).filter(([te,Y])=>Y.trim()!==""&&(r||i.includes(te)))),V={providers:r?[]:i,providerModels:z};await s(V),m({providers:[...V.providers],providerModels:zn(V.providerModels)}),x(!1),q("Engine settings saved. They apply on the next sweep.")}catch(z){P(Zn(z))}finally{g(!1)}}}return ie()||!n?null:a.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):a.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):v.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(I,{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(Ss,{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:()=>{x(!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:N.map(z=>{const V=i.includes(z.name),te=j.has(z.name),Y=V&&!te,A=c[z.name],ee=z.knownModels.some(B=>B.id===A),_=A===void 0?"__inherit__":ee?A:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:V,disabled:!te&&!V,onChange:B=>Z(z.name,B.target.checked)})," ",e.jsx("span",{children:z.displayName}),Y&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),V&&(z.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${z.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${z.name}`,value:_,onChange:B=>O(z.name,B.target.value,ee),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",z.defaultModel||"default"]}),z.knownModels.map(B=>e.jsx("option",{value:B.id,children:B.displayName},B.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),_==="__custom__"&&e.jsx("input",{ref:T,"aria-label":`${z.displayName} custom model ID`,value:A??"",onChange:B=>{x(!0),h(w=>({...w,[z.name]:B.target.value}))},"aria-describedby":`project-model-hint-${z.name}`}),e.jsxs("p",{id:`project-model-hint-${z.name}`,className:"project-engine-help",children:[A?"Project override":"Inherited from instance settings",". ",z.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},z.name)})})]}),!r&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),y&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:y}),S&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:S}),k&&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(I,{type:"button",onClick:()=>{F()},disabled:b||!r&&i.length===0,children:b?"Saving engines…":"Save engines"}),e.jsx(I,{type:"button",variant:"outline",onClick:U,disabled:b,children:"Cancel"})]})]})}const $a={edit:"Edit schedule",pause:"Pause",resume:"Resume",save:"Save schedule"},Ey=[{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"}],Vo=["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 Er(t,s){const n=s==="UTC"?"UTC":s.split("/").pop()?.replace(/_/g," ")??s,a=new Date(`${t.startDate}T00:00:00Z`),r=Number.isNaN(a.getTime())?t.startDate:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(a),[o,i]=t.time.split(":").map(Number),d=Number.isInteger(o)&&Number.isInteger(i)?new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",timeZone:"UTC"}).format(new Date(Date.UTC(1970,0,1,o,i))):t.time;return`Every ${t.everyDays} days starting ${r} at ${d} · ${n}`}function Dy({projectName:t}){const s=Ot(),n=!ie()&&!Is()&&!s,a=us(),[r,o]=l.useState(!1),[i,d]=l.useState("daily"),[c,h]=l.useState(6),[u,m]=l.useState(""),[b,g]=l.useState(14),[f,x]=l.useState(""),[y,P]=l.useState("00:00"),[S,q]=l.useState("UTC"),[T,v]=l.useState(!1),[j,N]=l.useState(""),[k,E]=l.useState(!1),[O,Z]=l.useState(!1),[U,F]=l.useState(null),[z,V]=l.useState(void 0),te=Bu({client:Q,path:{name:t}}),Y=Ie({...cl({client:Q,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),A=Y.isPending||Y.isFetching,ee=Y.isError,_=Y.data?.find(J=>J.kind==="answer-visibility")??null,B=r&&z!==void 0&&(_?.updatedAt??null)!==z,w=J=>{a.setQueryData(te,me=>{const K=(me??[]).filter(xe=>xe.kind!=="answer-visibility");return J?[...K,J]:K})},H=J=>{if(J){if(J.recurrence)d("calendar"),g(J.recurrence.everyDays),x(J.recurrence.startDate),P(J.recurrence.time);else{const K=Hu(J.preset??null,J.cronExpr);d(K.freq),h(K.hour),m(K.customCron)}const me=Vo.includes(J.timezone);q(me?J.timezone:"Other"),v(!me),N(me?"":J.timezone)}else d("daily"),h(6),m(""),g(14),x(""),P("00:00"),q("UTC"),v(!1),N("");V(J?.updatedAt??null)},se=()=>{n&&(H(_),F(null),o(!0))},oe=()=>{H(_),F(null)},ne=async()=>{(await Y.refetch()).isError?F("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):F(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},ye=async(J,me)=>{if(J instanceof fn&&J.code==="SCHEDULE_VERSION_CONFLICT"){await ne();return}F(J instanceof Error?J.message:me)},W=async()=>{if(n&&!(B||z===void 0)){E(!0),F(null);try{const J=await Y.refetch();if(J.isError||J.data===void 0){F("Canonry could not verify the latest schedule. Try again before saving.");return}const me=J.data.find(Se=>Se.kind==="answer-visibility")??null;if((me?.updatedAt??null)!==z)return;const xe={timezone:T?j.trim()||"UTC":S,enabled:me?.enabled??!0,providers:me?.providers??[],expectedUpdatedAt:z};i==="calendar"?xe.recurrence={everyDays:b,startDate:f,time:y}:i==="custom"?xe.cron=u.trim():xe.preset=Qu(i,c);const we=await Ri(t,xe);o(!1),V(void 0),w(we),Te({title:"Schedule saved",detail:we.recurrence?Er(we.recurrence,we.timezone):ar(we.preset??null,we.cronExpr,we.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(J){await ye(J,"Failed to save schedule")}finally{E(!1)}}},ue=async()=>{if(!n||!_)return;const J=_.updatedAt;E(!0),F(null);try{const me=await Y.refetch();if(me.isError||me.data===void 0){F("Canonry could not verify the latest schedule. Try again before updating it.");return}const K=me.data.find(Se=>Se.kind==="answer-visibility")??null;if(!K||K.updatedAt!==J){F("This schedule changed elsewhere. Review the latest version and try again.");return}const xe={timezone:K.timezone,enabled:!K.enabled,providers:K.providers,expectedUpdatedAt:J};K.recurrence?xe.recurrence=K.recurrence:K.preset?xe.preset=K.preset:xe.cron=K.cronExpr;const we=await Ri(t,xe);w(we),Te({title:we.enabled?"Schedule resumed":"Schedule paused",detail:we.recurrence?Er(we.recurrence,we.timezone):ar(we.preset??null,we.cronExpr,we.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(me){await ye(me,"Failed to update schedule")}finally{E(!1)}},ve=async()=>{if(!n||!_)return;const J=_.updatedAt;Z(!0),F(null);try{await zu(t,J),w(null),o(!1),V(void 0),Te({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(me){await ye(me,"Failed to remove schedule")}finally{Z(!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&&!A&&!ee&&!r&&e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:se,children:_?$a.edit:"+ Set schedule"})]}),A&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),U&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:U}),!A&&ee&&e.jsxs(pe,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(I,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{Y.refetch()},children:"Retry"})]}),!A&&!ee&&!r&&_===null&&e.jsx(pe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?Ys:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!A&&!ee&&!r&&_!==null&&e.jsx(pe,{className:"surface-card compact-card",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[s&&e.jsx("p",{className:"text-sm text-secondary",children:Ys}),e.jsx("p",{className:"text-sm font-medium text-strong",children:_.recurrence?Er(_.recurrence,_.timezone):ar(_.preset??null,_.cronExpr,_.timezone)}),!_.recurrence&&e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:_.cronExpr})]}),_.enabled&&_.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",uh(_.nextRunAt,_.timezone)]}),_.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(_.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(ce,{tone:_.enabled?"positive":"neutral",children:_.enabled?"Active":"Paused"}),n&&e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:k,onClick:He(ue),children:_.enabled?$a.pause:$a.resume}),n&&e.jsx(I,{type:"button",variant:"ghost",size:"sm",disabled:O,onClick:He(ve),children:O?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[B&&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(I,{type:"button",variant:"outline",size:"sm",onClick:oe,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:J=>d(J.target.value),children:Ey.map(J=>e.jsx("option",{value:J.value,children:J.label},J.value))})]}),i!=="calendar"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:c,disabled:i==="twice-daily"||i==="custom",onChange:J=>h(parseInt(J.target.value)),children:Array.from({length:24},(J,me)=>e.jsx("option",{value:me,children:Vu(me)},me))})]})]}),i==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:u,onChange:J=>m(J.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:J=>g(Number(J.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:f,onChange:J=>x(J.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:y,onChange:J=>P(J.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:T?"Other":S,onChange:J=>{J.target.value==="Other"?(v(!0),q("Other")):(v(!1),q(J.target.value))},children:[Vo.map(J=>e.jsx("option",{value:J,children:J},J)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),T&&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:J=>N(J.target.value)})]}),U&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:U}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:()=>{o(!1),V(void 0),F(null)},children:"Cancel"}),e.jsx(I,{type:"button",size:"sm",disabled:k||Y.isFetching||ee||B||i==="custom"&&!u.trim()||i==="calendar"&&(!Number.isInteger(b)||b<1||b>3650||!f||!y),onClick:He(W),children:k?"Saving...":$a.save})]})]})]})}const Oy=[{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 Fy({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[o,i]=l.useState(""),[d,c]=l.useState(["citation.lost","citation.gained"]),[h,u]=l.useState(!1),[m,b]=l.useState(null),[g,f]=l.useState({}),[x,y]=l.useState(new Set),P=!ie()&&!Is();l.useEffect(()=>{Wu(t).then(n).catch(()=>n([]))},[t]);const S=j=>{c(N=>N.includes(j)?N.filter(k=>k!==j):[...N,j])},q=async()=>{if(!(!o.trim()||d.length===0)){u(!0),b(null);try{const j=await Yu(t,{channel:"webhook",url:o.trim(),events:d});n(N=>N==="loading"?[j]:[...N,j]),i(""),c(["citation.lost","citation.gained"]),r(!1),Te({title:"Webhook added",detail:`Notifications will be sent to ${j.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(j){b(j instanceof Error?j.message:"Failed to add webhook")}finally{u(!1)}}},T=async j=>{if(!x.has(j)){y(N=>new Set(N).add(j));try{await Xu(t,j),n(N=>N==="loading"?N:N.filter(k=>k.id!==j)),Te({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${j}`,dedupeMode:"drop"})}catch(N){b(N instanceof Error?N.message:"Failed to remove webhook")}finally{y(N=>{const k=new Set(N);return k.delete(j),k})}}},v=async j=>{f(N=>({...N,[j]:{state:"testing"}}));try{const N=await Ju(t,j);f(k=>({...k,[j]:{state:N.ok?"ok":"fail",status:N.status}})),N.ok&&Te({title:"Test notification sent",detail:`Webhook returned status ${N.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${j}`,dedupeMode:"replace"})}catch{f(N=>({...N,[j]:{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"})]}),P&&s!=="loading"&&e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),b(null)},children:a?"Cancel":"+ Add webhook"})]}),P&&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:j=>i(j.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:Oy.map(j=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:d.includes(j.value),onChange:()=>S(j.value)}),e.jsx("span",{className:"text-sm text-neutral",children:j.label})]},j.value))})]}),m&&e.jsx("p",{className:"text-negative-400 text-sm",children:m}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),b(null)},children:"Cancel"}),e.jsx(I,{type:"button",size:"sm",disabled:h||!o.trim()||d.length===0,onClick:He(q),children:h?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(pe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(j=>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:j.urlHost,children:j.urlDisplay??j.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:j.events.map(N=>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:N.replace("."," ")},N))})}),e.jsx("td",{children:e.jsx(ce,{tone:j.enabled?"positive":"neutral",children:j.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[g[j.id]&&(()=>{const N=g[j.id],k=N.state==="testing"?"Sending…":N.state==="ok"?`Delivered${N.status?` (${N.status})`:""}`:`Failed${N.status?` (${N.status})`:""}`;return e.jsx(ce,{tone:N.state==="ok"?"positive":N.state==="fail"?"negative":"neutral",children:k})})(),P&&e.jsx(I,{variant:"ghost",size:"sm",type:"button",disabled:g[j.id]?.state==="testing",onClick:()=>{v(j.id)},children:"Test"}),P&&e.jsx(I,{variant:"ghost",size:"sm",type:"button",disabled:x.has(j.id),onClick:()=>{T(j.id)},children:x.has(j.id)?"Removing…":"Remove"})]})})]},j.id))})]}),m&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:m})]})]})}function Gy({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:o}){return ie()||Ot()?null:e.jsx(em,{open:t,onOpenChange:n,children:e.jsxs(tm,{onCloseAutoFocus:i=>{r&&(i.preventDefault(),r())},children:[e.jsxs(sm,{children:[e.jsx(nm,{children:"Run AI sweep for the whole project?"}),e.jsxs(am,{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(I,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(ze,{disabled:o,onClick:a,children:"Run project-wide sweep"})]})]})})}const zo=2e3,Qo=3e5;function Ky(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function _y(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 Uy({projectName:t,refreshNonce:s}){const n=us(),[a,r]=l.useState(null),[o,i]=l.useState([]),[d,c]=l.useState(null),[h,u]=l.useState([]),[m,b]=l.useState([]),[g,f]=l.useState(null),[x,y]=l.useState(""),[P,S]=l.useState(""),[q,T]=l.useState(""),[v,j]=l.useState(!0),[N,k]=l.useState(!1),[E,O]=l.useState(null),[Z,U]=l.useState("performance");l.useEffect(()=>{F()},[t,s]);async function F(){j(!0),O(null);try{const w=await n.fetchQuery({...pl({client:Q,path:{name:t}}),staleTime:Dt});if(r(w),w.connected){const[H,se,oe,ne]=await Promise.all([n.fetchQuery({...Tm({client:Q,path:{name:t}}),staleTime:Dt}).catch(()=>null),n.fetchQuery({...$m({client:Q,path:{name:t}}),staleTime:Dt}).catch(()=>[]),n.fetchQuery({...Mm({client:Q,path:{name:t}}),staleTime:Dt}).catch(()=>[]),w.siteUrl?Promise.resolve([]):n.fetchQuery({...Lm({client:Q,path:{name:t}}),staleTime:Dt}).then(ye=>ye.sites).catch(()=>[])]);c(H),u(se),b(oe),i(ne)}else c(null),u([]),b([]),i([])}catch(w){O(w instanceof Error?w.message:"Failed to load Bing data")}finally{j(!1)}}async function z(){if(P.trim()){O(null);try{const w=await qm(t,P.trim());await wt(n,"bing"),S(""),w.availableSites.length>0&&i(w.availableSites),await F()}catch(w){O(w instanceof Error?w.message:"Failed to connect")}}}async function V(){try{await Em(t),await wt(n,"bing"),r(null),i([]),c(null),u([]),b([]),f(null),T(""),O(null)}catch(w){O(w instanceof Error?w.message:"Failed to disconnect")}}async function te(){if(q)try{await Dm(t,q),await wt(n,"bing"),await F()}catch(w){O(w instanceof Error?w.message:"Failed to set site")}}async function Y(){if(x.trim())try{const w=await Om(t,x.trim());await wt(n,"bing"),f(w),u(H=>[w,...H])}catch(w){O(w instanceof Error?w.message:"Inspection failed")}}async function A(w){k(!0),O(null);try{const H=await $i(t,{urls:[w]}),{succeeded:se,failed:oe,total:ne}=H.summary;Te({title:"Bing submission requested",detail:oe===0?`${se} URL submitted to Bing.`:`${se}/${ne} submitted successfully, ${oe} failed.`,tone:oe===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${w}`,dedupeMode:"replace"})}catch(H){const se=H instanceof Error?H.message:"Submission failed";O(se),Te({title:"Bing submission failed",detail:se,tone:"negative",dedupeKey:`bing:indexing:${t}:${w}`,dedupeMode:"replace"})}finally{k(!1)}}async function ee(){k(!0),O(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 w=await $i(t,{allUnindexed:!0}),{succeeded:H,failed:se,total:oe}=w.summary;Te({title:"Bing submissions requested",detail:se===0?`${H}/${oe} URL${oe!==1?"s":""} submitted to Bing.`:`${H}/${oe} submitted successfully, ${se} failed.`,tone:se===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(w){const H=w instanceof Error?w.message:"Batch submission failed";O(H),Te({title:"Bing submissions failed",detail:H,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{k(!1)}}if(v)return e.jsx(pe,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return ie()?e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ce,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ce,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:P,onChange:w=>S(w.target.value),onKeyDown:w=>{w.key==="Enter"&&z()}}),e.jsx(ze,{size:"sm",disabled:!P.trim(),onClick:He(z),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(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(ze,{size:"sm",variant:"ghost",onClick:He(V),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.domain})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Ht(a.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Select site"}),o.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:q,onChange:w=>T(w.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),o.map(w=>e.jsxs("option",{value:w.url,children:[w.url,w.verified?" (verified)":""]},w.url))]}),!ie()&&e.jsx(ze,{size:"sm",disabled:!q,onClick:He(te),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-muted",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),E&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:E})]});const _=[{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"}],B=_.find(w=>w.key===Z)??_[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(ze,{size:"sm",variant:"ghost",onClick:He(V),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?Ht(a.updatedAt):"—"})]})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:B.eyebrow}),e.jsx("h3",{children:B.title})]}),e.jsx("p",{className:"text-xs text-muted",children:d?.lastInspectedAt?`Last inspected ${Ht(d.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:_.map(w=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${Z===w.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>U(w.key),children:w.label},w.key))}),Z==="coverage"&&d&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ya,{label:"Indexed",value:d.summary.indexed,tone:"positive"}),e.jsx(ya,{label:"Not in index",value:d.summary.notIndexed+(d.summary.unknown??0),tone:"negative"}),e.jsx(ya,{label:"Status unknown",value:d.summary.unknown??0,tone:"neutral"}),e.jsx(ya,{label:"Coverage",value:`${d.summary.percentage}%`,tone:"neutral"})]}),d.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",d.notIndexed.length,")"]}),!ie()&&e.jsx(ze,{size:"sm",variant:"ghost",disabled:N,onClick:He(ee),children:N?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!ie()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:d.notIndexed.map(w=>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:w.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:w.httpCode??"—"}),!ie()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:N,onClick:()=>{A(w.url)},children:"Submit"})})]},w.id))})]})})]}),(d.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(d.unknown??[]).length,")"]}),!ie()&&e.jsx(ze,{size:"sm",variant:"ghost",disabled:N,onClick:He(ee),children:N?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!ie()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(d.unknown??[]).map(w=>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:w.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:w.lastCrawledDate?Ht(w.lastCrawledDate):"—"}),!ie()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:N,onClick:()=>{A(w.url)},children:"Submit"})})]},w.id))})]})})]}),d.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",d.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:d.indexed.map(w=>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:w.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:w.lastCrawledDate?Ht(w.lastCrawledDate):"—"})]},w.id))})]})})]})]}),Z==="coverage"&&!d&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),Z==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!ie()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:x,onChange:w=>y(w.target.value),onKeyDown:w=>{w.key==="Enter"&&Y()}}),e.jsx(ze,{size:"sm",disabled:!x.trim(),onClick:He(Y),children:"Inspect"})]}),g&&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:g.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:g.inIndex?"text-positive-400":"text-negative-400",children:g.inIndex?"Yes":"No"})," · ","HTTP: ",g.httpCode??"—"," · ","Crawled: ",g.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(w=>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:w.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(ce,{tone:w.inIndex?"positive":"negative",children:w.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:w.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Ht(w.inspectedAt)})]},w.id))})]})})]}),Z==="performance"&&e.jsx("div",{className:"mt-4",children:m.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:fa[pn.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:fa[pn.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:fa[pn.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:fa[pn.Position]})]})}),e.jsx("tbody",{children:m.map((w,H)=>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:w.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:w.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:w.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(w.ctr)?w.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:w.averagePosition.toFixed(1)})]},H))})]})})})]})]})}function By({projectName:t}){const s=us(),[n,a]=l.useState("google"),[r,o]=l.useState(!0),[i,d]=l.useState("idle"),[c,h]=l.useState(null),u=l.useRef(null),[m,b]=l.useState(null),[g,f]=l.useState(null),[x,y]=l.useState(0);async function P(q=!1){q||o(!0),h(null);try{const[T,v]=await Promise.all([s.fetchQuery({...ni({client:Q,path:{name:t}}),staleTime:Dt}).catch(()=>[]),s.fetchQuery({...pl({client:Q,path:{name:t}}),staleTime:Dt}).catch(()=>null)]),j=T.find(N=>N.connectionType==="gsc")??null;b(j),f(v)}catch(T){h(T instanceof Error?T.message:"Failed to load search engine connections")}finally{o(!1)}}async function S(){if(i!=="idle")return;u.current?.abort();const q=new AbortController;u.current=q;const T=q.signal;d("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 v=[],j=[];try{async function N(){if(!m)return;const O=await Rm(t);if(!O?.id)return;const Z=Date.now()+Qo;for(;Date.now()<Z;){if(T.aborted||(await new Promise(F=>setTimeout(F,zo)),T.aborted))return;const U=await Or(O.id).catch(()=>null);if(!U)break;if(["completed","failed","cancelled"].includes(U.status)){U.status!=="completed"&&v.push(`Google sync ${U.status}`);return}}j.push("Google sync is still running — search data will appear shortly")}async function k(){if(!g?.connected)return;const O=await Im(t).catch(()=>null);if(!O?.id){v.push("Bing sweep could not be started");return}const Z=Date.now()+Qo;for(;Date.now()<Z;){if(T.aborted||(await new Promise(F=>setTimeout(F,zo)),T.aborted))return;const U=await Or(O.id).catch(()=>null);if(!U)break;if(["completed","failed","cancelled","partial"].includes(U.status)){U.status==="failed"?v.push("Bing sweep failed"):U.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([N(),k()]);for(const O of E)O.status==="rejected"&&v.push(O.reason instanceof Error?O.reason.message:"Sync failed");if(await Promise.all([wt(s,"gsc"),wt(s,"bing")]),T.aborted)return;if(d("reloading"),await P(!0),y(O=>O+1),v.length>0){const O=`Partial refresh: ${[...v,...j].join("; ")}`;h(O),Te({title:"Search coverage partially refreshed",detail:O,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(N){if(!T.aborted){const k=N instanceof Error?N.message:"Refresh failed";h(k),Te({title:"Search coverage refresh failed",detail:k,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{T.aborted||d("idle")}}return l.useEffect(()=>(P(),()=>{u.current?.abort()}),[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([q,T])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===q,className:`project-subnav-link ${n===q?"project-subnav-link-active":""}`,onClick:()=>a(q),children:T},q))}),!ie()&&e.jsxs(ze,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{S()},children:[e.jsx(ea,{className:`h-3.5 w-3.5 ${i!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":i==="syncing"?"Refreshing search data…":i==="reloading"?"Reloading workspaces…":"Refresh search data"]})]}),c&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:c}),n==="google"&&e.jsx(mx,{projectName:t,refreshNonce:x}),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(Uy,{projectName:t,refreshNonce:x})]})]})}function Va({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(Ue,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${Jo[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 Vy({model:t,sweepRunning:s,hasVisibilityBaseline:n}){const a=t.citationMovement,r=t.mentionMovement,o=t.movementComparison,i=t.recentRuns.find(g=>g.kind===Ws["answer-visibility"]&&(g.status===Oa.completed||g.status===Oa.partial)),d=g=>g.tone==="positive"?"improved":g.tone==="negative"?"declined":g.gained>0||g.lost>0?"mixed":"steady",c=d(r),h=d(a),u=(()=>{if(s)return"A fresh sweep is running now";if(!n)return"No AI Visibility baseline yet";if(!o.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(o.querySetChanged)return"Tracking scope changed since the previous sweep";if(c===h)return c==="steady"?"Answer mentions and citation coverage held steady":c==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${c}`;const g=c==="mixed"?"Answer mention movement was mixed":c==="steady"?"Answer mentions held steady":`Answer mentions ${c}`,f=h==="mixed"?"citation movement was mixed":h==="steady"?"citation coverage held steady":`citation coverage ${h}`;return`${g}; ${f}`})(),m=[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(Ue,{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:u})]}),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(Va,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(Va,{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?`${m||"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:Ot()?Ys:"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.":Ot()?Ys:"Complete your first AI Visibility sweep to measure both signals."})]})})]})}function Dr({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($n,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:o})]})}function zy({insights:t,suggestedQueries:s,onManageQueries:n}){const{openEvidence:a}=Zo(),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(ce,{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((g,f)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(Gr,{state:g.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:g.query}),g.provider?e.jsx(Tn,{provider:g.provider}):null,!ie()&&g.evidenceId?e.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(g.evidenceId)},children:"View evidence"}):null]},g.evidenceId||`${b.id}-${f}`))})]}):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(I,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},b.query),d=t.slice(0,1),c=r.slice(0,1),h=t.slice(1),u=r.slice(1),m=h.length+u.length;return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[d.map(o),c.map(i)]}),m>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:[m," more ",m===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[h.map(o),u.map(i)]})]}):null]})}function db(t){const{projectName:s}=lc({from:"/projects/$projectName"}),a=dl()?.dashboard.projects.find(j=>j.project.name===s||j.project.id===s)?.project.name??null,r=Ie({...Zu({client:Q}),enabled:!a}),o=a??r.data?.find(j=>j.name===s||j.id===s)?.name??null,i=ul(),d=ml(t.tab,hl(i)),[c,h]=l.useState(null),u=o!==null&&c===o,m=l.useCallback(()=>{o&&h(o)},[o]),{commandCenter:b,isLoading:g,overviewLoading:f,overviewError:x,isError:y,latestVisibilityRevision:P,competitorHistoryRevision:S,refetch:q}=xl(o,{overview:d==="overview"&&u}),T=!a&&r.isLoading||g;return!o&&!a&&r.isSuccess&&!g?e.jsx("div",{className:"page-container",children:e.jsxs(pe,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(I,{asChild:!0,children:e.jsx(Ss,{to:"/",children:"Return to overview"})})]})}):!b&&(y||r.isError)?e.jsxs("div",{className:"page-container",role:"alert",children:[e.jsx("p",{children:"Could not load this project."}),e.jsx(I,{type:"button",variant:"outline",onClick:()=>{Promise.all([r.refetch(),q()])},children:"Retry"})]}):!b||T?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(Yy,{model:b,refetch:q,latestVisibilityRevision:P,competitorHistoryRevision:S,overviewLoading:f,overviewError:x,overviewRequested:u,onRequestOverview:m,...t})}function Qy({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=l.useRef(null),o=l.useRef(null),[i,d]=l.useState(null);l.useLayoutEffect(()=>{const u=r.current,m=o.current;if(!u||!m)return;const b=()=>{const f=u.getBoundingClientRect().width;if(!f)return;const x=Number.parseFloat(getComputedStyle(u).columnGap)||0,y=new Map([...m.querySelectorAll("[data-project-tab]")].map(j=>[j.dataset.projectTab,j.getBoundingClientRect().width])),P=j=>y.get(j)??0,S=j=>j.reduce((N,k)=>N+P(k),0)+Math.max(0,j.length-1)*x,q=[...t.map(j=>j.key),...s.length?["more"]:[],...n?[n.key]:[]];let T=t.map(j=>j.key),v=!1;if(S(q)>f){const j=t.find(E=>E.key===a),N=j?[j.key]:[];v=!!(n&&S([...N,"more",n.key])>f);const k=["more",...n&&!v?[n.key]:[]];for(const E of t)if(E.key!==j?.key){if(S([...N,E.key,...k])>f)break;N.push(E.key)}T=t.filter(E=>N.includes(E.key)).map(E=>E.key)}d(j=>j?.settingsInMore===v&&j.visibleKeys.join()===T.join()?j:{visibleKeys:T,settingsInMore:v})};if(b(),typeof ResizeObserver>"u")return window.addEventListener("resize",b),()=>window.removeEventListener("resize",b);const g=new ResizeObserver(b);return g.observe(u),g.observe(m),()=>g.disconnect()},[t,s,n,a]);const c=i?t.filter(u=>i.visibleKeys.includes(u.key)):t,h=[...t.filter(u=>!c.includes(u)),...s,...i?.settingsInMore&&n?[n]:[]];return e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",ref:r,children:[e.jsx("div",{className:"project-subnav-measure","aria-hidden":"true",children:e.jsxs("div",{className:"project-subnav-measure-row",ref:o,children:[[...t,...n?[n]:[]].map(u=>e.jsx("span",{className:"project-subnav-link","data-project-tab":u.key,children:u.label},u.key)),e.jsxs("span",{className:"project-subnav-link project-subnav-more-trigger","data-project-tab":"more",children:["More",e.jsx($n,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),c.map(u=>e.jsx(Ss,{to:u.href,search:m=>({...m,onboarding:void 0}),className:`project-subnav-link ${u.key===a?"project-subnav-link-active project-subnav-current":""}`,"aria-current":u.key===a?"page":void 0,children:e.jsx("span",{className:"project-subnav-label",children:u.label})},u.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(Hy,{items:h,activeTab:a}),n&&!i?.settingsInMore&&e.jsx(Ss,{to:n.href,search:u=>({...u,onboarding:void 0}),className:`project-subnav-link ${a==="settings"?"project-subnav-link-active":""}`,"aria-current":a==="settings"?"page":void 0,children:n.label})]})]})}function Hy({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null),o=l.useRef(null),i=l.useRef("first"),d=l.useId(),c=t.map(u=>u.key).join();if(l.useEffect(()=>{a(!1)},[c]),l.useEffect(()=>{if(!n)return;const u=r.current?.querySelectorAll('[role="menuitem"]');(i.current==="last"?u?.[u.length-1]:u?.[0])?.focus()},[n]),l.useEffect(()=>{if(!n)return;const u=b=>{r.current&&!r.current.contains(b.target)&&a(!1)},m=b=>{b.key==="Escape"&&(a(!1),o.current?.focus())};return document.addEventListener("pointerdown",u),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",u),document.removeEventListener("keydown",m)}},[n]),t.length===0)return null;const h=t.some(u=>u.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",ref:o,className:`project-subnav-link project-subnav-more-trigger ${h?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?d:void 0,onClick:()=>{i.current="first",a(u=>!u)},onKeyDown:u=>{u.key!=="ArrowDown"&&u.key!=="ArrowUp"||(u.preventDefault(),i.current=u.key==="ArrowUp"?"last":"first",a(!0))},children:["More",e.jsx($n,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:d,"aria-label":"More project sections",onKeyDown:u=>{const m=[...u.currentTarget.querySelectorAll('[role="menuitem"]')],b=m.indexOf(document.activeElement),g=u.key==="Home"?0:u.key==="End"?m.length-1:u.key==="ArrowDown"?(b+1)%m.length:u.key==="ArrowUp"?(b-1+m.length)%m.length:null;g!==null&&(u.preventDefault(),m[g]?.focus())},onBlur:u=>{r.current?.contains(u.relatedTarget)||a(!1)},children:t.map(u=>e.jsx(Ss,{to:u.href,search:m=>({...m,onboarding:void 0}),role:"menuitem",tabIndex:-1,className:`project-subnav-menu-item ${u.key===s?"project-subnav-menu-item-active":""}`,"aria-current":u.key===s?"page":void 0,onClick:()=>a(!1),children:u.label},u.key))}):null]})}const Wy=20;function Yy({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r,overviewLoading:o,overviewError:i,overviewRequested:d,onRequestOverview:c}){const h=cc(),u=us(),{canWrite:m}=vn(),[b,g]=l.useState(null),f=l.useRef(null),x=dl(),y=s.project.name,P=x?.dashboard.projects.some(M=>M.project.name===y)??!1,S=Ie({...rm({client:Q,path:{name:y}}),enabled:!ie()&&!!y&&(m||t==="portfolio"||t==="overview"||t==="settings"),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),q=x?x.dashboard.settings.providerStatuses.filter(M=>M.state==="ready").map(M=>Ii(M.name)):void 0,T=S.data?.answerVisibilityProviderReady,v=q,j=s.project.providers.map(Ii),N=v?.some(M=>j.length===0||j.includes(M))===!0,k=j.length===0||j.includes(im),E=Ie({...om({client:Q}),enabled:!ie()&&m&&T===void 0&&k&&!N,staleTime:6e4,retry:!1}),O=k?E.isSuccess?typeof E.data.browserVersion=="string":E.isError?!1:void 0:!1,Z=T??lm({projectProviders:j,configuredApiProviders:v,cdpConfigured:O}),U=l.useMemo(()=>hl(ul()),[]),F=ml(t,U),z=l.useMemo(()=>s.competitors.map(M=>M.domain),[s.competitors]),[V,te]=l.useState(!1),[Y,A]=l.useState(!1),ee=cm(),_=dc({strict:!1}),B=mc(_),w=l.useCallback(M=>{h({to:".",search:p=>hc(p,M)})},[h]),H=_.manageQueries===!0,se=l.useCallback(()=>{h({to:".",replace:!0,search:M=>({...M,siteHealthRunId:void 0})})},[h]),[oe,ne]=l.useState(H),[ye,W]=l.useState(""),[ue,ve]=l.useState(!1),[J,me]=l.useState(null),[K,xe]=l.useState("30d"),[we,Se]=l.useState(void 0),[Ze,Be]=l.useState(!1),[Fe,et]=l.useState(null),[Me,D]=l.useState(!1),$e=xc(_),[R,ge]=l.useState(void 0),[Ee,Qe]=l.useState(void 0),Ge=l.useCallback(M=>{ge(M.search),M.sort&&Qe(M.sort),h({to:".",search:p=>({...p,...pc(M)}),replace:!1})},[h]),[he,ht]=l.useState(!1),Ke=s?.project.displayName||s?.project.name||y,De=dm(),St=Ie({...Ti({client:Q,path:{name:y}}),enabled:F==="portfolio"&&!!y,staleTime:0,refetchOnMount:"always"}),Ye=Ie({...um({client:Q,path:{name:y}}),enabled:!ie()&&!!y&&(m||F==="portfolio"||F==="overview"||F==="settings"),staleTime:0,refetchOnMount:"always"}),Ce=Ye.data?.active??null,rt=Ye.data!==void 0,pt=new Set(Ce&&Number(Ce.plan.schemaVersion)===2?Ce.plan.groups?.map(M=>M.stableKey)??[]:[]),qe={...$e.scope==="group"&&!!$e.groupKey&&rt&&!pt.has($e.groupKey)?{scope:"all",queryClass:$e.queryClass}:$e,...R?{search:R}:{}},C=Ce===null?null:Number(Ce.plan.schemaVersion),Re=Ce?.revision??0,Ne=rt?`${y}:${Re}`:null,Ve=l.useRef(null);l.useEffect(()=>{const M=Ve.current;Ne!==null&&(Ve.current=Ne),gc(M,Ne)&&(Ge({scope:"all",queryClass:"all"}),ht(!1))},[Ne,Ge]);const gt={client:Q,path:{name:y},query:{scope:qe.scope,...qe.groupKey?{groupKey:qe.groupKey}:{},queryClass:qe.queryClass,...qe.search?{search:qe.search}:{},...Ee?{sort:Ee}:{},limit:50}},tt=Ho({...mm(gt),enabled:!1,initialPageParam:gt,getNextPageParam:(M,p)=>{if(!M.properties.nextCursor)return;const $=p[0]?.measurement.displayedRunId;return{path:gt.path,query:{...gt.query,cursor:M.properties.nextCursor,...$?{runId:$}:{}}}},placeholderData:si,staleTime:0,refetchOnMount:"always"}),Pt=tt.data?.pages[0]?.measurement.displayedRunId,We=Ie({...hm({client:Q,path:{name:y},query:{revision:Re,...Pt?{runId:Pt}:{}}}),enabled:F==="overview"&&!!y&&Ce!==null&&C===1,staleTime:0,refetchOnMount:"always"}),X=Ye.data!==void 0,Le=St.data!==void 0,Ae=Ye.isPending&&!X,ke=Ye.isError&&!X,Wt=St.isPending&&!Le,Yt=St.isError&&!Le,Gt=We.data!==void 0,ft=ny({activePlanSchemaVersion:S.data?.activeSchemaVersion??C,hasDraft:S.data?.draft!==null&&S.data?.draft!==void 0}),it=ft.surface==="simple-overview",Kt=S.data===void 0&&Ye.data===void 0&&(Ye.isLoading||S.isLoading);l.useEffect(()=>{F==="overview"&&it&&!Kt&&c()},[Kt,it,c,F]);const ts=F==="overview"&&it&&!Kt,_t=xl(y,{evidence:ts}),Ut=_t.commandCenter?.visibilityEvidence??s.visibilityEvidence,dt=m&&!ie()&&!Ot()&&F!=="overview",ss=Ie({...Ti({client:Q,path:{name:y}}),enabled:dt,staleTime:ai,refetchOnWindowFocus:"always"}),Je=C===2&&B.measurementScope==="group"?B.measurementScopeKey:void 0,Lt=C===2&&B.measurementScope==="project",Bt=l.useMemo(()=>{if(!(Ce?.plan.schemaVersion!==2||!Je))return Ce.plan.groups.find(M=>M.stableKey===Je)},[Ce,Je]),ps={client:Q,path:{name:y},query:{window:K,queryClass:C===2&&B.queryClass!=="unknown"?B.queryClass:"non-brand",...Je?{groupKey:Je}:{},...Lt?{scope:"all-markets"}:{}}},ms=F==="overview"&&!B.marketKey&&!!y&&(it||rt)&&!Kt&&(it||(B.measurementScope==="project"||C===2&&B.measurementScope==="group")&&B.queryClass!=="unknown"&&(C===2||B.queryClass!=="branded")),[Vt,gs]=l.useState(null);l.useEffect(()=>{ms||gs(null)},[ms]),l.useEffect(()=>{gs(null)},[y]);const Jt=Vt===y,vt=ms&&Jt,Xt=Ie({...xm(ps),enabled:vt,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});pm(y,JSON.stringify([r,s.competitors.map(M=>M.domain).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,Re,S.data?.draft?.etag??null]),vt);const yt=Xt.isError?Xt.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,Zt=l.useMemo(()=>s.competitors.map(M=>({domain:M.domain,label:M.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:M.citationCount,answeredResults:M.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),fs=l.useMemo(()=>{if(Ce?.plan.schemaVersion!==2)return Zt;const M=Je?Bt?.competitors??[]:Ce.plan.groups.flatMap($=>$.competitors),p=new Map;for(const $ of M){const re=$.domain.trim().toLowerCase();!re||p.has(re)||p.set(re,{domain:$.domain,label:$.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const $ of Zt){const re=$.domain.trim().toLowerCase();!re||p.has(re)||p.set(re,$)}return[...p.values()]},[Ce,Je,Zt,Bt]),G=C===2?fs:Zt,ae=At({...gm({client:Q}),meta:{skipGlobalErrorToast:!0}}),be=S.data!==void 0?"success":S.isError?"error":"pending",le=l.useMemo(()=>{const M=tt.data?.pages;return M?!fc(M):!1},[tt.data]),je=l.useMemo(()=>{const M=tt.data?.pages,p=M?.[0],$=M?.at(-1);if(!(!p||!$||le))return{...p,properties:{...p.properties,items:M.flatMap(re=>re.properties.items),nextCursor:$.properties.nextCursor}}},[le,tt.data]),Oe=l.useMemo(()=>{if(Ce)return Ce.plan.schemaVersion===1?We.data?uy(Ce,We.data):void 0:je?yc({overview:je,activePlan:Ce,sort:Ee,report:We.data,reportState:je.measurement.displayedRunId===void 0?"ready":We.isFetching&&We.data===void 0?"loading":We.isError&&We.data===void 0?"error":We.data?"ready":"loading"}):void 0},[Ce,We.data,We.isError,We.isFetching,je]),ut=C===2?le?"error":tt.isPending?"loading":tt.isError&&Oe===void 0?"error":"ready":We.isPending&&!Gt?"loading":We.isError&&!Gt?"error":"ready",ot=(s?.recentRuns??[]).some(M=>M.kind===Ws["answer-visibility"]&&(M.status===Oa.running||M.status===Oa.queued)),ys=s.queryCounts.total>0,L=l.useMemo(()=>(s?.project.locations??[]).map(M=>M.label),[s?.project.locations]),fe=l.useMemo(()=>new Set(Ut.map(M=>M.location??"")),[Ut]),nt=fe.has(""),jt=l.useMemo(()=>[...new Set(Ut.map(M=>M.query))].sort((M,p)=>M.localeCompare(p)),[Ut]),mt=jt.length>0||s.queryCounts.total>0||(ss.data?.length??0)>0||Ce!==null,Ls=m&&!mt&&(Ye.data===void 0&&Ye.isPending||ss.isLoading||ts&&_t.evidenceLoading),sn=m&&(S.isError&&!S.isFetching||dt&&ss.isError&&!ss.isFetching),zt=m&&!sn&&(Ls||Z===void 0||S.isFetching),qn=!zt&&!sn&&mt&&Z===!0,Ct=m&&!zt&&!qn,hs=!ie()&&F==="overview"&&Ct&&!mt,nn=Ie({...fm({client:Q,path:{name:y},query:{limit:Wy}}),enabled:hs&&!!y,retry:!1}),En=nn.isSuccess&&nn.data.scans.some(M=>M.status==="completed"||M.status==="partial"),Ha=hs&&nn.isSuccess&&!En,Wa=hs&&En,an=Ie({...cl({client:Q,path:{name:y}}),enabled:!ie()&&!Ot()&&!!y,retry:!1}).data?.find(M=>M.kind===Ws["answer-visibility"]),Dn=an?.enabled&&an.nextRunAt?`Next AI sweep ${new Date(an.nextRunAt).toLocaleString()}`:null,rn=l.useMemo(()=>{const M=[...fe].filter(Boolean);return M.length>1?M:L},[fe,L]);l.useEffect(()=>{if(!ts||we===void 0||we===""||!y){et(null),D(!1);return}D(!0),ym(y,we,20).then(M=>{et(M),D(!1)}).catch(()=>{et(null),D(!1)})},[we,y,ts]);const qs=l.useMemo(()=>{if(!Fe)return null;const M=new Map;for(const p of Fe){for(const[$,re]of Object.entries(p.providerRuns??{}))M.set(`${p.query}::${$}`,re.map(de=>({runId:de.runId,citationState:de.citationState,createdAt:de.createdAt,answerMentioned:de.answerMentioned,visibilityState:de.visibilityState,visibilityTransition:de.visibilityTransition,mentionState:de.mentionState,mentionTransition:de.mentionTransition})));(!p.providerRuns||Object.keys(p.providerRuns).length===0)&&M.set(`${p.query}::`,p.runs.map($=>({runId:$.runId,citationState:$.citationState,createdAt:$.createdAt,answerMentioned:$.answerMentioned,visibilityState:$.visibilityState,visibilityTransition:$.visibilityTransition,mentionState:$.mentionState,mentionTransition:$.mentionTransition})))}return M},[Fe]),jn=l.useMemo(()=>{const M=we!==void 0?Ut.filter(p=>we===""?!p.location:p.location===we):Ut;return qs?M.map(p=>{const $=qs.get(`${p.query}::${p.provider}`)??qs.get(`${p.query}::`);return $?{...p,runHistory:$}:p}):M},[Ut,we,qs]);async function la(){if(!(b!==y||!m||ie()||Ot()||De.isPending||ot||!qn))try{await De.mutateAsync({projectName:y,projectLabel:Ke,sourceAction:"project-run"}),g(null),n()}catch{}}function ca(){h({to:"/setup",search:{experience:"legacy",setupProject:y}})}function da(){h({to:"/projects/$projectName/technical-aeo",params:{projectName:y}})}async function On(){A(!0);try{await Pm(y),Te({title:"Project deleted",detail:`${Ke} was removed.`,tone:"positive",dedupeKey:`project:delete:${y}`,dedupeMode:"drop"}),h({to:"/"}),n()}catch(M){console.error("Failed to delete project:",M)}finally{A(!1)}}async function Ya(){const M=ye.split(`
|
|
7
|
-
`).map(p=>p.trim()).filter(Boolean);if(M.length!==0){ve(!0);try{await jm(y,M),n(),W("")}finally{ve(!1)}}}async function Es(M){me(M);try{await vm(y,[M]),n()}catch(p){Te({title:"Could not remove query",detail:p instanceof Error?p.message:`Failed to remove "${M}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{me(null)}}async function ua(M){const p=M.trim();if(!p)return!1;try{return await Nm(y,[p]),n(),!0}catch($){return Te({title:"Could not add competitor",detail:$ instanceof Error?$.message:`Failed to add ${p}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function ma(M){const p=s.competitors.find($=>$.domain===M);if(!p)return Te({title:"Could not remove competitor",detail:`Could not find ${M} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await wm(y,p.id),n(),!0}catch($){return Te({title:"Could not remove competitor",detail:$ instanceof Error?$.message:`Failed to remove ${p.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function Fn(M){const p=M.trim();if(!p||!Je||C!==2||!m||ie()||ae.isPending)return!1;try{const $=await ae.mutateAsync({client:Q,path:{name:y},headers:{"Idempotency-Key":Ky()},body:{expectedActiveRevision:Re,groupKey:Je,domain:p}});return Promise.allSettled([S.refetch()]),Te({title:$.draftCreated?"Competitor added to a market draft":"Market competitor updated",detail:`Publish the Advanced Measurement draft before ${p} is used in future market runs.`,tone:"positive",dedupeKey:`competitor:market-pin:${Je}:${p}`,dedupeMode:"replace"}),!0}catch($){return Te({title:"Could not add market competitor",detail:$ instanceof Error?$.message:`Failed to add ${p} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function Gn(M,p){const $=await Sm(M,p);return await u.invalidateQueries({queryKey:Cm({client:Q})}),u.setQueryData(km({client:Q,path:{name:M}}),$),_y(u,$),p.providers!==void 0&&await u.invalidateQueries({queryKey:Am({client:Q,path:{name:M}}),exact:!0}),$}const Qt=`/projects/${encodeURIComponent(s.project.name)}`,Kn=[{key:"overview",label:"AI Visibility",href:Qt},{key:"search-console",label:"Search Engines",href:`${Qt}/search-console`},{key:"activity",label:"Activity",href:`${Qt}/activity`},{key:"technical-aeo",label:"Site Health",href:`${Qt}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${Qt}/conversions`},{key:"local",label:"Local Presence",href:`${Qt}/local`},{key:"queries",label:"Queries",href:`${Qt}/queries`},{key:"backlinks",label:"Backlinks",href:`${Qt}/backlinks`}],ha=[{key:"report",label:"Report",href:`${Qt}/report`},{key:"history",label:"Change History",href:`${Qt}/history`}],xa=Kn.filter(M=>rr(M.key,U)),Ja=ha.filter(M=>rr(M.key,U)),Xa=rr("settings",U)?{key:"settings",label:"Settings",href:`${Qt}/settings`}:null;function Za(M){return it?M:e.jsx(fp,{projectName:y,selection:B,showUnmeasuredFallback:!Ce&&!ys&&B.measurementScope==="project"&&B.queryClass==="all"&&!B.provider&&!B.model&&!B.location&&!B.from&&!B.to&&!B.revision&&!B.measurementRunId&&!B.queryKey&&!B.marketKey,onSelectionChange:w,onManageQueries:ie()?void 0:()=>{h({to:"/projects/$projectName/queries",params:{projectName:y},search:p=>({...p,queryWorkspace:"tracked",trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:ie()?void 0:({id:p,label:$})=>e.jsx(Ss,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:y,targetKey:p},search:bc,"aria-label":`Property details for ${$}`,className:"inline-flex min-h-11 items-center text-sm text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:"Property details"}),fallback:M},`${y}:${JSON.stringify({...B,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]}),!ie()&&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(M=>e.jsx("span",{className:"tag",children:M},M))]})]}),e.jsxs("div",{className:Ot()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:[F==="overview"&&(it||B.from||B.to)?e.jsx("p",{className:"text-sm text-muted",children:it?s.dateRangeLabel:`${B.from?.slice(0,10)??"First measurement"} to ${B.to?.slice(0,10)??"Latest measurement"}`}):null,!ie()&&(Ot()?e.jsx(bm,{projectName:y,running:ot,portfolio:!it}):e.jsxs("div",{className:"flex items-center gap-3",children:[Dn?e.jsx("p",{className:"text-sm text-secondary",children:Dn}):null,Ha?e.jsx(ze,{type:"button",onClick:da,children:"Map site"}):Wa?e.jsx(ze,{type:"button",onClick:da,children:"View Page Health"}):null,e.jsx(ze,{type:"button",variant:"outline",disabled:De.isPending||ot||zt,onClick:sn?()=>{Promise.all([S.refetch(),...dt?[ss.refetch()]:[]])}:Ct?ca:M=>{f.current=M.currentTarget,g(y)},children:De.isPending?"Starting…":ot?"AI sweep running…":zt?"Checking AI readiness…":sn?"Retry AI readiness":Ct?"Set up AI Visibility":"Run AI sweep"})]}))]})]}),!ie()&&!Ot()&&e.jsx(Gy,{open:b===y,projectLabel:Ke,onOpenChange:M=>g(M?y:null),onConfirm:He(la),onClosed:()=>f.current?.focus(),disabled:De.isPending||ot||!qn}),e.jsx(Qy,{items:xa,overflowItems:Ja,settingsItem:Xa,activeTab:F}),F==="portfolio"&&!ie()?e.jsx(Of,{projectName:y,canEdit:m,queries:St.data??[],isQueryLoading:Wt,isQueryError:Yt,onRetryQueries:()=>{St.refetch()},publishedPlan:Ce,onCreateQueries:async M=>(await ee.mutateAsync({projectName:y,queries:[...M]}),(await St.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{h({to:"/projects/$projectName",params:{projectName:y},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([S.refetch(),Ye.refetch()]).finally(()=>{h({to:"/projects/$projectName",params:{projectName:y}})})}},y):F==="overview"?Kt||it&&!P&&(!d||o)?e.jsxs("div",{role:"status","aria-live":"polite",children:[e.jsx("span",{className:"sr-only",children:"Loading project overview"}),e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-hidden":"true"})]}):it&&i?e.jsxs("div",{role:"alert",className:"page-section-divider",children:[e.jsx("p",{children:"Could not load AI visibility."}),e.jsx(I,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[ke?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(I,{type:"button",size:"sm",variant:"outline",onClick:()=>{Ye.refetch()},children:"Retry setup check"})]}):null,Za(e.jsx(ay,{mode:ft,canEdit:m&&!ie()&&!Ae&&!ke,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(Ip,{projectName:s.project.name,competitorDomains:z,analyticsRevision:a})}),e.jsx(Vy,{model:s,sweepRunning:ot,hasVisibilityBaseline:ys}),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."})]})}),ys?e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsx(Nh,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:z},s.project.name),e.jsx("div",{className:"competitive-gaps",children:e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Va,{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(Va,{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(Dr,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[!ie()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(ze,{type:"button",variant:"outline",size:"sm",onClick:()=>ne(!oe),children:oe?"Done":"Manage queries"})}),!ie()&&oe&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[jt.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:jt.map(M=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsx("span",{className:"min-w-0 truncate text-sm text-strong",title:M,children:M}),e.jsx("button",{type:"button",className:"shrink-0 rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500 disabled:opacity-50","aria-label":`Remove query ${M}`,title:`Stop tracking "${M}"`,disabled:J!==null,onClick:()=>{Es(M)},children:J===M?"Removing…":"Remove"})]},M))}):e.jsx("p",{className:"mb-3 text-xs text-muted",children:"No queries tracked yet. Add some below."}),e.jsx("textarea",{className:"w-full resize-none rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:3,placeholder:"Enter queries to add, one per line",value:ye,onChange:M=>W(M.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[ye.split(`
|
|
8
|
-
`).filter(M=>M.trim()).length," to add"]}),e.jsx(ze,{type:"button",size:"sm",disabled:!ye.trim()||ue,onClick:He(Ya),children:ue?"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(M=>e.jsx("button",{className:`filter-chip ${we===M.label?"filter-chip-active":""}`,type:"button","aria-pressed":we===M.label,onClick:()=>{Se(M.label),Be(!1)},children:M.label},M.label)),nt&&e.jsx("button",{className:`filter-chip ${we===""?"filter-chip-active":""}`,type:"button","aria-pressed":we==="",onClick:()=>{Se(""),Be(!1)},children:"No location"}),rn.length>1&&we===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${Ze?"filter-chip-active":""}`,type:"button","aria-pressed":Ze,onClick:()=>Be(M=>!M),title:"Side-by-side location comparison",children:"Compare"})]}),_t.evidenceLoading?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading query evidence…"}):_t.evidenceError?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load query evidence."}),e.jsx(I,{type:"button",variant:"outline",onClick:()=>{_t.refetch()},children:"Retry"})]}):e.jsx(qh,{evidence:jn,compareLocations:Ze})]}),e.jsxs(Dr,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:ie(),children:[e.jsx(Fx,{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(Ue,{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(M=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(Tn,{provider:M.provider}),M.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:M.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[M.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[M.cited," of ",M.total]})]},`${M.provider}::${M.model??"unknown"}`))})]})})]})]}),!ie()&&e.jsx(Dr,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(M=>e.jsx(Wm,{run:M},M.id))})})]}),report:Oe,reportState:ut,onOpenSetup:ie()?void 0:()=>{h({to:"/projects/$projectName/portfolio",params:{projectName:y}})},onRetryReport:()=>{C===2?Promise.all([tt.refetch(),We.refetch()]):We.refetch()},onViewChange:M=>{Ge({scope:M.scope,...M.groupKey?{groupKey:M.groupKey}:{},queryClass:M.queryClass,...M.search?.trim()?{search:M.search.trim()}:{}})},onLoadMore:M=>{M===je?.properties.nextCursor&&tt.fetchNextPage()},onPropertyExpand:()=>{he&&We.isError&&We.refetch(),ht(!0)},onRetryEvidence:()=>{We.refetch()},isViewLoading:tt.isPlaceholderData,isLoadingMore:tt.isFetchingNextPage,isLoadMoreError:tt.isFetchNextPageError,viewSearch:qe.search??""},`${y}:${Re}`)),!it&&B.measurementScope==="project"?e.jsxs("details",{className:"page-section-divider",onToggle:M=>{M.currentTarget.open&&c()},children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm font-medium text-heading",children:"Project signals"}),!d||o?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading project signals…"}):i?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load project signals."}),e.jsx(I,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsx(zy,{insights:s.insights,suggestedQueries:s.suggestedQueries,onManageQueries:ie()?void 0:()=>{h({to:"/projects/$projectName/queries",params:{projectName:y},search:M=>({...M,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]},y):null,ms?e.jsxs("details",{className:"page-section-divider",open:Jt,onToggle:M=>gs(M.currentTarget.open?y: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(Ph,{window:K,landscape:Xt.data,pinnedFallback:G,canWrite:m,isEmbed:ie(),onWindowChange:xe,onPin:Je&&m&&!ie()?Fn:!Lt&&m&&!ie()?ua:void 0,onUnpin:Je||Lt||!m||ie()?void 0:ma,onAddCompetitor:Je&&m&&!ie()?Fn:!Lt&&m&&!ie()?ua:void 0,error:yt,onRetry:vt?()=>{Xt.refetch()}:void 0,isLoading:vt&&Xt.isPending&&Xt.data===void 0,scopeLabel:Je?`${Bt?.label??Je} group`:Lt?"All markets":"Project-wide"})]}):null]}):F==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(My,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(M,p)=>{await Gn(M,p)},onRefresh:()=>{n()}}),e.jsx(qy,{project:s.project,onSave:async M=>{await Gn(s.project.name,M)}}),m&&!ie()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Advanced measurement"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Measure individual properties, locations, or site sections with separate query sets."}),be==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):be==="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(I,{type:"button",size:"sm",variant:"outline",onClick:()=>{S.refetch()},children:"Retry"})]}):e.jsx(I,{type:"button",variant:"outline",onClick:()=>{h({to:"/projects/$projectName/portfolio",params:{projectName:y}})},children:ic(ft.setupAction)})]}):null,e.jsx(Dy,{projectName:s.project.name}),e.jsx(Fy,{projectName:s.project.name}),m&&!ie()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-negative-400",children:"Delete project"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Permanently deletes this project and all its queries, competitors, runs, and snapshots."}),V?e.jsxs(pe,{className:"surface-card p-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(I,{type:"button",variant:"destructive",disabled:Y,onClick:He(On),children:Y?"Deleting...":"Yes, delete project"}),e.jsx(I,{type:"button",variant:"outline",disabled:Y,onClick:()=>te(!1),children:"Cancel"})]})]}):e.jsxs(ze,{type:"button",variant:"outline",onClick:()=>te(!0),children:[e.jsx(bl,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):F==="report"?e.jsx(gy,{projectName:s.project.name}):F==="queries"||F==="discovery"?e.jsx(Kp,{projectName:y,queryWorkspace:_.queryWorkspace==="research"||F==="discovery"&&_.queryWorkspace===void 0?"research":"tracked",onQueryWorkspaceChange:M=>w({queryWorkspace:M,trackingQueryId:void 0}),researchMode:_.researchMode==="test"?"test":"find",onResearchModeChange:M=>w({researchMode:M}),selection:B,onSelectionChange:w,trackingQueryId:typeof _.trackingQueryId=="string"?_.trackingQueryId:void 0,onTrackingQueryIdChange:M=>w({trackingQueryId:M})}):F==="technical-aeo"?e.jsx(Ym,{projectName:s.project.name,projectId:s.project.id,initialRunId:_.siteHealthRunId,onReleaseInitialRun:se}):F==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(Zg,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(Fg,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):F==="history"?e.jsx(pg,{projectName:s.project.name}):F==="activity"?e.jsx(Jh,{projectName:s.project.name}):F==="backlinks"?e.jsx(Ox,{projectName:s.project.name}):F==="local"?e.jsx(xx,{projectName:s.project.name,projectId:s.project.id}):F==="search-console"?e.jsx(By,{projectName:s.project.name}):null]})}export{db as ProjectPage,Qy as ProjectSubnav,Gy as ProjectSweepConfirmation,_y as patchProjectDashboardCache};
|