@ainyc/canonry 4.191.0 → 4.192.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/assets/assets/{AuditHistoryPanel-C2dvjYNh.js → AuditHistoryPanel-DvqnrQc_.js} +1 -1
  2. package/assets/assets/{BacklinksPage-D1yPQtfF.js → BacklinksPage-BCk2qBfC.js} +1 -1
  3. package/assets/assets/{ChartPrimitives-DLEICrrL.js → ChartPrimitives-Bxa_vFmq.js} +1 -1
  4. package/assets/assets/{HistoryPage-DOEa7naA.js → HistoryPage-IMlkx--Q.js} +1 -1
  5. package/assets/assets/MeasurementPropertyPage-1o1e5vmH.js +1 -0
  6. package/assets/assets/ProjectPage-BusVoYaC.js +8 -0
  7. package/assets/assets/{RunRow-BO7lyC1C.js → RunRow-BherM7NU.js} +1 -1
  8. package/assets/assets/{RunsPage-DHSWfTav.js → RunsPage-B5G_OrmE.js} +1 -1
  9. package/assets/assets/{SettingsPage-oiJdhiq0.js → SettingsPage-CMeCn5uk.js} +1 -1
  10. package/assets/assets/{SiteHealthSection-gVdylFY-.js → SiteHealthSection-DZX1yv4k.js} +3 -3
  11. package/assets/assets/{TrafficPage-YIdwRpQh.js → TrafficPage-BV-HOztp.js} +1 -1
  12. package/assets/assets/{TrafficSourceDetailPage-B4Cop6ox.js → TrafficSourceDetailPage-9IN0q7bd.js} +1 -1
  13. package/assets/assets/{extract-error-message-XavUZNf3.js → extract-error-message-c7zJp5uX.js} +1 -1
  14. package/assets/assets/{index-njfYnO22.js → index-D3KGn0S0.js} +26 -26
  15. package/assets/assets/{react-sigma_core.esm.min-V7giUpEn.js → react-sigma_core.esm.min-DxHkjhKC.js} +1 -1
  16. package/assets/assets/{vendor-lucide-dNHw1I5G.js → vendor-lucide-CW2qe0uH.js} +1 -1
  17. package/assets/assets/{vendor-markdown-9tTeP8v7.js → vendor-markdown-B-Oq2NYq.js} +1 -1
  18. package/assets/assets/{vendor-radix-BpmvLvpp.js → vendor-radix-twS1M3FF.js} +1 -1
  19. package/assets/assets/{vendor-recharts-FA0uySU7.js → vendor-recharts-D-cUuLZo.js} +1 -1
  20. package/assets/assets/{vendor-tanstack-CYBjbqVr.js → vendor-tanstack-ZXXkndVj.js} +1 -1
  21. package/assets/index.html +6 -6
  22. package/dist/{chunk-KBUV3HGS.js → chunk-QRNKMGVD.js} +1351 -1228
  23. package/dist/{chunk-WSD5J6O4.js → chunk-S5QNBQ72.js} +2 -2
  24. package/dist/{chunk-XI6FN52S.js → chunk-T4OO575U.js} +45 -14
  25. package/dist/{chunk-ZK4FJDCH.js → chunk-T6GRXUOE.js} +519 -231
  26. package/dist/{chunk-2A7E5TDU.js → chunk-V4ZLHKOG.js} +5 -4
  27. package/dist/cli.js +14 -10
  28. package/dist/index.js +4 -4
  29. package/dist/{intelligence-service-EVRWZHDG.js → intelligence-service-QYRQHSJH.js} +2 -2
  30. package/dist/mcp.js +3 -3
  31. package/package.json +13 -13
  32. package/assets/assets/MeasurementPropertyPage-D-O8vnMS.js +0 -1
  33. package/assets/assets/ProjectPage-DqTCcimz.js +0 -8
@@ -1,8 +0,0 @@
1
- import{j as e,r as l,u as $e,L as ks,h as ms,o as Pt,B as ei,C as ac,k as rc,l as ic,D as oc}from"./vendor-tanstack-CYBjbqVr.js";import{T as de,t as lc,a as cc,M as Vo,I as _e,s as zo,B as P,b as dc,u as Qo,C as uc,P as $n,h as mc,c as hc,d as mn,g as Ho,e as Wo,f as fe,i as W,j as ae,k as Ct,l as He,m as xc,n as pc,o as gc,p as Yo,q as fc,r as yc,S as hn,v as bc,w as vc,x as Ts,y as Qt,z as jc,A as vi,D as Jo,G as _t,E as ti,F as Nc,H as wc,J as Sc,K as Cc,L as ji,N as Te,O as kc,Q as Ac,R as Ja,U as Pc,V as Rc,W as Ic,X as $c,Y as Tc,Z as Mc,_ as Lc,$ as qc,a0 as Ec,a1 as Dc,a2 as Oc,a3 as Fc,a4 as Gc,a5 as Kc,a6 as _c,a7 as Xo,a8 as Ys,a9 as Uc,aa as Zo,ab as Da,ac as Bc,ad as We,ae as Vc,af as zc,ag as Qc,ah as Oa,ai as Hc,aj as Wc,ak as Yc,al as pn,am as Jc,an as Xc,ao as Zc,ap as el,aq as Er,ar as ed,as as si,at as td,au as Xn,av as Js,aw as Ut,ax as sd,ay as nd,az as ad,aA as Xa,aB as Ln,aC as rd,aD as id,aE as od,aF as ld,aG as cd,aH as Yn,aI as Ni,aJ as ya,aK as Za,aL as dd,aM as ud,aN as wi,aO as er,aP as xn,aQ as md,aR as tl,aS as sl,aT as hd,aU as xd,aV as Si,aW as pd,aX as gd,aY as fd,aZ as yd,a_ as bd,a$ as vd,b0 as jd,b1 as Nd,b2 as wd,b3 as Sd,b4 as Cd,b5 as kd,b6 as Ad,b7 as Pd,b8 as Rd,b9 as Id,ba as $d,bb as Td,bc as Md,bd as Ld,be as qd,bf as Ed,bg as Dd,bh as Od,bi as Fd,bj as Gd,bk as Kd,bl as _d,bm as js,bn as Ud,bo as pt,bp as Bd,bq as Vd,br as zd,bs as Qd,bt as Hd,bu as Wd,bv as Yd,bw as Jd,bx as Xd,by as Zd,bz as eu,bA as tu,bB as su,bC as nu,bD as au,bE as ru,bF as iu,bG as ou,bH as lu,bI as cu,bJ as du,bK as uu,bL as mu,bM as hu,bN as xu,bO as pu,bP as gu,bQ as fu,bR as yu,bS as bu,bT as vu,bU as ju,bV as Nu,bW as wu,bX as Su,bY as Cu,bZ as ku,b_ as Au,b$ as Pu,c0 as nl,c1 as tr,c2 as Ru,c3 as Ci,c4 as Iu,c5 as $u,c6 as Tu,c7 as Mu,c8 as Lu,c9 as qu,ca as Eu,cb as al,cc as Du,cd as rl,ce as il,cf as ol,cg as ll,ch as Ou,ci as Fu,cj as Gu,ck as Ku,cl as _u,cm as Uu,cn as ki,co as Bu,cp as Vu,cq as zu,cr as Qu,cs as Hu,ct as Ai,cu as Wu,cv as Yu,cw as Ju,cx as Xu,cy as Zu,cz as em,cA as Fa,cB as tm,cC as sr,cD as sm,cE as nm,cF as am,cG as rm,cH as im,cI as om,cJ as lm,cK as cm,cL as dm,cM as um,cN as cl,cO as mm,cP as hm,cQ as xm,cR as pm,cS as gm,cT as fm,cU as ba,cV as ym,cW as bm,cX as vm,cY as Pi,cZ as jm}from"./index-njfYnO22.js";import{C as gn,e as Ga,q as Zn,U as Nm,r as wm,L as Sm,s as Cm,i as km,P as Ka,D as dl,t as Am,u as ul,v as Pm,d as Rm,E as Im,p as $m,w as Tm,x as ml}from"./vendor-lucide-dNHw1I5G.js";import{R as Mm}from"./RunRow-BO7lyC1C.js";import{u as fn,D as Qs,a as qs,b as hl,M as La,c as Rs,S as Lm}from"./SiteHealthSection-gVdylFY-.js";import{C as ea,f as yn,a as ds,b as Tt,c as Bt,d as es,e as nt,g as us,h as Es,M as xl,i as pl,o as Ds,j as Hs,p as qm}from"./ChartPrimitives-DLEICrrL.js";import{u as Em,a as Dm,b as Om,t as Fm,e as Gm,c as ft}from"./extract-error-message-XavUZNf3.js";import{R as Xs,C as Zs,a as ta,X as en,Y as tn,T as sn,b as Dr,L as _a,A as Bs,d as Ls,e as Km}from"./vendor-recharts-FA0uySU7.js";import{M as _m}from"./vendor-markdown-9tTeP8v7.js";import{A as Um}from"./AuditHistoryPanel-C2dvjYNh.js";import{a as Bm,b as Vm}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-BpmvLvpp.js";import"./vendor-yaml-GWJz5H2G.js";function Ws(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function zm(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=Qm(r,1));return a}function Qm(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 Hm(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 Wm(t,s){const n=Hm(t,s);return n===null?null:Math.round(n*100)}function nr(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Ws(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Ws(t.prior)} ${s})`:`Flat ${n} (${Ws(t.prior)} ${s})`}const gl=30;function Ri(t){return Math.round(t*10)/10}function Ym(t){return t.prior>=gl&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Ri(t.deltaAbs)} vs ${Ri(t.prior)}`}function Jm(t,s,n){return t.prior>=gl&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Ws(Math.round(t.deltaAbs))} ${s} ${n}`}function Xm(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 Zm=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function fl(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function yl(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 bl(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(fl).map(yl).filter(Boolean)):new Set}function vl(t,s){const n=fl(t).map(yl).filter(Boolean).filter(a=>!Zm.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function eh(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function th(t,s){const n=bl(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=vl(eh(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function sh(t){const s=bl(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=vl(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const nh=1e6;function ah(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/nh)}const ni={queryClass:"all"},rh=["all","non-brand","branded"];function jl(t){return typeof t=="string"&&rh.includes(t)}function Nl(t){const s=jl(t.class)?t.class:ni.queryClass,n=t.scope;if(typeof n!="string"||n==="all"||n.length===0)return{scope:"all",queryClass:s};const a=n.startsWith("group:")?n.slice(6):"";return a?{scope:"group",groupKey:a,queryClass:s}:{scope:"all",queryClass:s}}function ih(t,s){return s===null||t===null?!1:t!==s}function oh(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===ni.queryClass?void 0:t.queryClass}}function lh(t,s){if(!(typeof t!="string"||t.length>16384||!s))try{const n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return;const a=n,r=i=>typeof i=="string"&&i.trim().length>0,o=i=>i===null||r(i);return a.queryKey!==s||!r(a.provider)||a.queryClass!=="branded"&&a.queryClass!=="non-brand"&&a.queryClass!=="unknown"||!o(a.model)||!o(a.location)||!o(a.runId)||a.revision!==null&&(typeof a.revision!="number"||!Number.isSafeInteger(a.revision)||a.revision<=0)?void 0:{queryKey:s,queryClass:a.queryClass,provider:a.provider,model:a.model,location:a.location,runId:a.runId,revision:a.revision}}catch{return}}function ch(t){const s=u=>typeof t[u]=="string"&&t[u]!==""?t[u]:void 0,n=Nl({scope:s("scope"),class:s("class")}),a=s("measurementScope")??(n.scope==="group"?"group":"project"),r=s("measurementScopeKey")??(s("measurementScope")?void 0:n.groupKey),o=s("queryClass")??s("class"),i={measurementScope:r&&(a==="group"||a==="market"||a==="property")?a:"project",queryClass:o==="unknown"||jl(o)?o:ni.queryClass};i.measurementScope!=="project"&&(i.measurementScopeKey=r);for(const[u,h]of[["measurementProvider","provider"],["measurementModel","model"],["measurementLocation","location"],["measurementFrom","from"],["measurementTo","to"],["measurementRunId","measurementRunId"],["measurementQueryKey","queryKey"]]){const m=s(u);m!==void 0&&(i[h]=m)}const c=Number(t.measurementRevision);Number.isSafeInteger(c)&&c>0&&(i.revision=c);const d=lh(t.measurementAnswer,i.queryKey);return d&&(i.answer=d),i}function dh(t,s){const n={...t,...s};return["measurementScope","measurementScopeKey","queryClass","measurementProvider","measurementModel","measurementLocation","measurementFrom","measurementTo","measurementRevision","measurementRunId"].some(a=>a in s)?(n.measurementQueryKey=s.measurementQueryKey,n.measurementAnswer=s.measurementAnswer):"measurementQueryKey"in s&&!("measurementAnswer"in s)&&(n.measurementAnswer=void 0),"measurementScope"in s&&(n.scope=void 0,n.measurementQueryKey=void 0,s.measurementScope==="project"&&(n.measurementScopeKey=void 0)),"queryClass"in s&&(n.class=void 0),n}function Or({state:t,label:s}){return e.jsx(de,{tone:cc(t),children:s??lc(t)})}const an=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Ii={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},uh={"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."},mh="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function hh(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 xh({breakdown:t,projectLabel:s,competitorDomains:n}){const a=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(a===0)return null;const r=new Map(t.perCompetitor.map(i=>[i.domain,i.mentionSnapshots])),o=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...n.map(i=>({label:i,mentions:r.get(i)??0,isYou:!1}))].sort((i,c)=>c.mentions-i.mentions||(i.label<c.label?-1:1));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(_e,{text:mh})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:o.map(i=>{const c=i.mentions/a*100;return e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${i.isYou?"text-heading font-medium":"text-secondary"}`,children:i.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${i.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${c>0?Math.max(c,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:i.mentions}),e.jsxs("td",{className:"mention-share-share",children:[c.toFixed(1),"%"]})]},i.label)})})]})}function ph({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=l.useState("non-brand"),o=l.useId(),i=t.scope==="pooled",c=!i&&t.branded.snapshotsTotal>0,d=c?a:"non-brand",u=i?"pooled":d,h=d==="branded"?t.branded:t.breakdown,m=d==="branded"?t.breakdown:t.branded,b=hh(h,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:m.snapshotsTotal>0}),p=u==="non-brand"?Vo[t.tone]:"text-secondary";function x(g){const f=an.findIndex(S=>S.value===d);let N=null;g.key==="ArrowRight"||g.key==="ArrowDown"?N=(f+1)%an.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?N=(f-1+an.length)%an.length:g.key==="Home"?N=0:g.key==="End"&&(N=an.length-1),N!==null&&(g.preventDefault(),r(an[N].value),g.currentTarget.querySelectorAll('[role="radio"]')[N]?.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(_e,{text:uh[u]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:x,children:an.map(g=>{const f=g.value===d;return e.jsx("button",{type:"button",role:"radio","aria-checked":f,tabIndex:f?0:-1,onClick:()=>r(g.value),className:`segmented-option min-h-11 ${f?"segmented-option-active":""}`,children:g.label},g.value)})}):e.jsx("span",{className:"mention-share-class",children:Ii[u]})]}),b.numeric?e.jsxs("p",{className:`mention-share-value ${p}`,children:[b.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:b.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:Ii[u]}),` · ${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(xh,{breakdown:h,projectLabel:s,competitorDomains:n})]})}const rn=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],$i=5;function gh(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 fh(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function ar(t){return t==="unavailable"?"Unavailable":"Not measured"}function wl(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 yh({value:t,onChange:s}){function n(a){const r=rn.findIndex(c=>c.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%rn.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+rn.length)%rn.length:a.key==="Home"?o=0:a.key==="End"&&(o=rn.length-1),o===null)return;a.preventDefault();const i=rn[o];s(i.value),a.currentTarget.querySelectorAll('[role="radio"]')[o].focus()}return e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"block text-sm font-medium text-heading",children:"History"}),e.jsx("div",{role:"radiogroup","aria-label":"Competitor history window",className:"segmented",onKeyDown:n,children:rn.map(a=>{const r=a.value===t;return e.jsx("button",{type:"button",role:"radio","aria-checked":r,tabIndex:r?0:-1,onClick:()=>s(a.value),className:`segmented-option min-h-11 ${r?"segmented-option-active":""}`,children:a.label},a.value)})})]})}function Fr({row:t,isProject:s=!1,metricState:n="measured",shareContext:a,canManage:r,onPin:o,onUnpin:i}){const c=!s&&r&&!t.pinned&&!!o,d=!s&&r&&t.pinned&&!!i,u=n==="measured",h=u&&t.sampleUrls.length>0,[m,b]=l.useState(!1),[p,x]=l.useState(null);async function g(f,N){if(!(!N||m)){b(!0),x(null);try{await N(t.domain)===!1&&x(`Could not ${f} competitor. Try again.`)}catch{x(`Could not ${f} competitor. Try again.`)}finally{b(!1)}}}return e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"font-medium text-heading",children:[t.label,s?e.jsx("span",{className:"ml-1 text-secondary",children:"(you)"}):null]}),e.jsx("td",{className:"text-secondary",children:s?"Your brand":wl(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:u?dc(t.shareOfVoice,a):ar(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:u?t.mentionCount:ar(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:u?t.citationCount:ar(n)}),e.jsx("td",{className:"text-right",children:c||d||h?e.jsxs("div",{className:"flex min-w-max items-start justify-end gap-2",children:[h?e.jsxs("details",{className:"inline-disclosure text-left text-xs text-secondary",children:[e.jsx("summary",{children:"Source URLs"}),e.jsx("ul",{className:"mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal",children:t.sampleUrls.map(f=>e.jsx("li",{className:"break-all",children:f},f))})]}):null,d&&i?e.jsxs(P,{type:"button",size:"sm",variant:"outline",disabled:m,onClick:()=>{g("unpin",i)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,c&&o?e.jsxs(P,{type:"button",size:"sm",variant:"outline",disabled:m,onClick:()=>{g("pin",o)},children:["Pin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,p?e.jsx("span",{role:"alert",className:"sr-only",children:p}):null]}):e.jsx("span",{className:"text-faint",children:"—"})})]})}function Gr({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function bh({rows:t,shareContext:s,canManage:n,onPin:a}){const[r,o]=l.useState(!1),i=r?t:t.slice(0,$i);return e.jsxs("tbody",{children:[e.jsx(Gr,{children:"Observed in this window"}),i.map(c=>e.jsx(Fr,{row:{...c,pinned:!1},shareContext:s,canManage:n,onPin:a},c.domain)),t.length>$i?e.jsx("tr",{children:e.jsx("td",{colSpan:6,children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-sm text-secondary",children:["Showing ",i.length," of ",t.length," observed competitors."]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11 text-sm","aria-expanded":r,"aria-label":r?"Show fewer observed competitors":`Show all ${t.length} observed competitors`,onClick:()=>o(c=>!c),children:r?"Show fewer":`Show all ${t.length}`})]})})}):null]})}function vh({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,c]=l.useState(null);async function d(){const u=n.trim();if(!(!u||r)){o(!0),c(null);try{if(await t(u)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("Could not add competitor. Try again.")}finally{o(!1)}}}return e.jsxs("details",{className:"inline-disclosure competitor-landscape-manage",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:u=>{u.preventDefault(),d()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:u=>a(u.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(P,{type:"submit",size:"sm",className:"min-h-10",disabled:r||!n.trim(),children:r?"Adding…":"Add competitor"}),i?e.jsx("p",{role:"alert",className:"w-full text-sm text-negative",children:i}):null]})]})}function jh({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:c,onAddCompetitor:d,error:u,onRetry:h,isLoading:m=!1,scopeLabel:b}){const p=a&&!r,x=s?.pinned??n,g=s?.observed??[],f=s?.otherSources??[],N=s?.evidence,S=fh(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:gh(s.filters?.queryClass)}):null,s?.reason?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:zo(s.reason)}):null]}),e.jsx(yh,{value:t,onChange:o})]}),u?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:[e.jsx("span",{children:u}),h?e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:h,children:"Retry competitor history"}):null]}):null,m&&!s&&x.length===0?e.jsx("div",{role:"status","aria-live":"polite",className:"h-48 animate-pulse rounded-md bg-surface-subtle",children:e.jsx("span",{className:"sr-only",children:"Loading competitor history"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table","aria-label":"Competitor landscape",children:[e.jsx("caption",{className:"sr-only",children:"Pinned competitors followed by competitors observed in the selected history window."}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Competitor"}),e.jsx("th",{scope:"col",children:"Type"}),e.jsx("th",{scope:"col",children:"Share of voice"}),e.jsx("th",{scope:"col",children:"Mentions"}),e.jsx("th",{scope:"col",children:"Citations"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsxs("tbody",{children:[s?e.jsxs(e.Fragment,{children:[e.jsx(Gr,{children:"You"}),e.jsx(Fr,{row:s.project,shareContext:s,isProject:!0,metricState:S,canManage:!1})]}):null,e.jsx(Gr,{children:"Pinned"}),x.length>0?x.map(R=>e.jsx(Fr,{row:{...R,pinned:!0},shareContext:s,metricState:S,canManage:p,onUnpin:c},R.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s&&g.length>0?e.jsx(bh,{shareContext:s,rows:g,canManage:p,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),N?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:[N.answeredResults," ",N.answeredResults===1?"answer":"answers"]}),N.missingAnswerTextResults>0?e.jsx("span",{className:"text-caution",children:"Answer data incomplete"}):null,N.incompleteSourceResults>0?e.jsx("span",{className:"text-caution",children:"Citation data incomplete"}):null]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:["About these results",e.jsx(gn,{size:14,"aria-hidden":"true",className:"transition-transform group-open:rotate-180 motion-reduce:transition-none"})]})]}),e.jsxs("div",{className:"max-w-prose space-y-2 pb-2 pt-1",children:[g.length===0?e.jsx("p",{children:"No additional competitors were identified in this period."}):null,e.jsxs("p",{children:[N.sourceResults," ",N.sourceResults===1?"result includes":"results include"," source URLs."]}),N.missingAnswerTextResults>0?e.jsxs("p",{children:[N.missingAnswerTextResults," ",N.missingAnswerTextResults===1?"result has":"results have"," no answer text and ",N.missingAnswerTextResults===1?"is":"are"," excluded from mention share."]}):null,N.incompleteSourceResults>0?e.jsxs("p",{children:[N.incompleteSourceResults," ",N.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,N.excludedProbeResults+N.excludedNonCompletedResults>0?e.jsxs("p",{children:[N.excludedProbeResults+N.excludedNonCompletedResults," test or unfinished ",N.excludedProbeResults+N.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(R=>e.jsxs("li",{children:[R.name," · ",R.answerCount," answers"]},R.name))})]}):null,f.length>0?e.jsxs("details",{className:"inline-disclosure",children:[e.jsxs("summary",{children:["Other observed sources (",f.length,")"]}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:f.map(R=>e.jsxs("li",{children:[e.jsxs("span",{children:[R.label," · ",wl(R.surfaceClass)," · ",R.citationCount," citations"]}),R.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:R.sampleUrls.map(y=>e.jsx("li",{className:"break-all",children:y},y))}):null]},R.domain))})]}):null]}),p&&d?e.jsx(vh,{onAddCompetitor:d}):null]})}function Ti({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},r={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},o=n.length-1,i=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=new Date(n[o].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),d=n.map((u,h)=>{const m=new Date(u.createdAt).toLocaleDateString();return`${h===o?"Latest run, ":""}${m}: ${u.citationState}${u.model?`, model ${u.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${d}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((u,h)=>{const m=!!(u.model&&h>0&&n[h-1]?.model&&n[h-1].model!==u.model),b=h===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[u.citationState]??"rounded-sm"} ${a[u.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:[u.citationState,new Date(u.createdAt).toLocaleDateString(),u.model?`model ${u.model}`:null,m?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${u.runId}:${u.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[c," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function Kr(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 Nh=320;function wh(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function Sh(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function Mi(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 Li(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 qi(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const r=t[t.length-1].citationState,o=t[t.length-2].citationState;if(o!=="cited"&&r==="cited")return`Newly ${n}`;if(o==="cited"&&r!=="cited")return"Lost since last run";let i=0;for(let c=t.length-1;c>=0&&t[c].citationState===r;c--)i++;return r==="cited"?i<=1?`${a} in latest run`:`${a} for ${i} runs`:i<=1?`Not ${n} in latest run`:`Not ${n} across ${i} runs`}function Ch(t,s){return t.map(n=>Sl(n,s))}function Sl(t,s){return s==="citations"?t:{...t,citationState:Mi(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Mi(n,s)}))}}function Ei(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,o=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",c=o==="cited"||o==="emerging";return r==="lost"||o!==null&&c&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||o!==null&&!c&&i?{key:s,label:`New ${n}`,tone:"positive"}:o===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function kh(t){const s=Kr(Ch(t,"mentions")),n=Kr(t);return[Ei(s,"mentions"),Ei(n,"citations")]}function Ah({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 Di({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:kh(t).map(s=>e.jsx(Ah,{signal:s},s.key))})}function Ph({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Qo(),[r,o]=l.useState(new Set),[i,c]=l.useState("mentions"),[d,u]=l.useState(n),[h,m]=l.useState("all"),b=l.useMemo(()=>{const y=new Map;for(const j of t){const A=j.query,E=j.queryClass??null,D=s?j.location??null:null,F=JSON.stringify([A,E,D]),V=y.get(F)??{key:F,phrase:A,queryClass:E,location:D,items:[],rawItems:[]};V.items.push(Sl(j,i)),V.rawItems.push(j),y.set(F,V)}return[...y.values()]},[t,i,s]),p=l.useMemo(()=>b.filter(y=>h==="all"||(h==="unclassified"?y.queryClass===null:y.queryClass===h)),[b,h]),x=fn({rows:p,getSearchText:Sh}),g=x.rows.map(y=>y.key),f=g.length>0&&g.every(y=>r.has(y)),N=y=>{o(j=>{const A=new Set(j);return A.has(y)?A.delete(y):A.add(y),A})},S=i==="mentions"?"mentioned":"cited",q=i==="mentions"?"Mention History":"Citation History",R=i==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":i==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>c("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":i==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>c("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:i==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{o(y=>{const j=new Set(y);for(const A of g)f?j.delete(A):j.add(A);return j})},children:f?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":d==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":d==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("detailed"),children:"Detailed"})]})]})]})]}),b.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(Qs,{value:x.query,onChange:x.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"w-full max-w-md"}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-secondary",children:["Query class",e.jsxs("select",{value:h,onChange:y=>{m(y.target.value),x.setPage(1)},className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:[e.jsx("option",{value:"all",children:"All queries"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]})]}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:q}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:x.rows.map(({key:y,phrase:j,queryClass:A,location:E,items:D,rawItems:F})=>{const V=r.has(y),B=D.map(O=>O.citationState),w=B.includes("cited")?"cited":B.includes("emerging")?"emerging":B.includes("lost")?"lost":B.every(O=>O==="pending")?"pending":"not-cited",G=Kr(D),L=D.filter(O=>O.citationState===uc.cited||O.citationState==="emerging").length,ee=qi(G,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:()=>N(y),onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),N(y))},tabIndex:0,role:"button","aria-expanded":V,children:[e.jsx("td",{children:e.jsx(Ga,{size:14,className:`transition-transform duration-150 text-muted ${V?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:j}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:E??"No location"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.jsx(de,{tone:"neutral",className:"whitespace-nowrap",children:wh(A)}),D.map(O=>e.jsx($n,{provider:O.provider},O.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{state:w,label:Li(w,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${L} of ${D.length} engines ${R}`,children:[L,"/",D.length]})]})}),e.jsx("td",{children:e.jsx(Ti,{history:G})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ee}),e.jsx(Di,{items:F})]}),e.jsx("td",{})]}),V&&D.map((O,X)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx($n,{provider:O.provider})}),e.jsx("td",{children:e.jsx(Or,{state:O.citationState,label:Li(O.citationState,i)})}),e.jsx("td",{children:e.jsx(Ti,{history:O.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:qi(O.runHistory,i)}),e.jsx(Di,{items:[F[X]??O]})]}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",size:"sm",type:"button",onClick:oe=>{oe.stopPropagation(),a(O.id)},children:"View"})})]}),d==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx($h,{item:O,onViewFull:()=>a(O.id)})})]})]},O.id))]},y)})})]})}),x.totalRows===0&&(x.hasQuery||h!=="all")?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(qs,{page:x.page,pageSize:x.pageSize,visibleRows:x.rows.length,totalRows:x.totalRows,onPageChange:x.setPage,itemLabel:x.hasQuery||h!=="all"?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",S==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Rh(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=hc(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 Oi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function Ih(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 $h({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}=Ih(t.answerSnippet,Nh),o=Rh(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:mc(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] ${Oi(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,Oi(t,i)?" · competitor source":""]},`c-${i}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors in answer:"}),t.mentionedCompetitorDomains.slice(0,4).map(i=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:i},`co-${i}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:i=>{i.stopPropagation(),s()},children:"View full answer →"})]})}function va({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}function Ha({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 rr=nt[0],ir=nt[1],Fi=nt[2],Gi=nt[3],Th=["both","server","ga4"],Ki={fontSize:11,paddingTop:6},_i=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Ui=t=>typeof t=="number"?Ws(Math.round(t)):String(t),as=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function or(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 lr({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(_e,{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 Mh(t,s){return n=>{const{cx:a,cy:r,index:o,key:i}=n,c=o??-1;return!(t[c]!=null&&t[c-1]==null&&t[c+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function Lh({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,c]=l.useState("both"),d=Em(t,{sinceMinutes:s,granularity:"day",limit:1}),u=Dm(t),m=$e({...Ho({client:W,path:{name:t}}),enabled:!!t,staleTime:mn}).data?.connected===!0,b=$e({...Wo({client:W,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&m,staleTime:mn}),p=l.useMemo(()=>d.data?.series?.points??[],[d.data]),x=l.useMemo(()=>{const E=b.data;return new Map((E?.days??[]).map(D=>[D.date,D.sessions]))},[b.data]),g=l.useMemo(()=>{const E=F=>F.measured!==!1;if(p.length===0||E(p[0]))return null;const D=p.findIndex(E)-1;return D<0?{from:p[0].bucket,to:p[p.length-1].bucket}:{from:p[0].bucket,to:p[D].bucket}},[p]),f=d.data?.series?.coverageStart??null,N=d.data?.series?.trends,S=l.useMemo(()=>{const E=or(N?.crawlerContentHits,p.length),D=or(N?.aiUserFetchHits,p.length),F=or(N?.aiReferralLandedHits,p.length);return p.map((V,B)=>({...V,crawlerContentHits:V.measured!==!1?as(V.crawlerContentHits):null,aiUserFetchHits:V.measured!==!1?as(V.aiUserFetchHits):null,aiReferralLandedHits:V.measured!==!1?as(V.aiReferralLandedHits):null,ga4Visits:x.get(V.bucket)??null,crawlTrend:E[B],fetchTrend:D[B],visitTrend:F[B]}))},[p,x,N]),q=d.data?.totals,R=q&&{crawlers:as(q.crawlerContentHits),fetches:as(q.aiUserFetchHits),visits:as(q.aiReferralLandedHits)},y=l.useMemo(()=>p.reduce((E,D)=>({crawlers:E.crawlers+as(D.crawlerContentHits),fetches:E.fetches+as(D.aiUserFetchHits),visits:E.visits+as(D.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[p]),j=R??y,A=j.crawlers>0||j.fetches>0||j.visits>0;if(d.isLoading)return e.jsx(fe,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(d.isError)return e.jsxs(fe,{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(!A){const E=u.data?.sources,D=E!==void 0&&E.length===0,F=!D&&f===null;return e.jsxs(fe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:D?"No server-side traffic source connected yet.":F?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:D?"Connect a traffic source to see how AI engines read this site over time.":F?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(fe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(lr,{label:"AI crawlers",value:Ws(j.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(lr,{label:"AI page fetches",value:Ws(j.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(lr,{label:"AI visitors",value:Ws(j.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),p.length>0&&e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-xs text-muted",children:[e.jsx("span",{className:"text-secondary font-semibold",children:"Latest day (UTC)"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(p[p.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(p[p.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:as(p[p.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:x.get(p[p.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(_e,{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:E=>a(E.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:E=>o(E.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Xs,{width:"100%",height:206,children:e.jsxs(Zs,{data:S,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(ta,{stroke:ea,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Tt,stroke:ds,tickFormatter:yn,minTickGap:28}),e.jsx(tn,{tick:Tt,stroke:ds,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:es.contentStyle,labelStyle:es.labelStyle,itemStyle:es.itemStyle,labelFormatter:Bt,formatter:Ui}),g&&e.jsx(Dr,{x1:g.from,x2:g.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(_a,{wrapperStyle:Ki,iconType:"plainline",iconSize:14,formatter:E=>_i.has(E)?"":E}),e.jsx(Bs,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:rr,fill:rr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Bs,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:ir,fill:ir,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Ls,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:rr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Ls,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:ir,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(_e,{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(Ha,{windows:Th,value:i,onChange:c,label:"Visit measurement source",formatOption:E=>E==="ga4"?"GA4":E==="both"?"Both":"Server"})]}),e.jsx(Xs,{width:"100%",height:176,children:e.jsxs(Zs,{data:S,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(ta,{stroke:ea,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Tt,stroke:ds,tickFormatter:yn,minTickGap:28}),e.jsx(tn,{tick:Tt,stroke:ds,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:es.contentStyle,labelStyle:es.labelStyle,itemStyle:es.itemStyle,labelFormatter:Bt,formatter:Ui}),g&&e.jsx(Dr,{x1:g.from,x2:g.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(_a,{wrapperStyle:Ki,iconType:"plainline",iconSize:14,formatter:E=>_i.has(E)?"":E}),i!=="ga4"&&e.jsx(Ls,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Fi,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Ls,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Gi,strokeWidth:1.8,strokeDasharray:"5 3",dot:Mh(S.map(E=>E.ga4Visits),Gi)}),r&&i!=="ga4"&&e.jsx(Ls,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Fi,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const qh=6,Tn="__other__",Rn="_socialTotal";function Eh(t,s=qh){const n=new Map;for(const h of t)n.set(h.source,(n.get(h.source)??0)+h.sessions);const a=[...n.entries()].sort((h,m)=>m[1]!==h[1]?m[1]-h[1]:h[0].localeCompare(m[0])),r=a.slice(0,s),o=new Set(r.map(([h])=>h)),i=Math.max(0,a.length-s),c=new Map;for(const h of t){let m=c.get(h.date);m||(m={date:h.date,[Rn]:0},c.set(h.date,m));const b=o.has(h.source)?h.source:Tn;m[b]=(m[b]??0)+h.sessions,m[Rn]=(m[Rn]??0)+h.sessions}const d=[...c.values()].sort((h,m)=>String(h.date).localeCompare(String(m.date))),u=r.map(([h])=>h);return i>0&&u.push(Tn),{data:d,sources:u,otherCount:i}}function In(t){return t.replace(/\+/g," ")}function Cl(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Bi="_totalSessions",Vi="_organicSessions";function Dh(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Bi]:i.sessions,[Vi]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[Bi]:0,[Vi]:0},n.set(i.date,c));for(const d of i.bySource)c[d.source]=(c[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([i],[c])=>i.localeCompare(c)).map(([i,c])=>({date:i,...c})),r=a.map(i=>i.date),o=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:o}}const Oh=["7d","30d","90d"],Fh={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Us=nt,_r=us.textDim,kl=us.textFaint,Kn=25;function Gh(t){return hl(t.landingPage)}const Kh=25,_h=10,cr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function ja(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Al(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 Uh({projectName:t}){const{data:s,isLoading:n,isError:a}=Om(t);if(n)return e.jsx(fe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(fe,{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."," ",!ae()&&e.jsx(ks,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(fe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ae()&&e.jsxs(e.Fragment,{children:[e.jsx(ks,{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(fe,{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(de,{tone:Fm(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?Al(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ae()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(ks,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function Bh({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Uh,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Ha,{windows:Oh,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(Vh,{projectName:t,window:s}),e.jsx(Lh,{projectName:t,sinceMinutes:Fh[s]})]})}function Vh({projectName:t,window:s}){const n=ms(),a=s??"30d",[r,o]=l.useState(null),[i,c]=l.useState(null),[d,u]=l.useState(!0),[h,m]=l.useState(!1),[b,p]=l.useState(!1),[x,g]=l.useState(null),[f,N]=l.useState(null),[S,q]=l.useState("sessions"),[R,y]=l.useState("desc"),[j,A]=l.useState("sessions"),[E,D]=l.useState("desc"),[F,V]=l.useState("sessions"),[B,w]=l.useState("desc"),[G,L]=l.useState("sessions"),[ee,O]=l.useState("desc"),[X,oe]=l.useState(cr),[k,I]=l.useState([]),[$,te]=l.useState([]),[le,pe]=l.useState(!1);async function ie(J){u(!0),g(null);try{const qe=await n.fetchQuery({...Ho({client:W,path:{name:t}}),staleTime:mn});if(J.current)return;if(o(qe),!qe.connected){c(null),oe(cr),I([]),te([]),u(!1);return}const Pe=a==="all"?void 0:a,Re=await n.fetchQuery({...xc({client:W,path:{name:t},query:Pe?{window:Pe}:void 0}),staleTime:mn}).then(xt=>xt),Ht=Re.windowStart||Re.windowEnd?{...Re.windowStart?{startDate:Re.windowStart}:{},...Re.windowEnd?{endDate:Re.windowEnd}:{}}:void 0,[jt,Rt,qt]=await Promise.all([n.fetchQuery({...Wo({client:W,path:{name:t},query:Pe?{window:Pe}:void 0}),staleTime:mn}).catch(()=>cr),n.fetchQuery({...pc({client:W,path:{name:t},query:Pe?{window:Pe}:void 0}),staleTime:mn}).catch(()=>[]),n.fetchQuery({...gc({client:W,path:{name:t},query:Ht}),staleTime:mn}).catch(()=>[])]);if(J.current)return;c(Re),oe(jt),I(Rt),te(qt),u(!1)}catch(qe){if(J.current)return;g(qe instanceof Error?qe.message:"Failed to load GA4 data"),u(!1)}}l.useEffect(()=>{const J={current:!1};return ie(J),()=>{J.current=!0}},[t,a,n]);async function Ne(){m(!0),g(null),N(null);try{const J=await Yo(t);N(`Synced ${J.rowCount.toLocaleString()} page rows, ${J.aiReferralCount.toLocaleString()} AI and ${J.socialReferralCount.toLocaleString()} social referral rows (${J.days} days)`),await Ct(n,"ga"),await ie({current:!1})}catch(J){g(J instanceof Error?J.message:"Sync failed")}finally{m(!1)}}async function Y(){p(!0),g(null),N(null);try{await fc(t),await Ct(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),N("GA4 disconnected")}catch(J){g(J instanceof Error?J.message:"Disconnect failed")}finally{p(!1)}}function z(J){ce.setPage(1),S===J?y(qe=>qe==="desc"?"asc":"desc"):(q(J),y("desc"))}function ne(J){j===J?D(qe=>qe==="desc"?"asc":"desc"):(A(J),D("desc"))}function Z(J){F===J?w(qe=>qe==="desc"?"asc":"desc"):(V(J),w("desc"))}const be=l.useMemo(()=>i?.topPages?[...i.topPages].sort((J,qe)=>{const Pe=J[S],Re=qe[S];return typeof Pe=="string"&&typeof Re=="string"?R==="asc"?Pe.localeCompare(Re):Re.localeCompare(Pe):R==="asc"?Pe-Re:Re-Pe}):[],[i?.topPages,S,R]),ce=fn({rows:be,getSearchText:J=>hl(J.landingPage),pageSize:_h}),De=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((J,qe)=>{const Pe=J[j],Re=qe[j];return typeof Pe=="string"&&typeof Re=="string"?E==="asc"?Pe.localeCompare(Re):Re.localeCompare(Pe):E==="asc"?Pe-Re:Re-Pe}):[],[i?.aiReferrals,j,E]),we=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((J,qe)=>{const Pe=J[G],Re=qe[G];return typeof Pe=="string"&&typeof Re=="string"?ee==="asc"?Pe.localeCompare(Re):Re.localeCompare(Pe):ee==="asc"?Pe-Re:Re-Pe}):[],[i?.aiReferralLandingPages,G,ee]),Se=fn({rows:we,getSearchText:Gh,pageSize:Kh}),Je=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 Ue(J){Se.setPage(1),G===J?O(qe=>qe==="desc"?"asc":"desc"):(L(J),O("desc"))}const Be=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((J,qe)=>{const Pe=J[F],Re=qe[F];return typeof Pe=="string"&&typeof Re=="string"?B==="asc"?Pe.localeCompare(Re):Re.localeCompare(Pe):B==="asc"?Pe-Re:Re-Pe}):[],[i?.socialReferrals,F,B]),{socialChartData:ze,socialChartSources:Oe,socialOtherCount:_}=l.useMemo(()=>{const J=Eh($);return{socialChartData:J.data,socialChartSources:J.sources,socialOtherCount:J.otherCount}},[$]),{chartData:U,chartSources:H,dateRange:Ie}=l.useMemo(()=>{const J=Dh(X,k);return{chartData:J.data,chartSources:J.sources,dateRange:J.dateRange}},[X,k]);if(d&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return ae()?e.jsx(fe,{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 Ct(n,"ga"),await ie({current:!1})))()}});const Ge=i?.organicSharePctDisplay??"0%",se=i?.channelBreakdown?.organic.sharePctDisplay??Ge,Xe=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,ut=i?.aiSessionsDeduped??0,mt=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,Ve=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Fe=i?.paidAiSessionsBySession??0,ht=i?.paidAiSharePctBySessionDisplay??"0%",Ze=i?new Set(i.aiReferrals.map(J=>J.source.toLowerCase())).size:0,Ae=De[0]??null,at=i?.totalDirectSessions??0,kt=i?.directSharePctDisplay??"0%",Mt=i?.channelBreakdown?.direct.sessions??at,Ee=i?.channelBreakdown?.direct.sharePctDisplay??kt,C=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Ce=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",ve=i?.socialSessions??0,Ye=i?.socialSharePctDisplay??"0%",yt=i?.channelBreakdown?.social.sessions??ve,tt=i?.channelBreakdown?.social.sharePctDisplay??Ye,Lt=i?new Set(i.socialReferrals.map(J=>J.source.toLowerCase())).size:0,Qe=Be[0]??null;return e.jsxs(e.Fragment,{children:[x&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:x}),f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:f}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!ae()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:h,onClick:He(Ne),children:[e.jsx(Zn,{className:`w-3.5 h-3.5 mr-1.5 ${h?"animate-spin":""}`}),h?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:b,onClick:He(Y),children:[e.jsx(Nm,{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(_e,{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(dr,{value:ja(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(dr,{value:ja(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Ge} of total`,tone:"positive"}),e.jsx(dr,{value:i.totalUsers===null?"—":ja(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!ae()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:h,onClick:He(Ne),children:[e.jsx(Zn,{className:`w-3.5 h-3.5 mr-1.5 ${h?"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(_e,{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."})]})]}),Ie&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Ie.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Ie.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),U.length>0&&e.jsxs(fe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:H.length>0?"AI vs. total sessions":"All sessions (baseline)"}),H.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),H.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:U,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Tt,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn}),e.jsx(tn,{tick:Tt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...es,labelFormatter:Bt,formatter:(J,qe)=>{const Pe=typeof J=="number"?J.toLocaleString():String(J??0),Re=String(qe??"");return Re==="_totalSessions"?[Pe,"Total Sessions"]:Re==="_organicSessions"?[Pe,"Organic Sessions"]:[Pe,Re]}}),e.jsx(_a,{wrapperStyle:{fontSize:11,color:us.text},formatter:J=>J==="_totalSessions"?"Total Sessions":J==="_organicSessions"?"Organic Sessions":J}),e.jsx(Bs,{type:"monotone",dataKey:"_totalSessions",stroke:us.textFaint,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),H.map((J,qe)=>e.jsx(Bs,{type:"monotone",dataKey:J,stackId:"ai",stroke:Us[qe%Us.length],fill:Us[qe%Us.length],fillOpacity:.4,strokeWidth:1.5},J))]})})})]}),e.jsxs(fe,{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(fs,{label:"Organic",value:se,hint:`${Xe.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(fs,{label:"Social",value:tt,hint:`${yt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(fs,{label:"Direct",value:Ee,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(fs,{label:"Visitors from AI (at least)",value:Ve,hint:Fe>0?`${mt.toLocaleString()} sessions · ${Fe.toLocaleString()} paid`:`${mt.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(fs,{label:"Other channels",value:Ce,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."})]}),Ae&&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:Ae.source})," via ",Ae.medium,", accounting for ",Ae.sessions.toLocaleString()," sessions.",Fe>0&&e.jsxs("span",{children:[" Paid AI: ",Fe.toLocaleString()," sessions (",ht,")."]})]})]}),e.jsxs(fe,{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?`${Ze} 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:E,onSort:ne,align:"left"}),e.jsx(rs,{label:"Medium",sortKey:"medium",current:j,dir:E,onSort:ne,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:E,onSort:ne,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:De.map(J=>e.jsx(Hh,{referral:J,totalSessions:ut},`${J.source}:${J.medium}:${J.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(fe,{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:Je})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Qs,{value:Se.query,onChange:Se.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Se.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(rs,{label:"Landing Page",sortKey:"landingPage",current:G,dir:ee,onSort:Ue,align:"left"}),e.jsx(rs,{label:"Source",sortKey:"source",current:G,dir:ee,onSort:Ue,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:G,dir:ee,onSort:Ue,align:"right"})]})}),e.jsx("tbody",{children:Se.rows.map(J=>e.jsx(Wh,{row:J},`${J.landingPage}:${J.source}:${J.medium}:${J.sourceDimension}`))})]})}),e.jsx(qs,{page:Se.page,pageSize:Se.pageSize,visibleRows:Se.rows.length,totalRows:Se.totalRows,onPageChange:Se.setPage,itemLabel:Se.hasQuery?"matches":"rows"})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No landing pages match this filter"}),e.jsx("button",{type:"button",onClick:()=>Se.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(_e,{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(fe,{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(fs,{label:"Social Sessions",value:ja(ve),hint:`${ve.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(fs,{label:"Share of Traffic",value:Ye,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(fs,{label:"Platforms",value:String(Lt),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),Qe&&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:`${Qe.source} via ${Qe.medium}`,children:Cl(In(Qe.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Qe.medium,children:["via ",In(Qe.medium)," · ",Qe.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(fs,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(fs,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(fs,{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."})]})]})]}),ze.length>0&&e.jsxs(fe,{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"})]}),_>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Oe.length-1," sources · ",_," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:ze,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Tt,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn}),e.jsx(tn,{tick:Tt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...es,labelFormatter:Bt,formatter:(J,qe)=>{const Pe=typeof J=="number"?J.toLocaleString():String(J??0),Re=String(qe??"");if(Re===Rn)return[Pe,"Total Social"];if(Re===Tn){const Ht=`Other (${_} source${_===1?"":"s"})`;return[Pe,Ht]}return[Pe,In(Re)]}}),e.jsx(Bs,{type:"monotone",dataKey:Rn,stroke:kl,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Oe.map((J,qe)=>{const Re=J===Tn?_r:Us[qe%Us.length];return e.jsx(Bs,{type:"monotone",dataKey:J,stackId:"social",stroke:Re,fill:Re,fillOpacity:.4,strokeWidth:1.5},J)})]})})}),e.jsx(Jh,{sources:Oe,otherCount:_})]}),e.jsxs(fe,{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?Be.length>Kn&&!le?`Top ${Kn} of ${Be.length}`:`${Be.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:F,dir:B,onSort:Z,align:"left"}),e.jsx(rs,{label:"Medium",sortKey:"medium",current:F,dir:B,onSort:Z,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:F,dir:B,onSort:Z,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(le?Be:Be.slice(0,Kn)).map(J=>e.jsx(Yh,{referral:J,totalSessions:ve},`${J.source}:${J.medium}:${J.channelGroup}`))})]})}),Be.length>Kn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>pe(J=>!J),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:le?`Show top ${Kn}`:`Show all ${Be.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(_e,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx(Qs,{value:ce.query,onChange:ce.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:R,onSort:z,align:"left"}),e.jsx(rs,{label:"Sessions",sortKey:"sessions",current:S,dir:R,onSort:z,align:"right"}),e.jsx(rs,{label:"Organic",sortKey:"organicSessions",current:S,dir:R,onSort:z,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:ce.rows.map(J=>e.jsx(Qh,{page:J},J.landingPage))})]})}),ce.totalRows===0&&ce.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(qs,{page:ce.page,pageSize:ce.pageSize,visibleRows:ce.rows.length,totalRows:ce.totalRows,onPageChange:ce.setPage,itemLabel:ce.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 ${Al(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,c]=l.useState(null),[d,u]=l.useState(!1),[h,m]=l.useState(null),b=l.useRef(null),p=l.useCallback(g=>{const f=g.target.files?.[0];if(!f)return;m(null),o(f.name);const N=new FileReader;N.onload=()=>{const S=N.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)."),c(null);return}c(S)}catch{m("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},N.onerror=()=>{m("Failed to read file."),c(null)},N.readAsText(f)},[]);async function x(){if(m(null),!n.trim()){m("Property ID is required.");return}if(!i){m("Please upload a service account key file.");return}u(!0);try{await yc(t,{propertyId:n.trim(),keyJson:i});try{await Yo(t)}catch{}s()}catch(g){m(g instanceof Error?g.message:"Failed to connect GA4")}finally{u(!1)}}return e.jsxs(fe,{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."}),h&&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:h}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:g=>a(g.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:b,type:"file",accept:".json,application/json",onChange:p,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>b.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(wm,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(P,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:He(x),children:d?"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 Pl={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function dr({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 ${Pl[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function fs({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(_e,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Pl[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Qh({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 Rl={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Il={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 Hh({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Rl[t.sourceDimension]??t.sourceDimension,r=Il[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 Wh({row:t}){const s=Rl[t.sourceDimension]??t.sourceDimension,n=Il[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(La,{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 Yh({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 Jh({sources:t,otherCount:s}){const n=[{key:Rn,color:kl,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Tn)n.push({key:Tn,color:_r,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=In(r);n.push({key:r,color:Us[a%Us.length]??_r,label:Cl(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 Xh(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 Zh=["7d","30d","90d","all"],Na=500,zi=[{key:"clicks",label:"Clicks",color:nt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:nt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Es.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:nt[2],inverted:!0,format:t=>t.toFixed(1)}],Ks=25,ex="canonry:google-oauth-complete",tx=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function sx(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const d=t.prior[s],u=t.trailing[s];return d!==null&&u!==null&&d<=0&&u>0?`new in the last ${a}d`:d===null||d<=0?`no prior ${a}d to compare`:u===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%":`${tx.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function nx(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,o=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,c=`${r.startDate} to ${r.endDate}`,d=`Tile percentages compare these ${s} ${o} (${c}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?d:`${d} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function Qi(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Hi(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 Wi(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function ax({projectName:t,refreshNonce:s}){const n=ms(),[a,r]=l.useState(!1),[o,i]=l.useState([]),[c,d]=l.useState([]),[u,h]=l.useState([]),[m,b]=l.useState(null),[p,x]=l.useState([]),[g,f]=l.useState([]),[N,S]=l.useState(null),[q,R]=l.useState(""),[y,j]=l.useState(""),[A,E]=l.useState("30"),[D,F]=l.useState(!1),[V,B]=l.useState("30d"),[w,G]=l.useState(["clicks","impressions"]),[L,ee]=l.useState(!0),[O,X]=l.useState(null),[oe,k]=l.useState(0),[I,$]=l.useState({startDate:"",endDate:"",query:"",page:""}),[te,le]=l.useState(0),[pe,ie]=l.useState(!1),[Ne,Y]=l.useState(0),[z,ne]=l.useState(!1),[Z,be]=l.useState(""),[ce,De]=l.useState(!0),[we,Se]=l.useState(!1),[Je,Ue]=l.useState(!1),[Be,ze]=l.useState(!1),[Oe,_]=l.useState(!1),[U,H]=l.useState(!1),[Ie,Ge]=l.useState(!1),[se,Xe]=l.useState(null),[ut,mt]=l.useState(!1),[Ve,Fe]=l.useState(!1),[ht,Ze]=l.useState(null),[Ae,at]=l.useState(null),[kt,Mt]=l.useState([]),[Ee,C]=l.useState(new Set),[Ce,ve]=l.useState({}),[Ye,yt]=l.useState(new Set),[tt,Lt]=l.useState(""),[Qe,J]=l.useState(null),[qe,Pe]=l.useState(""),[Re,Ht]=l.useState(!1),[jt,Rt]=l.useState(!1),[qt,xt]=l.useState(!1),[Et,ts]=l.useState(!1),[rt,Vt]=l.useState("indexed"),[Nt,ss]=l.useState(null),it=!!(I.query.trim()||I.page.trim()||Nt),Dt=Nt!==null,Wt=l.useMemo(()=>{if(!Nt)return u;const{key:v,dir:Q}=Nt;return[...u].sort((he,ye)=>{const et=v===hn.CTR?Number.isFinite(he.ctr)?he.ctr:0:he[v],st=v===hn.CTR?Number.isFinite(ye.ctr)?ye.ctr:0:ye[v];return Q==="asc"?et-st:st-et})},[u,Nt]),It=fn({rows:Wt,pageSize:Rs}),hs=z?It.rows:Wt,Yt=fn({rows:(ht??[]).filter(v=>v.path.toLowerCase().includes(tt.trim().toLowerCase())),pageSize:Rs}),[wt,As]=l.useState([]),[gt,Ot]=l.useState(null),[ys,xs]=l.useState(1),zt=l.useMemo(()=>{if(wt.length<2)return null;const v=wt[wt.length-1],Q=wt[wt.length-2];return{indexed:v.indexed-Q.indexed,notIndexed:v.notIndexed-Q.notIndexed}},[wt]);l.useEffect(()=>{xs(1)},[se,rt,gt]);const K=l.useMemo(()=>gt?(se?.reasonGroups??[]).find(v=>v.reason===gt):void 0,[se,gt]),re=l.useMemo(()=>se?rt==="indexed"?se.indexed:rt==="deindexed"?se.deindexed:rt==="notIndexed"?gt?K?.urls??[]:(se.reasonGroups??[]).length===0?se.notIndexed:[]:[]:[],[se,rt,gt,K]),je=Math.max(1,Math.ceil(re.length/Ks)),ue=Math.min(Math.max(1,ys),je),me=(ue-1)*Ks,Ke=l.useMemo(()=>se?.indexed.slice(me,me+Ks)??[],[se,me]),ns=l.useMemo(()=>se?.notIndexed.slice(me,me+Ks)??[],[se,me]),ot=l.useMemo(()=>se?.deindexed.slice(me,me+Ks)??[],[se,me]),bs=l.useMemo(()=>(K?.urls??[]).slice(me,me+Ks),[K,me]),[T,xe]=l.useState(!1),[dt,Me]=l.useState(null),[bt,vs]=l.useState(null),[Ft,Jt]=l.useState(null);function bn(v,Q){const he=Gm(v),ye=Xh(he);ye?(vs(ye),Me(null)):(vs(null),Me(he.message||Q))}const St=o.find(v=>v.connectionType==="gsc"),ps=(St?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),vn=kt.length>0?kt:(ht??[]).map(v=>v.path),Ya=vn.filter(v=>ht?.some(Q=>Q.path===v&&Q.isSitemapsIndex)).length,qn=Ya===1?"Resubmit sitemap index":Ya>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",ia=u.length>0||p.length>0||g.length>0,En=bc(),Os=vc();async function oa(v,Q=!1){if(!v){d([]),R("");return}Ue(!0);try{const{sites:he}=await n.fetchQuery({...Lc({client:W,path:{name:t}}),staleTime:Q?0:_t});d(he),R(v.propertyId??he[0]?.siteUrl??""),vs(null)}catch(he){d([]),bn(he,"Failed to load Search Console properties")}finally{Ue(!1)}}async function nn(v){_(!0);const Q=v??te;try{const he=it?Na:Rs,ye=it?0:Q,et={limit:String(he)};I.startDate&&(et.startDate=I.startDate),I.endDate&&(et.endDate=I.endDate),I.query&&(et.query=I.query),I.page&&(et.page=I.page),ye>0&&(et.offset=String(ye)),V&&V!=="all"&&!I.startDate&&(et.window=V);const st=await n.fetchQuery({...wc({client:W,path:{name:t},query:et}),staleTime:_t}),lt=st.rows;it?(ie(!1),h(lt),Y(lt.length),ne(!0)):(ie(ye+lt.length<st.totalMatching),h(lt),Y(0),ne(!1))}catch(he){h([]),ie(!1),Y(0),Me(he instanceof Error?he.message:"Failed to load GSC performance data")}finally{_(!1)}}async function Dn(){try{const v={};I.startDate&&(v.startDate=I.startDate),I.endDate&&(v.endDate=I.endDate),V&&V!=="all"&&!I.startDate&&(v.window=V);const Q=await n.fetchQuery({...Nc({client:W,path:{name:t},query:v}),staleTime:_t});b(Q)}catch{b(null)}}async function jn(v=!1){H(!0);try{const Q=Z.trim()||void 0,he={limit:"20"};Q&&(he.url=Q);const[ye,et]=await Promise.all([n.fetchQuery({...Tc({client:W,path:{name:t},query:he}),staleTime:v?0:_t}),n.fetchQuery({...Mc({client:W,path:{name:t}}),staleTime:v?0:_t})]);x(ye),f(et)}catch(Q){x([]),f([]),Me(Q instanceof Error?Q.message:"Failed to load GSC inspection history")}finally{H(!1)}}async function la(v=!1){mt(!0);try{const[Q,he]=await Promise.all([n.fetchQuery({...kc({client:W,path:{name:t}}),staleTime:v?0:_t}),n.fetchQuery({...Ac({client:W,path:{name:t}}),staleTime:v?0:_t}).catch(()=>[])]);Xe(Q),As(he)}catch(Q){Xe(null),As([]),Me(Q instanceof Error?Q.message:"Failed to load coverage data")}finally{mt(!1)}}async function ca(v){xe(!0),Me(null);try{const Q=await ji(t,{urls:v}),{succeeded:he,failed:ye,total:et}=Q.summary;Te({title:"Indexing requested",detail:ye===0?`${he} URL${he!==1?"s":""} submitted for indexing.`:`${he}/${et} submitted successfully, ${ye} failed.`,tone:ye===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(Q){Me(Q instanceof Error?Q.message:"Failed to request indexing")}finally{xe(!1)}}async function da(){xe(!0),Me(null);try{const v=await ji(t,{urls:[],allUnindexed:!0}),{succeeded:Q,failed:he,total:ye}=v.summary;Te({title:"Indexing requested",detail:he===0?`${Q} unindexed URL${Q!==1?"s":""} submitted for indexing.`:`${Q}/${ye} submitted successfully, ${he} failed.`,tone:he===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(v){Me(v instanceof Error?v.message:"Failed to request indexing")}finally{xe(!1)}}async function On(){Fe(!0),Me(null);try{const v=await Ja(t);n.setQueryData(Pc({client:W,path:{name:t}}),v),Ze(v.sitemaps),at(v.summary),Mt(v.preferredSubmissionUrls),C(new Set),ve({}),v.sitemaps.length===0&&Jt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(v){Me(v instanceof Error?v.message:"Failed to list sitemaps")}finally{Fe(!1)}}async function ua(v){const Q=Ee.has(v);if(C(he=>{const ye=new Set(he);return Q?ye.delete(v):ye.add(v),ye}),!(Q||Ce[v])){yt(he=>new Set(he).add(v));try{const he=await Ja(t,v);ve(ye=>({...ye,[v]:he.sitemaps}))}catch(he){Me(he instanceof Error?he.message:"Failed to load sitemap files")}finally{yt(he=>{const ye=new Set(he);return ye.delete(v),ye})}}}async function Ps(v){if(!ps||v.length===0)return;const Q=[...new Set(v)];Rt(!0),Me(null),J({completed:0,total:Q.length});let he=0,ye=0,et=0,st=null;try{for(let At=0;At<Q.length;At+=50){const ct=Q.slice(At,At+50);try{const ke=await Rc(t,ct);he+=ke.summary.accepted,ye+=ke.summary.failed,et+=ct.length,J({completed:et,total:Q.length})}catch(ke){et+=ct.length;const Fs=ct.length,Gn=Q.length-et,fa=ke instanceof Error?ke.message:"The batch request failed",Gs=`${he} accepted, ${ye} failed, ${Fs} unconfirmed, ${Gn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;st=`Sitemap submission stopped after a batch request failed. ${Gs} ${fa}`,Me(st),Te({title:"Sitemap resubmission partially completed",detail:Gs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const lt=Q.length;Te({title:ye===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ye===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${he}/${lt} sitemap submissions; ${ye} failed. Indexing is not guaranteed.`,tone:ye===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Pe("")}catch(lt){Me(lt instanceof Error?lt.message:"Failed to submit sitemap to Google")}finally{Rt(!1),J(null),await On(),st&&Me(st)}}async function Xt(){Rt(!0);const v=ht??[];try{const Q=v.filter(ye=>ye.isSitemapsIndex),he=[];for(let ye=0;ye<Q.length;ye+=4)(await Promise.all(Q.slice(ye,ye+4).map(async st=>{const lt=Ce[st.path];if(lt)return lt;const At=await Ja(t,st.path);return ve(ct=>({...ct,[st.path]:At.sitemaps})),At.sitemaps}))).forEach((st,lt)=>{he.push(...st.length>0?st.map(At=>At.path):[Q[ye+lt].path])});await Ps([...v.filter(ye=>!ye.isSitemapsIndex).map(ye=>ye.path),...he])}catch(Q){Me(Q instanceof Error?Q.message:"Failed to load sitemap files"),Rt(!1)}}async function ma(v){Ht(!0),Me(null);try{await Ic(t,"gsc",v),await Ct(n,"google"),i(Q=>Q.map(he=>he.connectionType==="gsc"?{...he,sitemapUrl:v}:he)),Te({title:"Default sitemap updated",detail:v,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(Q){Me(Q instanceof Error?Q.message:"Failed to set the default sitemap")}finally{Ht(!1)}}async function ha(v){try{await Os.mutateAsync({projectName:t,projectLabel:t,opts:v?{sitemapUrl:v}:void 0})}catch{}}async function xa(){De(!0),Me(null);try{const[v,Q]=await Promise.all([Jo().catch(()=>null),n.fetchQuery({...ti({client:W,path:{name:t}}),staleTime:_t}).catch(()=>[])]);r(!!v?.google?.configured),i(Q);const he=Q.find(ye=>ye.connectionType==="gsc");await Promise.all([oa(he),nn(),Dn(),jn(),la(),he?.propertyId?On():Promise.resolve()])}finally{De(!1)}}l.useEffect(()=>{xa()},[t,s]),l.useEffect(()=>{le(0),X(null),$(v=>v.startDate||v.endDate?{...v,startDate:"",endDate:""}:v),k(v=>v+1),Dn()},[V]);const pa=l.useRef(!1);l.useEffect(()=>{if(!pa.current){pa.current=!0;return}le(0),It.setPage(1),nn(0)},[oe]);function Fn(v){const Q=O===v?null:v;X(Q),$(he=>({...he,startDate:Q??"",endDate:Q??""})),k(he=>he+1)}const ga=l.useRef(!1);l.useEffect(()=>{if(!ga.current){ga.current=!0;return}le(0),nn(0)},[Dt]);async function M(){if(!a){Me("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Se(!0),Me(null),Jt(null);try{let v=function(ke){if(ke.source!==ye||ke.origin!==et||!ke.data||typeof ke.data!="object")return;const Fs=ke.data;Fs.type!==ex||Fs.connectionType!=="gsc"||ct(!0)};const{authUrl:Q,redirectUri:he}=await Cc(t,"gsc");if(!Q.startsWith("https://accounts.google.com/")){Me("Unexpected OAuth redirect URL. Please try again.");return}const ye=window.open(Q,"_blank","width=600,height=700");if(!ye){window.location.assign(Q);return}const et=he?new URL(he).origin:window.location.origin;let st=!1,lt=null;const At=()=>{lt!==null&&window.clearInterval(lt),window.removeEventListener("message",v)},ct=async ke=>{if(!st){st=!0,At(),Jt(ke?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Ct(n,"google"),await xa()}finally{Jt(null)}}};window.addEventListener("message",v),Jt("Finish the Google consent flow in the popup. This page will refresh automatically."),lt=window.setInterval(()=>{ye.closed&&ct(!1)},1e3)}catch(v){Me(v instanceof Error?v.message:"Failed to start OAuth flow")}finally{Se(!1)}}async function ge(){Me(null),Jt(null);try{await Sc(t,"gsc"),await Ct(n,"google"),i(v=>v.filter(Q=>Q.connectionType!=="gsc")),d([]),R("")}catch(v){Me(v instanceof Error?v.message:"Failed to disconnect")}}async function Le(){if(q){ze(!0),Me(null);try{await qc(t,"gsc",q),await Ct(n,"google"),i(v=>v.map(Q=>Q.connectionType==="gsc"?{...Q,propertyId:q}:Q)),Te({title:"GSC property updated",detail:`${t} is now linked to ${q}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(v){Me(v instanceof Error?v.message:"Failed to save GSC property")}finally{ze(!1)}}}async function Zt(){Me(null),Jt(null);try{await En.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(A,10)||void 0,full:D||void 0}}),await Ct(n,"gsc")}catch{}}async function gs(){if(y.trim()){Ge(!0),Me(null),Jt(null);try{const v=await $c(t,y.trim());await Ct(n,"gsc"),S(v),j(""),await jn()}catch(v){Me(v instanceof Error?v.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"})]})}),bt&&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:bt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:bt.message}),(Ts(bt.enableUrl)||Ts(bt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ts(bt.enableUrl)&&e.jsx("a",{href:Ts(bt.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),Ts(bt.indexingApiUrl)&&e.jsx("a",{href:Ts(bt.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>vs(null),children:"×"})]})}),dt&&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:[dt,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Me(null),children:"×"})]}),Ft&&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:[Ft,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Jt(null),children:"×"})]}),ce?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[St?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:St.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",se?.lastInspectedAt?Qt(se.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:He(ge),children:"Disconnect"})]}):e.jsxs(fe,{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(de,{tone:a?"caution":"negative",children:a?"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:a?"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:[a?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:we,onClick:He(M),children:we?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(ks,{to:"/settings",children:"Open Settings"})}),!a&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),(St||ia)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(fe,{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(_e,{text:`${nx(m?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${Na.toLocaleString()} matching rows while the table shows ${Rs} per page.`})]}),m?.window?.startDate&&m.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[m.window.startDate," to ",m.window.endDate,(m.window.daysSinceLatestData??0)>0&&` · latest data ${m.window.daysSinceLatestData} day${m.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{windows:Zh,value:V,onChange:v=>{B(v),le(0),It.setPage(1)},label:"Search Console time period",formatOption:v=>v==="all"?"All":v}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Oe,onClick:()=>{le(0),It.setPage(1),nn(0),Dn()},children:Oe?"Loading…":"Apply filters"})]})]}),m&&m.daily.length>0&&(()=>{const{totals:v,daily:Q,trends:he,periodComparison:ye}=m,st=zi.filter(ke=>w.includes(ke.key)).map(ke=>({dataKey:ke.key,label:ke.label,color:ke.color,axisId:ke.key,inverted:ke.inverted,formatValue:ke.format,trend:L?he?.[ke.key]??null:null})),lt=ke=>v[ke]??null,At=new Map(Q.map(ke=>[ke.date,ke])),ct=Q.length===0?[]:zm(Q[0].date,Q[Q.length-1].date).map(ke=>At.get(ke)??{date:ke});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:zi.map(ke=>{const Fs=w.includes(ke.key),Gn=lt(ke.key),fa=Gn===null;return e.jsxs("button",{type:"button","aria-pressed":Fs,disabled:fa,className:`rounded-md border px-3 py-2 text-left transition-colors ${Fs?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${fa?"cursor-not-allowed opacity-50":""}`,onClick:()=>{G(Gs=>Gs.includes(ke.key)?Gs.length===1?Gs:Gs.filter(nc=>nc!==ke.key):[...Gs,ke.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:Fs?ke.color:"transparent",border:`1px solid ${ke.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ke.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Gn===null?"—":ke.format(Gn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:sx(ye,ke.key,ke.inverted)})]},ke.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:L,onChange:ke=>ee(ke.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(xl,{data:ct,xKey:"date",series:st,xTickFormatter:yn,labelFormatter:Bt,onSelectX:Fn,selectedX:O})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:Q.map(ke=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":O===ke.date,onClick:()=>Fn(ke.date),children:[Bt(ke.date),": ",ke.clicks," clicks, ",ke.impressions," impressions"]},ke.date))}),O&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Bt(O)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Fn(O),children:["Show all ",v.days," days"]})]}),v.position!==null&&(v.positionDays??v.days)<v.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",v.positionDays," of ",v.days," days. The rest have no property-level position recorded."]}),(v.position===null||v.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:I.startDate,onChange:v=>$(Q=>({...Q,startDate:v.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:I.endDate,onChange:v=>$(Q=>({...Q,endDate:v.target.value}))}),e.jsx(Qs,{value:I.query,onChange:v=>$(Q=>({...Q,query:v})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Qs,{value:I.page,onChange:v=>$(Q=>({...Q,page:v})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),u.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(hn).map(v=>e.jsx("th",{className:"text-right","aria-sort":Nt?.key===v?Nt.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:()=>{It.setPage(1),ss(Q=>Q?.key===v?Q.dir==="desc"?{key:v,dir:"asc"}:null:{key:v,dir:"desc"})},children:[jc[v],Nt?.key===v?Nt.dir==="desc"?" ↓":" ↑":""]})},v))]})}),e.jsx("tbody",{children:hs.map((v,Q)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:v.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:v.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(La,{value:v.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:v.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(v.ctr)?v.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.position.toFixed(1)})]},`${v.date}:${v.query}:${v.page}:${Q}`))})]})}),e.jsx(qs,{page:z?It.page:Math.floor(te/Rs)+1,pageSize:Rs,visibleRows:hs.length,totalRows:z?Ne:void 0,hasNextPage:z?void 0:pe,disabled:Oe,itemLabel:z?"matches":"rows",onPageChange:v=>{if(z){It.setPage(v);return}const Q=(v-1)*Rs;le(Q),nn(Q)}}),z&&Ne>=Na?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Na.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(fe,{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(_e,{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:[se&&se.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:T,onClick:()=>{da()},children:T?"Requesting…":`Request indexing (${se.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ut,onClick:()=>{la(!0)},children:ut?"Loading…":"Reload saved coverage"})]})]}),se&&se.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const v=se.summary.indexed+se.summary.notIndexed,Q=v>0?se.summary.indexed/v:0,he=v>0?se.summary.notIndexed/v:0,ye=54,et=2*Math.PI*ye,st=et*(1-Q),lt=et*he,At=et*Q;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:ye,fill:"none",stroke:us.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ye,fill:"none",stroke:Es.positiveDeep,strokeWidth:"14",strokeDasharray:et,strokeDashoffset:st,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),se.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ye,fill:"none",stroke:us.textFaint,strokeWidth:"14",strokeDasharray:`${lt} ${et-lt}`,strokeDashoffset:-At,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-3xl font-bold tabular-nums text-primary",children:[(Q*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:se.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:se.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(se.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(se.reasonGroups??[]).length," ",(se.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),se.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:se.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(v=>{const Q=v==="indexed"?se.indexed.length:v==="notIndexed"?se.notIndexed.length:se.deindexed.length,he=v==="indexed"?"Indexed":v==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":rt===v,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${rt===v?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{Vt(v),Ot(null)},children:[he," (",Q,")"]},v)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[rt==="indexed"&&se.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:Ke.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.crawlTime?v.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:v.isMobileFriendly===!0?"Yes":v.isMobileFriendly===!1?"No":"—"})]},v.id))})]}),rt==="notIndexed"&&!gt&&(se.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:(se.reasonGroups??[]).map(v=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>Ot(v.reason),onKeyDown:Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),Ot(v.reason))},tabIndex:0,role:"button","aria-label":`View ${v.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:v.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.count})]},v.reason))})]}),rt==="notIndexed"&&!gt&&(se.reasonGroups??[]).length===0&&se.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:ns.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.coverageState??"Unknown"})]},v.id))})]}),rt==="notIndexed"&&gt&&(()=>{const v=(se.reasonGroups??[]).find(Q=>Q.reason===gt);return v?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>Ot(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:v.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[v.count," affected page",v.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:T,onClick:()=>{ca(v.urls.map(Q=>Q.url))},children:T?"Requesting…":`Request indexing (${v.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:bs.map(Q=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:Q.url}),e.jsx("td",{className:"text-secondary",children:Q.crawlTime?Q.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:T,onClick:()=>{ca([Q.url])},title:"Request indexing",children:"Index"})})]},Q.id))})]})]}):null})(),rt==="deindexed"&&se.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:ot.map((v,Q)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.previousState}),e.jsx("td",{className:"text-secondary",children:v.currentState}),e.jsx("td",{className:"text-secondary",children:v.transitionDate.split("T")[0]})]},`${v.url}-${Q}`))})]}),(rt==="indexed"&&se.indexed.length===0||rt==="notIndexed"&&!gt&&se.notIndexed.length===0||rt==="deindexed"&&se.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(qs,{page:ue,pageSize:Ks,visibleRows:Math.min(Ks,re.length-me),totalRows:re.length,onPageChange:xs,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":Et,onClick:()=>ts(v=>!v),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Et?"Hide snapshots":wt.length>0?`View ${wt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",se.summary.indexed.toLocaleString()," indexed, ",se.summary.notIndexed.toLocaleString()," not indexed.",zt&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",zt.indexed>=0?"+":"",zt.indexed.toLocaleString()," indexed, ",zt.notIndexed>=0?"+":"",zt.notIndexed.toLocaleString()," not indexed."]})]}),Et&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:wt.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:wt.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:v.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:v.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.notIndexed.toLocaleString()})]},v.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:ut?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(fe,{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(_e,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Ve||!St?.propertyId,onClick:()=>{On()},children:Ve?"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:qe,onChange:v=>Pe(v.target.value),onKeyDown:v=>v.key==="Enter"&&void Ps([qe.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!ps||jt||!qe.trim(),onClick:()=>{Ps([qe.trim()])},children:jt?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!ps||jt||vn.length===0,onClick:()=>{Ps(vn)},children:jt?"Resubmitting…":qn}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!ps||jt||!ht?.length,onClick:()=>{Xt()},children:"Resubmit all files"}),Ae&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ae.indexes," index",Ae.indexes===1?"":"es",", ",Ae.files," file",Ae.files===1?"":"s"]}),Qe&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Qe.completed,"/",Qe.total]})]}),!ps&&St&&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(M),children:"Reconnect"})]}),ht&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:ht.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Qs,{value:tt,onChange:v=>{Lt(v),Yt.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:Yt.rows.flatMap(v=>{const Q=Qi(v),he=Hi(v),ye=Wi(v),et=Ce[v.path]??[],st=Ee.has(v.path),lt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(La,{value:v.path})}),e.jsx("td",{className:"text-secondary",children:v.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":st,"aria-label":`${st?"Collapse":"Expand"} files in ${v.path}`,onClick:()=>{ua(v.path)},children:Ye.has(v.path)?"Loading…":`${st?"▾":"▸"} Index${Ce[v.path]?` (${et.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ye}),e.jsx("td",{className:"text-secondary",children:v.lastSubmitted?v.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:v.lastDownloaded?v.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Q.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:he||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!ps||jt,onClick:()=>{Ps([v.path])},children:v.lastSubmitted?"Resubmit to Google":"Submit to Google"}),St?.sitemapUrl===v.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Re,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ma(v.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Os.isPending,onClick:()=>{ha(v.path)},children:"Inspect URLs"})]})})]},v.path),At=v.isSitemapsIndex&&st?et.map(ct=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(La,{value:ct.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Wi(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:Qi(ct).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Hi(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:!ps||jt,onClick:()=>{Ps([ct.path])},children:"Resubmit"}),St?.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:Re,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:Os.isPending,onClick:()=>{ha(ct.path)},children:"Inspect URLs"})]})})]},`${v.path}:${ct.path}`)):[];return[lt,...At]})})]}),e.jsx(qs,{page:Yt.page,pageSize:Rs,visibleRows:Yt.rows.length,totalRows:Yt.totalRows,onPageChange:Yt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(fe,{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:y,onChange:v=>j(v.target.value),onKeyDown:v=>v.key==="Enter"&&void gs()}),e.jsx(P,{type:"button",size:"sm",disabled:Ie||!St?.propertyId||!y.trim(),onClick:He(gs),children:Ie?"Inspecting…":"Inspect URL"})]}),N&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:N.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:N.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:vi(N.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Qt(N.crawlTime)})]})]})]}),e.jsxs(fe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:U,onClick:()=>{jn(!0)},children:U?"Loading…":"Refresh history"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:Z,onChange:v=>be(v.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:U,onClick:()=>{jn(!0)},children:"Apply filter"})]}),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:"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:p.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-neutral",children:v.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:vi(v.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Qt(v.inspectedAt)})]},v.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(fe,{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"})]})}),g.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:g.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:v.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Qt(v.transitionDate)})]},`${v.url}:${v.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),St&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>xt(v=>!v),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${qt?"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"})]})}),qt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(fe,{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(_e,{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:q,disabled:Je||c.length===0,onChange:v=>R(v.target.value),children:c.length===0?e.jsx("option",{value:"",children:Je?"Loading properties…":"No properties available"}):c.map(v=>e.jsxs("option",{value:v.siteUrl,children:[v.siteUrl," · ",v.permissionLevel]},v.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Je,onClick:()=>{oa(St,!0)},children:Je?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!q||Be,onClick:He(Le),children:Be?"Saving…":"Save property"})]})]})]}),e.jsxs(fe,{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:A,onChange:v=>E(v.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:D,onChange:v=>F(v.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:En.isPending||!St.propertyId,onClick:He(Zt),children:En.isPending?"Queueing…":"Queue sync"}),!St.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const rx=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function ix({projectName:t,projectId:s}){const n=ms(),[a,r]=l.useState(null),[o,i]=l.useState(null),[c,d]=l.useState(!1),u=$e(ti({client:W,path:{name:t}})),h=u.data?.find(Y=>Y.connectionType==="gbp"),m=!!h,b=a?{locationName:a}:void 0,p=$e({...Ec({client:W,path:{name:t}}),enabled:m}),x=$e({...Dc({client:W,path:{name:t},query:b}),enabled:m}),g=$e({...Oc({client:W,path:{name:t},query:b}),enabled:m}),f=$e({...Fc({client:W,path:{name:t},query:b}),enabled:m}),N=$e({...Gc({client:W,path:{name:t},query:b}),enabled:m}),S=$e({...Kc({client:W,path:{name:t},query:b}),enabled:m}),q=$e({queryKey:["gbp-section-insights",t],queryFn:()=>_c(t),enabled:m});function R(){Ct(n,"gbp")}const y=Pt({...Uc(),onSuccess:Y=>{Xo({id:Y.runId,projectId:s,kind:Ys["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Te({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),j=l.useSyncExternalStore(Zo,Da,Da),A=Object.values(j.runs).some(Y=>Y.kind===Ys["gbp-sync"]&&Y.projectId===s),E=y.isPending||A,D=Pt({...Bc(),onSuccess:()=>R()});if(l.useEffect(()=>{if(!a||!p.data)return;const Y=p.data.locations.filter(z=>z.selected);(Y.length<=1||!Y.some(z=>z.locationName===a))&&r(null)},[a,p.data]),l.useEffect(()=>{if(!o||!p.data)return;(a?[a]:p.data.locations.filter(z=>z.selected).map(z=>z.locationName)).includes(o)||i(null)},[o,p.data,a]),u.isLoading)return null;if(!h){const Y=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(fe,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:Y.map((z,ne)=>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:ne+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:z.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:z.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:z.note})]})]},z.title))})]})})}const F=x.data,V=p.data?.locations??[],B=V.filter(Y=>Y.selected),w=g.data?.keywords??[],G=f.data?.lodging??[],L=N.data?.placeActions??[],ee=S.data?.places??[],O=V.length>0?V[0].accountName:h.domain,X=a?V.find(Y=>Y.locationName===a)?.displayName??null:null,oe=a?V.filter(Y=>Y.locationName===a):B,k=new Set(oe.map(Y=>Y.locationName)),I=G.filter(Y=>k.has(Y.locationName)),$=L.filter(Y=>k.has(Y.locationName)),te=ee.filter(Y=>k.has(Y.locationName)),le=new Set(B.map(Y=>Y.locationName)),pe=a?w:w.filter(Y=>le.has(Y.locationName)),ie=!a&&B.length>1,Ne=(q.data??[]).filter(Y=>!Y.dismissed&&rx.has(Y.type)&&(!X||Y.query===X||Y.query===a||Y.title.startsWith(X)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(fe,{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(_e,{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(de,{tone:"positive",children:"Connected"}),!ae()&&e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:E,onClick:()=>y.mutate({client:W,path:{name:t},body:{}}),children:E?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[O?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:O})," · "]}):null,p.data?`${p.data.totalSelected} of ${p.data.totalDiscovered} locations tracked`:"Loading locations…"]}),B.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:Y=>r(Y.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),B.map(Y=>e.jsx("option",{value:Y.locationName,children:Y.displayName},Y.id))]})]}),B.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:[Ne.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Ne.map(Y=>e.jsx("div",{className:["insight-card",bx(Y.severity),"rounded-r-lg border border-default bg-surface p-3 pl-4"].filter(Boolean).join(" "),children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-strong",children:[Y.title,Y.recommendation?.reason&&e.jsx(_e,{text:Y.recommendation.reason})]})},Y.id))]}),F&&e.jsx(wx,{performance:F.performance,freshness:F.freshness,timeseries:F.timeseries}),F?.profileCompleteness&&e.jsx(ox,{summary:F.profileCompleteness}),oe.length>0&&e.jsx(lx,{locations:oe,lodging:I,places:te,placeActions:$,expandedLocation:o,onToggleExpanded:Y=>{i(z=>z===Y?null:Y)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),g.data&&g.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[g.data.thresholdedPct,"% privacy-thresholded"]})]}),pe.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"}),ie&&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:pe.slice(0,25).map(Y=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:Y.keyword}),ie&&e.jsx("td",{className:"text-muted",children:V.find(z=>z.locationName===Y.locationName)?.displayName??Y.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:Y.valueCount!==null?Y.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",Y.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[Y.periodStart,"–",Y.periodEnd]})]},`${Y.locationName}:${Y.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>d(Y=>!Y),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",V.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:V.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!ae()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:V.map(Y=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:Y.displayName}),e.jsx("td",{className:"text-muted",children:Y.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(de,{tone:Y.selected?"positive":"neutral",children:Y.selected?"Tracked":"Not tracked"})}),!ae()&&e.jsx("td",{className:"text-right",children:e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:D.isPending,onClick:()=>D.mutate({client:W,path:{name:t,locationName:Y.locationName},body:{selected:!Y.selected}}),children:Y.selected?"Untrack":"Track"})})]},Y.id))})]})})]})]})})}function ox({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:_n(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:_n(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:_n(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:_n(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:_n(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(_e,{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 ${yx(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function lx({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:o}){const i=new Map(s.map(u=>[u.locationName,u])),c=new Map(n.map(u=>[u.locationName,u])),d=new Map;for(const u of a){const h=d.get(u.locationName)??[];h.push(u),d.set(u.locationName,h)}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(_e,{text:ae()?"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(u=>{const h=i.get(u.locationName)??null,m=c.get(u.locationName)??null,b=d.get(u.locationName)??[],p=r===u.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:u.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:u.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(de,{tone:u.selected?"positive":"neutral",children:u.selected?"Tracked":"Not tracked"}),u.openStatus&&u.openStatus!=="OPEN"&&e.jsx(de,{tone:u.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:$l(u.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(dx,{location:u})}),e.jsx("td",{children:e.jsx(ux,{lodging:h})}),e.jsx("td",{children:e.jsx(hx,{place:m,mapsUri:u.mapsUri})}),e.jsx("td",{children:e.jsx(px,{actions:b})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>o(u.locationName),children:p?"Hide":"Details"})})]}),p&&e.jsx("tr",{className:"bg-mono-950/35 hover:bg-mono-950/35",children:e.jsx("td",{colSpan:6,className:"px-4 py-4",children:e.jsx(fx,{location:u,lodging:h,place:m,placeActions:b})})})]},u.id)})})]})})]})}function cx(t){return[{label:"Description",tone:un(t.description)?"positive":"neutral",value:un(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:un(t.primaryPhone)?"positive":"neutral",value:un(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:un(t.websiteUri)?"positive":"neutral",value:un(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function dx({location:t}){const s=cx(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(de,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function ux({lodging:t}){return e.jsx(ai,{...mx(t)})}function mx(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 hx({place:t,mapsUri:s}){return e.jsx(ai,{...xx(t,s)})}function xx(t,s){if(!t)return{tone:"neutral",label:"Public listing not checked",detail:s?"Maps link available.":"No Places snapshot."};const n=t.amenities.length;return{tone:n>0?"positive":"neutral",label:n>0?`${n} signal${n===1?"":"s"} detected`:"0 supported signals detected",detail:`Places tier: ${t.tier}`}}function px({actions:t}){return e.jsx(ai,{...gx(t)})}function gx(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 ai({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(de,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function fx({location:t,lodging:s,place:n,placeActions:a}){const r=s?jx(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(ur,{title:"Owner profile · Business Information",children:[e.jsx(Gt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Gt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Gt,{label:"Description",value:un(t.description)?t.description:"Not returned"}),e.jsx(Gt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Gt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Gt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Gt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Gt,{label:"Open status",value:$l(t.openStatus)}),e.jsx(Gt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(ur,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{label:"Last checked",value:Yi(s.syncedAt)}),e.jsx(Gt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Gt,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(ur,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{label:"Places tier",value:n.tier}),e.jsx(Gt,{label:"Last checked",value:Yi(n.syncedAt)}),e.jsx(Gt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(o=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Ua(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Ua(o.providerType),o.uri?` · ${vx(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function ur({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Gt({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function _n(t,s,n){return t===s?"positive":t===0?n:"caution"}function yx(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function bx(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function un(t){return typeof t=="string"&&t.trim().length>0}function $l(t){return t?Ua(t):"Not returned"}function Ua(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function vx(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Yi(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function jx(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Nx(n)).map(([s])=>Ua(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Nx(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function wx({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Vc.filter(x=>(a[x]??0)>0),o=zc.filter(x=>(a[x]??0)>0),i=Object.keys(a).filter(x=>(a[x]??0)>0&&Qc(x)==="other").sort((x,g)=>(a[g]??0)-(a[x]??0)),c=Object.keys(a).filter(x=>(a[x]??0)===0).sort(),d=n.map(x=>{const g={date:x.date};for(const[f,N]of Object.entries(x.metrics))g[f]=N;return g}),u=n.find(x=>x.pending)?.date,h=n.length>0?n[n.length-1].date:void 0,m=d.length>0,b=s.dataThroughDate?`Data through ${Bt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,p=[...r,...i];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),b&&e.jsx("span",{className:"text-[11px] text-muted",children:b})]}),!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(Ji,{data:d,metrics:r,kind:"line",firstPending:u,lastDate:h}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:p.map(x=>e.jsxs("span",{className:"text-sm text-secondary",children:[Oa(x)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[x]??0).toLocaleString()})]},x))})]})]}),m&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Ji,{data:d,metrics:o,kind:"area",firstPending:u,lastDate:h})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(x=>Oa(x)).join(", ")]})]})}function Ji({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ta,{stroke:ea,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Tt,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn,minTickGap:24}),e.jsx(tn,{tick:Tt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...es,labelFormatter:Bt,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),Oa(String(i??""))]}),e.jsx(_a,{wrapperStyle:{fontSize:11,color:us.text},formatter:o=>Oa(o)}),a&&r&&e.jsx(Dr,{x1:a,x2:r,fill:us.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:us.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(Ls,{type:"monotone",dataKey:o,stroke:nt[i%nt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Bs,{type:"monotone",dataKey:o,stackId:"reach",stroke:nt[i%nt.length],fill:nt[i%nt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function Sx(t){return pl(Ds(String(t)))}function Cx(t){return Hs(Ds(String(t)))}function mr({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(Am,{className:"h-3.5 w-3.5","aria-hidden":!0})}),o&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const wa=Rs;function Nn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function hr(t){return t.toLocaleString()}function kx(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Ax(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 Px(t){const s=t.filter(n=>n.kind===Ys["backlink-extract"]&&!el(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Rx(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 Ix({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[o,i]=l.useState([]),[c,d]=l.useState(null),[u,h]=l.useState(null),[m,b]=l.useState(null),[p,x]=l.useState(Date.now()),[g,f]=l.useState(0),[N,S]=l.useState(!0),[q,R]=l.useState(!1),[y,j]=l.useState(null),A=l.useCallback(async()=>{S(!0),j(null);try{const[O,X,oe,k,I]=await Promise.all([Hc().catch(()=>null),Wc(t,{excludeCrawlers:!0}).catch(()=>null),Yc(t,{limit:wa,offset:g,excludeCrawlers:!0}).catch(te=>{if(te instanceof pn&&te.code==="NOT_FOUND")return null;throw te}),Jc(t).catch(()=>[]),Xc(t).catch(()=>[])]);d(O),n(X),r(oe),i(k);const $=Px(I);h($)}catch(O){j(O instanceof Error?O.message:"Failed to load backlinks")}finally{S(!1)}},[t,g]);l.useEffect(()=>{A()},[A]),l.useEffect(()=>{if(!u)return;const O=u.id;let X=!1;const oe=async()=>{try{const I=await Er(O);if(X)return;el(I.status)?(h(null),b(I),await A()):h($=>$?.id===I.id?{...$,...I}:$)}catch{}},k=window.setInterval(()=>{oe()},3e3);return()=>{X=!0,window.clearInterval(k)}},[u,A]),l.useEffect(()=>{if(!u)return;const O=window.setInterval(()=>x(Date.now()),1e3);return()=>window.clearInterval(O)},[u]),l.useEffect(()=>{if(!m||m.status==="failed")return;const O=window.setTimeout(()=>b(null),1e4);return()=>window.clearTimeout(O)},[m]);async function E(){R(!0),j(null);try{const O=await ed(t);h(O)}catch(O){O instanceof pn&&O.code==="MISSING_DEPENDENCY"?j("DuckDB is not installed. Visit the Backlinks admin page to install it."):j(O instanceof Error?O.message:"Failed to trigger extract")}finally{R(!1)}}const D=l.useMemo(()=>o.slice().sort((O,X)=>O.queriedAt.localeCompare(X.queriedAt)).map(O=>({date:O.queriedAt,linkingDomains:O.totalLinkingDomains})),[o]),F=a?.rows??[],V=a?.total??0,B=s?.excludedLinkingDomains??0,w=Math.floor(g/wa)+1;return l.useEffect(()=>{g>0&&g>=V&&f(0)},[g,V]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),y&&e.jsx(fe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:y})}),u&&e.jsx(fe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Sm,{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(de,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Rx(u.startedAt??null,u.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",p]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),m&&!u&&e.jsx(fe,{className:`surface-card p-4 mb-4 ${m.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[m.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(Cm,{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 ${m.status==="failed"?"text-negative":"text-positive"}`,children:m.status==="failed"?"Extract failed":"Extract complete"}),m.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Zc(m.error)}):m.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),G()]});function G(){return N?e.jsx(fe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):L()}function L(){const O=s!==null&&s.totalLinkingDomains>0,X=m?.status==="failed",oe=s!==null&&s.totalLinkingDomains===0&&!X,k=c?.status==="ready",I=c?.status==="failed",$=c&&(c.status==="downloading"||c.status==="querying"||c.status==="queued");return O?ee(e.jsxs(e.Fragment,{children:[!ae()&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:q||u!==null,onClick:He(E),children:[e.jsx(dl,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsx(mr,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ae()&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"Open admin"})})]})):e.jsx(fe,{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(km,{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."}),!ae()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"Set up backlinks"})})})]}),$&&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."]}),!ae()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"View sync status"})})})]}),I&&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."}),!ae()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"Go to Backlinks admin"})})})]}),k&&!$&&!oe&&!X&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:c.release})," is ready. Run an extract for this project."]}),!ae()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(P,{type:"button",size:"sm",disabled:q||u!==null,onClick:He(E),children:[e.jsx(Ka,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":q?"Queuing…":"Run extract"]}),e.jsx(mr,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),X&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!ae()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"Go to Backlinks admin"})})})]}),oe&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!ae()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Nn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:q||u!==null,onClick:He(E),children:[e.jsx(Ka,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsxs(mr,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:s.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function ee(O){if(!s)return null;const X="Linking hosts",oe="linking hosts",k="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:hr(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",oe]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:hr(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",oe," 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:kx(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",oe," 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"})," · ",k," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",Ax(s.queriedAt),B>0&&e.jsxs(e.Fragment,{children:[" · ",B," excluded domain",B===1?"":"s"]})]}),D.length>=2&&e.jsxs(fe,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:D,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:nt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:nt[0],stopOpacity:0})]})}),e.jsx(en,{dataKey:"date",tick:Tt,stroke:ds,tickFormatter:Sx}),e.jsx(tn,{tick:Tt,stroke:ds,allowDecimals:!1}),e.jsx(sn,{contentStyle:es.contentStyle,labelStyle:es.labelStyle,itemStyle:es.itemStyle,labelFormatter:Cx}),e.jsx(Bs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:nt[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(fe,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:X})]})}),e.jsxs("tbody",{children:[F.map(I=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:I.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:hr(I.numHosts)})]},I.linkingDomain)),F.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:B>0&&V===0?`Every referring domain in this ${k} was a crawler/proxy host (${B} hidden).`:`No referring domains in this ${k}.`})})]})]})}),e.jsx(qs,{page:w,pageSize:wa,visibleRows:F.length,totalRows:V,onPageChange:I=>f((I-1)*wa)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:O})]})}}function $x({projectName:t}){const s=$e({...td({client:W,path:{name:t}}),staleTime:si}),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:Xn(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:Ut()?"text-sm text-secondary":"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":Ut()?Js:"Run a sweep to see which engines cite this project."})]});const{providersCiting:r,providersMentioning:o,providersConfigured:i}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",r," of ",i," engines",e.jsx(_e,{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(_e,{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(Tx,{data:n}),e.jsx(Mx,{data:n}),n.competitorGaps.length>0&&e.jsx(Dx,{data:n})]})}function Tx({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:o}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Sa,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Sa,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Sa,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(Sa,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function Sa({label:t,value:s,helper:n,tone:a}){const r=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${r}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function Mx({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(Lx,{}),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($n,{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(ul,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(qx,{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 Lx(){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 qx({provider:t}){const s=Ex(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 Ex(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 Dx({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(_e,{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($n,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Xi="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",xr="flex min-h-11 w-full items-center justify-between gap-3 rounded px-2 text-left text-sm text-primary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",Un=t=>t.kind==="project"?"Whole site":t.label,Zi=t=>`${t} ${t===1?"property":"properties"}`;function Tl({options:t,selected:s,onSelect:n,label:a="Measurement scope",allowGroupSelect:r=!0}){const o=[...t].sort((k,I)=>k.label.localeCompare(I.label,void 0,{numeric:!0})||k.id.localeCompare(I.id)),[i,c]=l.useState(""),[d,u]=l.useState([]),[h,m]=l.useState(!1),b=l.useRef(null),p=l.useRef(null),x=l.useId(),g=o.filter(k=>k.kind==="group"),f=new Map(g.map(k=>[k.id,k])),N=f.get(d.at(-1)??""),S=f.get(d.at(-2)??""),q=i.trim().toLocaleLowerCase(),R=g.filter(k=>!k.parentGroupIds?.some(I=>f.has(I))),y=o.filter(k=>k.kind==="property"),j=k=>(k.parentGroupIds??[]).map(I=>f.get(I)?.label).filter(Boolean).join(" · "),A=k=>`${Un(k)} ${j(k)}`.toLocaleLowerCase().includes(q),E=k=>{const I=[...k.parentGroupIds??[]],$=new Set;for(;I.length;){const te=I.pop();if(te===N?.id)return!0;$.has(te)||($.add(te),I.push(...f.get(te)?.parentGroupIds??[]))}return!1},D=(h?[]:N?g.filter(k=>q?E(k):k.parentGroupIds?.includes(N.id)):q?g:R).filter(A),F=(N?y.filter(k=>k.parentGroupIds?.includes(N.id)):q||h||g.length===0?y:[]).filter(A),V=h||r&&N?[]:o.filter(k=>k.kind==="market"&&(r||N||q||g.length===0)&&(!N||k.parentGroupIds?.includes(N.id))&&A(k)),B=N||h?[]:o.filter(k=>k.kind==="project"&&A(k));l.useEffect(()=>{const k=I=>{b.current?.open&&I.target instanceof Node&&!b.current.contains(I.target)&&(b.current.open=!1)};return document.addEventListener("pointerdown",k),()=>document.removeEventListener("pointerdown",k)},[]);const w=k=>{b.current&&(b.current.open=!1,b.current.querySelector("summary")?.focus()),n(k)},G=k=>{const I=[];let $=f.get(k.parentGroupIds?.[0]??"");for(;$&&!I.includes($.id)&&$.id!==k.id;)I.unshift($.id),$=f.get($.parentGroupIds?.[0]??"");return[...I,k.id]},L=()=>{const k=s.kind==="group"?f.get(s.id):void 0,I=(s.parentGroupIds??[]).flatMap(te=>{const le=f.get(te);return le?[G(le)]:[]}),$=I.find(te=>te.at(-1)===N?.id)??I.sort((te,le)=>le.length-te.length)[0]??[];u(k?G(k):s.kind==="property"?$:[]),m(s.kind==="property"&&$.length===0&&g.length>0),c("")},ee=k=>{u(G(k)),m(!1),c(""),p.current?.focus()},O=(k,I=Un(k))=>e.jsxs("div",{className:"flex items-stretch",children:[e.jsxs("button",{type:"button",className:xr,"aria-label":k.kind==="group"&&!r?`Browse ${Un(k)}`:`Select ${Un(k)}`,"aria-current":s.kind===k.kind&&s.id===k.id?"true":void 0,onClick:()=>k.kind==="group"&&!r?ee(k):w(k),children:[e.jsxs("span",{className:"min-w-0 break-words",children:[I,q&&j(k)?e.jsx("span",{className:"block text-[13px] text-secondary",children:j(k)}):null]}),e.jsx("span",{className:"shrink-0 text-right text-[13px] text-secondary",children:k.kind==="market"?r?"Query context":"Market":k.kind==="property"?"Property":Zi(k.targetCount)})]}),r&&k.kind==="group"&&k.id!==N?.id&&o.some($=>$.parentGroupIds?.includes(k.id))?e.jsx("button",{type:"button","aria-label":`Browse ${k.label}`,title:`Browse ${k.label}`,className:"flex min-h-11 min-w-11 items-center justify-center rounded text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>ee(k),children:e.jsx(Ga,{size:18,"aria-hidden":"true"})}):null]},`${k.kind}:${k.id}`),X=(k,I)=>I.length>0?e.jsxs("section",{"aria-label":k,className:"mt-2",children:[e.jsx("h3",{className:"px-2 py-2 text-[13px] font-medium text-secondary",children:k}),I.map($=>O($))]}):null,oe=(k,I,$)=>I.length>0?e.jsxs("details",{open:$,className:"mt-2 border-y border-default",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer px-2 py-3 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[k," (",I.length,")"]}),I.map(te=>O(te))]},`${N?.id??"root"}:${k}`):null;return e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{id:`${x}-label`,className:"mb-1 block text-sm font-medium text-heading",children:a}),e.jsxs("details",{ref:b,className:"relative",onToggle:k=>{k.target===k.currentTarget&&k.currentTarget.open&&p.current?.focus()},onKeyDown:k=>{k.key==="Escape"&&(k.preventDefault(),k.currentTarget.open=!1,k.currentTarget.querySelector("summary")?.focus())},children:[e.jsxs("summary",{id:`${x}-value`,"aria-labelledby":`${x}-label ${x}-value`,className:`${Xi} visibility-scope-trigger`,onClick:()=>{b.current?.open||L()},children:[`${Un(s)}${s.kind==="group"?` · ${Zi(s.targetCount)}`:s.kind==="property"?" · Property":s.kind==="market"?" · Market":""}`,e.jsx(gn,{size:16,"aria-hidden":"true",className:"shrink-0 text-secondary"})]}),e.jsxs("div",{className:"visibility-scope-menu",children:[N||h?e.jsxs("div",{className:"mb-2 border-b border-default pb-2",children:[e.jsx("button",{type:"button",className:xr,"aria-label":`Back to ${S?.label??"all groups"}`,onClick:()=>{u(d.slice(0,-1)),m(!1),c(""),p.current?.focus()},children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pm,{size:16,"aria-hidden":"true"}),S?.label??"All groups"]})}),e.jsx("p",{className:"px-2 py-1 text-sm font-medium text-heading","aria-live":"polite",children:N?.label??"All properties"})]}):null,e.jsx("input",{ref:p,type:"search","aria-label":"Search scopes",className:Xi,placeholder:N?"Search within this group":h?"Search properties":"Search groups or properties",value:i,onChange:k=>c(k.target.value)}),e.jsxs("div",{className:"mt-2 max-h-80 overflow-y-auto",children:[r&&N&&!q?O(N,"All properties in this group"):null,B.map(k=>O(k)),N&&!q?oe("Subgroups",D,!0):X(N?"Subgroups":"Groups",D),q?X("Properties",F):oe(N&&D.length>0?"All properties":"Properties",F,!N||D.length===0),X("Markets",V),!N&&!h&&!q&&g.length>0&&y.length>0?e.jsxs("button",{type:"button",className:`${xr} mt-2 border-t border-default`,"aria-label":"Browse all properties",onClick:()=>{m(!0),p.current?.focus()},children:[e.jsx("span",{children:"All properties"}),e.jsx(Ga,{size:18,"aria-hidden":"true"})]}):null,q&&D.length+F.length+V.length+B.length===0?e.jsx("p",{className:"py-3 text-sm text-secondary",children:"No matching scopes."}):null]})]})]})]})}const aa="__cited__",ra="__mentioned__",cs="__mentionShare__";function Ml(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Ds(n),end:Ds(a),sweepCount:s.sweepCount??1}}function Ba(t){const s=Ml(t);if(!s)return"Sweep date unavailable";const n=Hs(s.start),a=Hs(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Ox(t){const s=Ml(t);return s?pl(s.start):""}function Mn(t){return t.trim().toLowerCase()}function Ur(t){return Math.round(t*1e3)/10}function Br(t){return t.byProvider??{}}function Fx(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?aa:ra,u=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(m=>({date:m.startDate,[d]:Ur(m[u])})),series:[d],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys(Br(d))))].sort();return{rows:t.buckets.map(d=>{const u={date:d.startDate},h=Br(d);for(const m of i){const b=h[m];u[m]=b?Ur(b[o]):null}return u}),series:i,hasData:a,singleBucket:r}}function Ll(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Gx(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Kx(t){return t.servedModelAttribution??{}}function _x(t){return t.modelServiceMismatch??{}}function Ux(t){return t.modelPointerChanges??{}}function Bx(t){return t.length>0?t.join(", "):null}function eo(t,s){const n=Mn(s);return Object.entries(t).find(([a])=>Mn(a)===n)?.[1]}function Is(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return`Mixed: ${t.models.join(", ")}${t.includesUnknown?" + unknown":""}`}}function Vx(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!eo(Br(a),s))continue;const r=Ll(a);return r?eo(r,s)??null:null}return null}function zx(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 Qx(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:zx(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Hx(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 Wx(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 Yx(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[cs]:r?.rate==null?null:Ur(r.rate)}}),n=s.map(a=>a[cs]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[cs],hasData:n.length>0,singleBucket:n.length===1}}function Jx(t,s,n){return s==="mentionShare"?Yx(t):Fx(t,s,n)}function to(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 so(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function no(t){return t>0?`+${t}`:`${t}`}function Xx(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${no(n.delta)} on ${so(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${no(s.delta)} on ${so(s.date)})`}const Zx=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],$s={"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",Vr=new Intl.NumberFormat("en",{style:"percent",maximumFractionDigits:1});function ep(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function Ss({value:t,unit:s}){return t.rate===null?e.jsx("span",{className:"text-sm text-secondary",children: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:Vr.format(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator,s?` ${s}`:""]})]})}function tp(t){const s=new Map;for(const n of t){const a=s.get(n.queryKey);a?a.rows.push(n):s.set(n.queryKey,{queryKey:n.queryKey,query:n.query,rows:[n]})}return[...s.values()]}function ao({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(Rm,{size:16,"aria-hidden":"true"}):e.jsx(ul,{size:16,"aria-hidden":"true"}),n?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Ss,{value:t}),t.reason==="evidence-incomplete"?e.jsx(_e,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function ro({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 sp({group:t,advanced:s,targetLabels:n,onViewAnswers:a}){const r=t.rows[0],o=u=>JSON.stringify([...u.targetKeys].sort()),i=t.rows.every(u=>o(u)===o(r)),c=t.rows.every(u=>u.location===r.location),d=u=>u===null?"No location targeting":`Search location: ${u}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[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&&i?e.jsx(ro,{targetKeys:r.targetKeys,labels:n}):null,c?e.jsx("span",{children:d(r.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:Cs(u.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:u.model??"Model not recorded"}),s&&!i?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(ro,{targetKeys:u.targetKeys,labels:n})}):null,c?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:d(u.location)})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(ao,{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(ao,{value:u.citationCoverage,singleAnswer:u.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(P,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${u.query} · ${u.provider}`,onClick:()=>a(u),children:[u.answerCount===1?"View answer":"View answers",e.jsx(Ga,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([u.provider,u.model,u.location])))]})}function np({population:t}){const s=l.useId();let n=0;const a=t.trend.map((d,u)=>(u>0&&d.continuity.state!=="comparable"&&(n+=1),{createdAt:Date.parse(d.createdAt),[`mentioned-${n}`]:d.mentionCoverage.rate,[`cited-${n}`]:d.citationCoverage.rate})),r=Array.from({length:n+1},(d,u)=>u),o=new Set(t.trend.slice(1).map(d=>d.continuity.state)),i=[...a.length===1?["First measurement. A trend appears after another comparable run."]:[],...o.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...o.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...o.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(d=>d.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[]];if(a.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const c=t.trend.some(d=>d.mentionCoverage.rate!==null||d.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[c?e.jsxs(e.Fragment,{children:[e.jsxs("ul",{"aria-label":"Trend legend",className:"flex gap-5 py-3 text-sm text-secondary",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:nt[1]}}),"Mentioned"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:Es.positive}}),"Cited"]})]}),i.length>0&&e.jsx("p",{id:s,className:"pb-3 text-sm text-secondary",children:i.join(" ")}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-describedby":i.length>0?s:void 0,"aria-label":`${$s[t.queryClass]} mention and citation trend`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:a,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ta,{stroke:ea,vertical:!1}),e.jsx(en,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Tt,tickLine:!1,axisLine:{stroke:ds},tickFormatter:d=>new Date(Number(d)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(tn,{domain:[0,1],tick:Tt,tickLine:!1,axisLine:!1,width:48,tickFormatter:d=>Vr.format(Number(d))}),e.jsx(sn,{...es,formatter:d=>typeof d=="number"?Vr.format(d):"Not measured",labelFormatter:d=>new Date(Number(d)).toLocaleDateString()}),r.map(d=>e.jsxs(l.Fragment,{children:[e.jsx(Ls,{type:"linear",dataKey:`mentioned-${d}`,name:"Mentioned",stroke:nt[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}}),e.jsx(Ls,{type:"linear",dataKey:`cited-${d}`,name:"Cited",stroke:Es.positive,strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}})]},d))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:c?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${$s[t.queryClass]} trend data`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"}),e.jsx("th",{children:"Comparison"})]})}),e.jsx("tbody",{children:t.trend.map(d=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(d.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(Ss,{value:d.mentionCoverage})}),e.jsx("td",{children:e.jsx(Ss,{value:d.citationCoverage})}),e.jsx("td",{children:d.continuity.state.replaceAll("-"," ")})]},d.runId))})]})})]})}function zr(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function ri(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,o=t.populations.find(u=>u.queryClass===r);if(o)return o;const i=zr(a,s)??zr(t,s),c=t.populations.find(u=>u.queryClass===i?.queryClass);if(c)return c;const d=["non-brand","branded","unknown"].map(u=>t.populations.find(h=>h.queryClass===u));return d.find(u=>u&&(u.summary.queryCount>0||u.trend.some(h=>h.queryCount>0)))??d.find(u=>u!==void 0)??t.populations[0]}function ap({report:t,onSelectionChange:s,queryClass:n=ri(t).queryClass}){const{selection:a,scopeOptions:r,filterOptions:o}=t,i=(c,d,u,h)=>e.jsxs("label",{className:"min-w-0",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:c}),e.jsx("select",{"aria-label":c,className:An,value:u,onChange:m=>s({[d]:m.target.value||void 0,measurementQueryKey:void 0}),children:h.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(Tl,{options:r,selected:a.scope,onSelect:c=>{s({measurementScope:c.kind,measurementScopeKey:c.kind==="project"?void 0:c.id})}}):null,i("Query type","queryClass",n,[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"},{value:"unknown",label:"Unclassified"}]),i("Answer engine","measurementProvider",a.provider??"",[{value:"",label:"All engines"},...o.providers.map(c=>({value:c,label:c}))]),i("Search location","measurementLocation",a.location.kind==="exact"?a.location.value:a.location.kind==="none"?"none":"",[{value:"",label:"All locations"},...o.locations.filter(c=>c.kind!=="all").map(c=>({value:c.kind==="exact"?c.value:"none",label:c.kind==="exact"?c.value:"No location"}))])]})})}function rp({report:t,isRefreshing:s=!1,onSelectionChange:n,onManageQueries:a,onPage:r,onSearch:o,search:i="",queryKey:c,answerSelection:d,evidenceReport:u,isEvidenceLoading:h=!1,evidenceError:m,onRetryEvidence:b,onEvidencePage:p}){const x=l.useRef(null),g=l.useRef(void 0),f=ri(t,c,d,u),N=u??t,S=N.populations.filter(w=>[...w.queries.items,...w.evidence.items].some(G=>G.queryKey===c)),q=d?[d.queryClass]:(S.length?S:h?[]:[f]).map(w=>w.queryClass),R=c?JSON.stringify([d??c,q]):void 0,y=l.useId();l.useEffect(()=>{if(!R){s||(g.current=void 0);return}if(g.current===R)return;const w=x.current?.querySelectorAll('[aria-label="Measured answers"]');if(w?.length){for(const G of w){const L=G.closest("details[data-query-results]");L&&(L.open=!0)}w[0].focus({preventScroll:!0}),w[0].scrollIntoView?.({block:"start"}),g.current=R}},[R,s]);const{selection:j,filterOptions:A}=t,E=j.measurement,D=ep(j.scope),F=new Map(t.scopeOptions.filter(w=>w.kind==="property").map(w=>[w.id,w.label])),V=w=>{const G=N.populations.find(L=>L.queryClass===w.queryClass)?.evidence;return{items:G?.items.filter(L=>L.queryKey===c&&(!d||L.provider===d.provider&&L.model===d.model&&L.location===d.location&&(d.runId===null||L.runId===d.runId)))??[],nextCursor:G?.nextCursor}},B=(w,G,L,ee,O)=>e.jsxs("div",{className:"min-w-40 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1",children:[e.jsx("label",{htmlFor:`${y}-${G}`,className:"text-sm font-medium text-heading",children:w}),e.jsx(_e,{text:O})]}),e.jsx("select",{id:`${y}-${G}`,className:An,value:L,onChange:X=>n({[G]:X.target.value||void 0,measurementQueryKey:void 0}),children:ee.map(X=>e.jsx("option",{value:X.value,children:X.label},X.value))})]});return e.jsxs("section",{ref:x,className:"visibility-report","aria-label":"AI visibility results",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default pb-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(de,{tone:E.state==="measured"?"positive":"neutral",children:E.state==="measured"?"Complete":E.state==="partial"?"Partial":"Not measured"}),E.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:new Date(E.completedAt).toLocaleDateString()}):null,E.awaitingSweep?e.jsxs("span",{role:"status",className:"inline-flex items-center gap-1 text-sm text-secondary",children:[e.jsxs("span",{children:[E.pendingAssignmentCount," query assignments pending across project"]}),e.jsx(_e,{text:`Measured under revision ${E.measuredRevision??"unavailable"}. Project has ${E.pendingAssignmentCount} assignments awaiting sweep. Existing results stay visible until those assignments are measured.`})]}):null]}),a?e.jsx(P,{variant:"outline",onClick:a,children:"Manage queries"}):null]}),j.provenance.kind==="legacy-simple"&&j.queryClass!=="unknown"&&j.queryClass!=="all"?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default py-3 text-sm text-secondary",children:[e.jsx("p",{children:"These saved results aren't separated by query type."}),e.jsx(P,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,e.jsx(ap,{report:t,queryClass:f.queryClass,onSelectionChange:n}),e.jsxs("details",{className:"border-b border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"More filters"}),e.jsxs("div",{className:"flex flex-wrap gap-4 pb-3",children:[e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:"Start date (UTC)"}),e.jsx("input",{type:"date",className:An,value:j.time.from?.slice(0,10)??"",onChange:w=>n({measurementFrom:w.target.value?`${w.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:j.time.to?.slice(0,10)??"",onChange:w=>n({measurementTo:w.target.value?`${w.target.value}T23:59:59.999Z`:void 0})})]}),B("AI model","measurementModel",j.model??"",[{value:"",label:"All models"},...Array.from(new Set(A.models.filter(w=>!j.provider||w.provider===j.provider).map(w=>w.model))).map(w=>({value:w,label:w}))],"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),B("Results from","measurementRunId",j.run.explicit?j.run.id??"":"",[{value:"",label:"Latest saved sweep"},...[...f.trend].reverse().map(w=>({value:w.runId,label:new Date(w.createdAt).toLocaleString()}))],"Choose a saved AI sweep to view its results. No new sweep starts.")]})]}),[f].map(w=>{const G=tp(w.queries.items);return e.jsxs("section",{"aria-label":$s[w.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h2",{children:$s[w.queryClass]}),e.jsx(_e,{text:w.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":w.queryClass==="branded"?"Queries that name the measured identity.":"These queries were not labeled as branded or non-brand when measured. Their saved results remain available here, separate from branded and non-brand rates."})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-8 gap-y-4 border-y border-default py-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:j.mode==="advanced"&&j.scope.kind!=="property"?"Answers mentioning a property":"Mentioned answers"}),j.mode==="advanced"?e.jsx(_e,{text:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned."}):null]}),e.jsx(Ss,{value:w.summary.mentionCoverage,unit:"answers"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:j.mode==="advanced"&&j.scope.kind!=="property"?"Answers citing a property":"Cited answers"}),j.mode==="advanced"?e.jsx(_e,{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(Ss,{value:w.summary.citationCoverage,unit:"answers"})]}),j.mode==="advanced"&&j.scope.kind!=="property"?e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Properties mentioned"}),e.jsx(Ss,{value:w.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:w.summary.queryCount})]})]}),e.jsx(np,{population:w}),j.mode==="advanced"?e.jsxs("details",{className:"border-t border-default text-sm text-secondary","aria-label":`${$s[w.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(([L,ee])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:w.summary.outcomes[L]}),e.jsx("span",{className:"text-sm text-secondary",children:ee}),L==="notMeasured"?e.jsx(_e,{text:"No eligible completed measurement for this selection. This is not the same as a measured answer with neither signal."}):null]},L))})]}):null,j.mode==="advanced"&&j.scope.kind!=="property"&&(w.breakdown.groups.length>0||w.breakdown.properties.length>0)?e.jsx(ip,{population:w,scope:j.scope,scopeOptions:t.scopeOptions,onSelectionChange:n},`${j.scope.kind}:${j.scope.id}`):null,e.jsxs("details",{className:"border-t border-default","data-query-results":w.queryClass,"aria-label":`${$s[w.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:[w.queries.total," ",w.queries.total===1?"result":"results"," · ",D]})]}),e.jsxs("div",{className:"pb-5",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-3",children:[o?e.jsx("input",{type:"search","aria-label":`Search ${$s[w.queryClass]}`,placeholder:"Search queries",className:`${An} max-w-sm`,value:i,onChange:L=>o(L.target.value)}):null,e.jsx(_e,{text:j.mode==="advanced"?"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, property scope, and answer counts. Mentioned and Cited count answers matching any assigned property, not the percentage of properties found.":"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, and answer counts. Mentioned counts answers naming your brand. Cited counts answers linking to your site."})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table measurement-results-table","aria-label":`${$s[w.queryClass]} engine results`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Answer engine"}),e.jsx("th",{scope:"col",children:"Mentioned"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),G.map(L=>e.jsx(sp,{group:L,advanced:j.mode==="advanced",targetLabels:F,onViewAnswers:ee=>n({measurementQueryKey:ee.queryKey,measurementAnswer:JSON.stringify({queryKey:ee.queryKey,queryClass:w.queryClass,provider:ee.provider,model:ee.model,location:ee.location,runId:j.run.id,revision:j.revision})})},L.queryKey))]})}),w.queries.items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:"No measured queries match this selection."}):e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:[G.length," ",G.length===1?"query":"queries"," · ",w.queries.items.length," ",w.queries.items.length===1?"engine result":"engine results"," shown of ",w.queries.total," results"]}),w.queries.nextCursor&&r?e.jsx(P,{variant:"outline",onClick:()=>r(w.queries.nextCursor),children:"Next queries"}):null,c&&q.includes(w.queryClass)?e.jsxs("section",{tabIndex:-1,className:"scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-label":"Measured answers","aria-busy":h,children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h3",{children:"Answers"}),e.jsx(P,{variant:"ghost",onClick:L=>{g.current=void 0,L.currentTarget.closest("details[data-query-results]")?.querySelector("summary")?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})},children:"Close answers"})]}),h?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(P,{variant:"outline",onClick:b,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[V(w).items.map(L=>e.jsxs("article",{className:"border-b border-default py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("strong",{className:"text-sm text-heading",children:L.provider}),L.model?e.jsx("span",{className:"text-sm text-secondary",children:L.model}):null,e.jsx("span",{className:"text-sm text-secondary",children:L.location??"No location"}),e.jsx("span",{className:"text-sm text-secondary",children:new Date(L.createdAt).toLocaleString()}),e.jsx(de,{tone:"neutral",children:L.mentioned===null?"Mention not checked":L.mentioned?"Mentioned":"Not mentioned"}),e.jsx(de,{tone:"neutral",children:L.cited===null?"Citation not checked":L.cited?"Cited":"Not cited"})]}),e.jsx("h4",{className:"mt-3 text-sm font-medium text-heading",children:L.query}),e.jsx("p",{className:"mt-3 max-w-prose whitespace-pre-wrap text-sm leading-6 text-primary",children:L.answerText??"Answer text unavailable."}),e.jsx("ul",{className:"mt-3 space-y-2",children:L.sources.map(ee=>{const O=Ts(ee);return e.jsx("li",{className:"break-all text-sm",children:O?e.jsx("a",{href:O,target:"_blank",rel:"noreferrer",className:"text-link hover:underline",children:ee}):e.jsx("span",{className:"text-secondary",children:ee})},ee)})})]},L.answerId)),V(w).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:V(w).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,V(w).nextCursor&&p?e.jsx(P,{variant:"outline",onClick:()=>p(V(w).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"border-t border-default","aria-label":`${$s[w.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:w.competitorAvailability.state==="unavailable"?"Not available":`${w.competitors.length} measured`})]}),e.jsxs("div",{className:"pb-5",children:[w.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):w.competitors.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No measured competitors in this selection."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Competitor"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:w.competitors.map(L=>e.jsxs("tr",{children:[e.jsx("td",{children:L.domain}),e.jsx("td",{children:e.jsx(Ss,{value:L.mentionCoverage})}),e.jsx("td",{children:e.jsx(Ss,{value:L.citationCoverage})})]},L.domain))})]})}),w.observedCompetitors.length>0?e.jsxs("details",{className:"mt-4 text-sm",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-heading",children:"Other names in answers"}),e.jsx("ul",{className:"divide-y divide-default",children:w.observedCompetitors.map(L=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:L.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[L.answerCount," ",L.answerCount===1?"answer":"answers"]})]},L.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},w.queryClass)})]})}function ip({population:t,scope:s,scopeOptions:n,onSelectionChange:a}){const r=new Map(n.filter(h=>h.kind==="group").map(h=>[h.id,h])),o=[...r.values()].some(h=>h.parentGroupIds?.length),i=t.breakdown.groups.filter(h=>{const m=r.get(h.id)?.parentGroupIds??[];return s.kind==="project"?m.length===0:s.kind==="group"&&o?m.includes(s.id):!0}),[c,d]=l.useState(()=>s.kind==="project"&&i.length>0?"groups":"properties"),u=fn({rows:c==="groups"?i:t.breakdown.properties,getSearchText:h=>h.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(h=>e.jsx(P,{variant:c===h?"secondary":"ghost",onClick:()=>{d(h),u.setPage(1)},children:h==="groups"?"Groups":"Properties"},h))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:u.query,onChange:h=>u.setQuery(h.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(h=>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:()=>a({measurementScope:c==="groups"?"group":"property",measurementScopeKey:h.id}),children:h.label})}),e.jsx("td",{children:h.queryCount}),e.jsx("td",{children:e.jsx(Ss,{value:h.mentionCoverage})}),e.jsx("td",{children:e.jsx(Ss,{value:h.citationCoverage})})]},h.id))})]})}),u.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",c," match this search."]}):null,e.jsx(qs,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:c,onPageChange:u.setPage})]})}function op({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,fallback:r,showUnmeasuredFallback:o=!1}){const[i,c]=l.useState(),[d,u]=l.useState(""),[h,m]=l.useState(),b=ms(),p=l.useMemo(()=>({scope:s.measurementScope,scopeKey:s.measurementScopeKey,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.queryClass,s.provider,s.model,s.location,s.from,s.to,s.revision,s.measurementRunId]),x=$e({...Xa({client:W,path:{name:t},query:{...p,limit:25,cursor:i,search:d||void 0}}),staleTime:ad,retry:!1,placeholderData:ei}),g={...p,queryKey:s.queryKey,queryClass:s.answer?.queryClass??s.queryClass,provider:s.answer?.provider??s.provider,model:s.answer?s.answer.model??void 0:s.model,location:s.answer?s.answer.location??"none":s.location,runId:s.answer?.runId??x.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??x.data?.selection.revision??s.revision,limit:50},f=JSON.stringify(g),N=$e({...Xa({client:W,path:{name:t},query:{...g,cursor:h?.selection===f?h.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&&!zr(x.data,s.queryKey)&&!N.data)return;const S=ri(x.data,s.queryKey,s.answer,N.data);if(!i&&!d){const{queryKey:q}=Xa({client:W,path:{name:t},query:{...p,queryClass:S.queryClass,limit:25}});b.setQueryData(q,{...x.data,selection:{...x.data.selection,queryClass:S.queryClass},populations:[S]},{updatedAt:x.dataUpdatedAt})}n({queryClass:S.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,N.data,n,b,t,p,i,d]),x.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:r});if(o&&x.data?.selection.mode==="simple"&&x.data.selection.measurement.state==="not-measured")return e.jsx(e.Fragment,{children:r});if(x.error){const S=Xn(x.error),q=s.measurementScope!=="project"&&S.includes("scope")&&S.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:q?"This saved group or property filter is unavailable for this measurement. Show the whole site to choose another.":S}),q?e.jsx(P,{variant:"outline",onClick:()=>{c(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:"Show whole site"}):e.jsx(P,{variant:"outline",onClick:()=>{c(void 0),x.refetch()},children:"Retry"})]})}return x.data?e.jsx("div",{"aria-busy":x.isFetching,children:e.jsx(rp,{report:x.data,isRefreshing:x.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:N.data,isEvidenceLoading:N.isFetching||!!s.queryKey&&N.isPending,evidenceError:N.error?Xn(N.error):void 0,onRetryEvidence:()=>{N.refetch()},onEvidencePage:N.isFetching?void 0:S=>m({selection:f,cursor:S}),search:d,onSearch:S=>{u(S),c(void 0)},onPage:x.isFetching?void 0:c,onSelectionChange:S=>{(!("measurementQueryKey"in S)||Object.keys(S).some(q=>q!=="measurementQueryKey"&&q!=="measurementAnswer"))&&c(void 0),m(void 0),n(S)},onManageQueries:a})}):e.jsx("section",{className:"page-section-divider",role:"status","aria-label":"Loading AI visibility",children:e.jsx("div",{className:"h-64 animate-pulse rounded-md bg-surface"})})}const lp=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],cp=[{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."}],ii=nt[2],dp="var(--chart-tooltip-bg)",up={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Cs(t){const s=Mn(t);return up[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Vs(t){return Math.round(t*10)/10}function mp(t){return t===aa||t===ra||t===cs}function ql(t){return t===aa?"Cited":t===ra?"Mentioned":t===cs?"Mention share":Cs(t)}function zn(t,s){return t===aa?Es.positive:t===ra?nt[1]:t===cs?ii:qm(Mn(t),s)}function hp(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function xp(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
2
- `)}function Wa(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function qa(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${Wa(s)}`:"Mention share":"Mentioned"}function sa(t){return t==="cited"?"citationRate":"mentionRate"}function El(t,s){return s==="cited"?t.cited:t.mentionedCount}function Dl(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 Ol(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Qr(t){const s=Ll(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>Mn(a).localeCompare(Mn(r))).map(([a,r])=>`${Cs(a)}: ${Is(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function pp(t){return t.some(({event:s})=>s.to.status==="mixed")?Es.caution:t.some(({event:s})=>s.to.status==="unknown")?Es.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?nt[4]:Es.positive}function gp(t,s,n){const a=Ol(t,s);return a?Ba(a):Hs(Ds(n))}function fp({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:o,mismatch:i,buckets:c}){const d=l.useId(),u=Object.entries(o).sort(([m],[b])=>m.localeCompare(b)),h=t.buckets.length>0||t.beforeWindow.length>0;return!s||!h?null:e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":d,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:d,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:m,events:b})=>b.map(({provider:p,event:x})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:gp(c,m,x.observedAt)}),e.jsxs("span",{children:[Cs(p),": ",Is(x.from)," → ",Is(x.to)]})]},`${p}-${x.observedAt}-${x.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:m,event:b})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Hs(Ds(b.observedAt))]}),e.jsxs("span",{children:[Cs(m),": ",Is(b.from)," → ",Is(b.to),b.anchorObservedAt?` (last seen ${Is(b.from)} on ${Hs(Ds(b.anchorObservedAt))})`:""]})]},`before-${m}-${b.observedAt}`))})]}),a.map(m=>e.jsxs("p",{className:"trend-model-evidence-note",children:[Cs(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 ",Cs(m)," change."]},`incomplete-${m}`)),u.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:u.map(([m,b])=>{const p=Bx(b.latestServedModelIds),x=i[m];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Hs(Ds(b.latestObservation.observedAt))}),e.jsxs("span",{children:[Cs(m),": ",p??Is(b.latestObservation.state),x?` — not the ${Is(x.configured)} you selected`:""]})]},`served-${m}`)})})]})]})}function io(t){return t===null?"no data":`${t}%`}function pr(t){return t==null?"undefined":`${Vs(t*100)}%`}function yp({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=Ol(o,s);if(!i)return null;if(a==="mentionShare"){const d=i.mentionShare.projectMentionSnapshots,u=i.mentionShare.competitorMentionSnapshots,h=d+u,m=i.mentionShare.rate==null?null:Vs(i.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Ba(i)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:ii},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",Wa(i.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:io(m)})]}),h>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",d," / ",h," brand mentions. Competitors ",u,"."]}):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:Qr(i)})]})}const c=r==="byProvider"?(n??[]).filter(d=>d.dataKey!==void 0):[{dataKey:a==="cited"?aa:ra,value:Vs(i[sa(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Ba(i)}),c.map((d,u)=>{const h=String(d.dataKey??d.name??""),m=r==="byProvider"?Dl(i,h,a):null,b=m?.count??El(i,a),p=m?.total??i.total,x=typeof d.value=="number"?d.value:Vs(m?m.rate*100:i[sa(a)]*100),g=d.color??zn(h,u);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:g},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:ql(h)}),e.jsx("span",{className:"trend-tooltip-value",children:io(x)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[b," / ",p," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${h}-${u}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:Qr(i)})]})}function bp({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:[qa(s,r)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(o=>{let i;if(s==="mentionShare"){const c=o.mentionShare.projectMentionSnapshots,d=o.mentionShare.competitorMentionSnapshots,u=c+d,h=Wa(o.mentionShare.scope);i=u>0?`${pr(o.mentionShare.rate)} mention share for ${h}, ${c} of ${u} brand mentions were you`:`mention share undefined for ${h}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(c=>{const d=Dl(o,c,s);return d?`${Cs(c)} ${pr(d.rate)} ${qa(s).toLowerCase()}, ${d.count} of ${d.total} snapshots`:`${Cs(c)} no data`}).join("; "):i=`${pr(o[sa(s)])} ${qa(s).toLowerCase()}, ${El(o,s)} of ${o.total} snapshots`;return i+=`; ${Qr(o)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Ba(o)}),e.jsx("td",{children:i})]},o.startDate)})})]})}function gr({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const o=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(i=>{const c=s===i.value,d=i.description?`${o}-${i.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":c,"aria-describedby":d,className:`segmented-option ${c?"segmented-option-active":""}`,onClick:()=>n(i.value),children:i.label}),i.description&&e.jsx("span",{id:d,className:"sr-only",children:i.description})]},i.value)})})}function vp({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[o,i]=l.useState("mentioned"),[c,d]=l.useState("byProvider"),u=l.useMemo(()=>xp(s),[s]),h=$e({queryKey:["analytics-metrics",t,a,u,n],queryFn:()=>sd(t,a),staleTime:si}),m=h.data??null,b=h.error,p=o==="mentionShare"?"overall":c,x=l.useMemo(()=>m?Jx(m,o,p):null,[m,o,p]),g=m?Gx(m):null,f=l.useMemo(()=>Qx(g??{}),[g]),N=l.useMemo(()=>Hx(g??{}),[g]),S=l.useMemo(()=>Wx(g??{}),[g]),q=l.useMemo(()=>Object.entries(g??{}).filter(([,I])=>I.anchorUnavailable).map(([I])=>I).sort(),[g]),R=l.useMemo(()=>m?Kx(m):{},[m]),y=l.useMemo(()=>m?_x(m):{},[m]),j=l.useMemo(()=>m?nd(Ux(m)):null,[m]),A=o!=="mentionShare"&&p==="byProvider",E=m?.buckets??[],D=E[E.length-1]?.mentionShare.scope??m?.mentionShareScope??"pooled",F=qa(o,D),V=o==="cited"?Es.positive:o==="mentionShare"?ii:nt[1],B=A?us.textDim:V,w=l.useMemo(()=>{const I=new Map(E.map($=>[$.startDate,Ox($)]));return $=>I.get(String($))??""},[E]),G=o==="mentionShare"?x?to(x.rows,cs):null:E.length>0?Vs(E[E.length-1][sa(o)]*100):null,L=o==="mentionShare"?x?hp(x.rows,cs):null:E.length>0?Vs(E[0][sa(o)]*100):null,ee=o==="mentionShare"?x?.rows.filter(I=>typeof I[cs]=="number").length??0:E.length,O=G!==null&&L!==null&&ee>1?Vs(G-L):null,X=s.length,oe=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(_e,{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."})]})]}),G!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:B},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:F}),A&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[G,"%"]}),O!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${O>0?"text-positive-400":O<0?"text-negative-400":"text-muted"}`,children:[O>0?"+":"",O.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(gr,{options:cp,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(gr,{options:lp,value:c,onChange:d,ariaLabel:"Series"}),e.jsx(gr,{options:Zx,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let k;if(b)k=e.jsx("p",{className:"text-sm text-negative-400",children:Xn(b)});else if(h.isLoading&&!m)k=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(o==="mentionShare"&&X===0)k=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!m||!x)k=null;else{const{rows:I,series:$,hasData:te}=x,le=Xx(m.queryChanges);if(!te)k=e.jsx("p",{className:"text-sm text-secondary",children:o==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${Wa(D)} in this window yet.`:Ut()?Js:"Run a sweep to start tracking citations and mentions over time."});else if(A&&$.length===0)k=e.jsxs("p",{className:"text-sm text-secondary",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-strong",children:"All engines"})," to see the trend."]});else{const pe=`${F} rate across ${I.length} ${I.length===1?"sweep":"sweeps"}. Latest ${G}%${O!==null?`, ${O>=0?"up":"down"} ${Math.abs(O).toFixed(1)} points over the period`:""}.`;k=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:pe}),e.jsx(bp,{buckets:E,metric:o,mode:p,series:$}),A&&$.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:$.map((ie,Ne)=>{const Y=to(I,ie),z=Vx(E,ie),ne=g===null?"Attribution unavailable":z?Is(z):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:zn(ie,Ne)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:ql(ie)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),ne]})]}),Y!==null&&e.jsxs("span",{className:"trend-legend-value",children:[Y,"%"]})]},ie)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${F} trend chart over ${I.length} ${I.length===1?"bucket":"buckets"}`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:I,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ta,{stroke:ea,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Tt,tickLine:!1,axisLine:{stroke:ds},tickFormatter:w,minTickGap:24}),e.jsx(tn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:ie=>`${ie}%`,tick:Tt,tickLine:!1,axisLine:!1,width:40}),e.jsx(sn,{cursor:{stroke:ds,strokeWidth:1},content:e.jsx(yp,{metric:o,mode:p,buckets:E})}),f.buckets.map(({bucketStartDate:ie,events:Ne})=>e.jsx(Km,{x:ie,stroke:pp(Ne),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${ie}`)),$.map((ie,Ne)=>e.jsx(Ls,{type:"monotone",dataKey:ie,name:ie,stroke:zn(ie,Ne),strokeDasharray:ie===cs?"5 4":void 0,strokeWidth:mp(ie)?2.5:2,dot:ie===cs?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:zn(ie,Ne),strokeWidth:1.5}:{r:2.5,fill:zn(ie,Ne),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:dp},connectNulls:ie!==cs,isAnimationActive:!1},ie))]})})}),e.jsx(fp,{partition:f,available:g!==null,counts:N,truncated:S,incompleteHistory:q,served:R,mismatch:y,buckets:E}),le&&e.jsx("p",{className:"visibility-trend-note",children:le})]})}}return e.jsxs("section",{className:"visibility-trend",children:[oe,k]})}const oo=new Set([Yn.queued,Yn.running]),ls={queryPlaceholder:"Write one research query per line",runAction:"Run queries",historyTitle:"Research history",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 lo({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:o,scopeError:i,onRetryScope:c,templates:d=[],viewerResearchConfig:u=null}){const h=ms(),{account:m,canWrite:b}=Ln(),p=m?.role==="viewer"&&u!==null,x=!b,[g,f]=l.useState(""),[N,S]=l.useState(""),[q,R]=l.useState(null),[y,j]=l.useState([]),A=l.useRef(null),E=l.useRef(!1),[D,F]=l.useState(0),V=$e({...rd({client:W,path:{name:t}}),staleTime:6e4}),B=$e({...id({client:W}),enabled:!x,staleTime:6e4}),w=$e({...od({client:W,path:{name:t},query:{limit:20}}),refetchInterval:z=>z.state.data?.runs.some(ne=>oo.has(ne.status))?3e3:!1}),G=w.isError?[]:w.data?.runs??[],L=w.data?.access?.canRun??(b||p),ee=w.data?.access?w.data.access.dailyRunLimit:p?u.viewerDailyRunLimit:null;l.useEffect(()=>{!q&&G[0]&&R(G[0].id)},[G,q]);const O=G.find(z=>z.id===q)??null,X=$e({...ld({client:W,path:{name:t,runId:q??""}}),enabled:!w.isError&&!!q,refetchInterval:O&&oo.has(O.status)?3e3:!1}),oe=w.isError||X.isError?null:X.data??null,k=V.data?.locations??[],I=l.useMemo(()=>{if(x)return(w.data?.providers??[]).map(ne=>({...ne,catalog:ne}));const z=new Map((B.data?.providerCatalog??[]).map(ne=>[ne.name,ne]));return(B.data?.providers??[]).filter(ne=>ne.configured&&z.get(ne.name)?.mode==="api").map(ne=>({...ne,catalog:{...z.get(ne.name),defaultModel:ne.model||z.get(ne.name).defaultModel}}))},[x,w.data?.providers,B.data]),$=!(x?w.isPending:B.isPending)&&I.length===0,te=I.find(z=>z.name===g)??null;l.useEffect(()=>{if(!g&&V.data&&!V.isError&&!B.isError){const z=V.data.providers.find(ne=>I.some(Z=>Z.name===ne));f(z??I[0]?.name??"")}},[g,I,V.data,V.isError,B.isError]);const le=te?.catalog.modelConfigurable??!1,pe=x?te?.catalog.defaultModel:(te?V.data?.providerModels[te.name]:"")||te?.catalog.defaultModel,ie=(le?N.trim():"")||pe,Ne=te?[...new Map([{id:te.catalog.defaultModel,displayName:te.catalog.defaultModel},...N.trim()?[{id:N.trim(),displayName:N.trim()}]:[],...te.catalog.knownModels].map(z=>[z.id,z])).values()]:[],Y=Pt({...cd(),onSuccess:async z=>{A.current=null,F(ne=>ne+1),j(z.runs),R(z.runs[0]?.id??null),await Ip(h),Te({title:"Research batch saved",detail:`${z.runs.length} ${z.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${z.runs.map(ne=>ne.id).join(":")}`,dedupeMode:"replace"})},onError:z=>{Te({title:"Could not start research",detail:z instanceof Error?z.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{E.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(jp,{projectName:t,canWrite:b,researchAllowed:L&&!w.isError,limitedAccess:x,isEmbed:ae(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:o,scopeError:i,onRetryScope:c,templates:d,locations:k,defaultLocation:V.data?.defaultLocation??null,providerOptions:I,provider:g,onProviderChange:z=>{f(z),S("")},resolvedModel:ie,visibilityModel:pe,configurableModel:le,model:N,onModelChange:S,modelOptions:Ne,settingsReady:x?!w.isPending&&!w.isError:!B.isPending&&!B.isError&&!B.isFetching,projectReady:!V.isPending&&!V.isError&&!V.isFetching,isPending:Y.isPending,errorMessage:Y.isError?"The request could not be confirmed.":void 0,onSubmit:(z,ne)=>{!L||w.isError||ae()||E.current||(A.current?.fingerprint!==ne&&(A.current={fingerprint:ne,key:crypto.randomUUID()}),E.current=!0,Y.mutate({client:W,path:{name:t},body:{...z,idempotencyKey:A.current.key}}))}},`${t}:${D}`),ee!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",ee," destination runs per project per day."]}),!x&&B.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(P,{variant:"outline",onClick:()=>{B.refetch()},children:"Retry providers"})]}):null,V.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(P,{variant:"outline",onClick:()=>{V.refetch()},children:"Retry locations"})]}):null,!(x?w.isError:B.isError)&&$&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:x?"No research engines are available. Ask your Canonry team to configure one.":"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."}),y.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",y.map((z,ne)=>e.jsxs("span",{children:[ne>0?", ":"",e.jsxs("a",{href:`#research-run-${z.id}`,className:"text-link underline",onClick:()=>R(z.id),children:[z.scope?.label??"Whole site",z.location?`, ${z.location.label}`:", No location"]})]},z.id))]}),e.jsxs(fe,{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:ls.historyTitle})}),w.isFetching&&e.jsx(de,{tone:"neutral",children:"Loading"})]}),w.isError?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(P,{variant:"outline",onClick:()=>{w.refetch()},children:"Retry history"})]}):w.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):G.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:ls.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:G.map(z=>e.jsxs("tr",{className:q===z.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>R(z.id),children:Ap(z.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:z.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:z.requestedModel??z.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:z.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:z.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[z.completedQueries+z.failedQueries,"/",z.totalQueries]}),e.jsx("td",{children:e.jsx(de,{tone:Fl(z.status),children:z.status})})]},z.id))})]})})]})]}),!w.isError&&X.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(P,{variant:"outline",onClick:()=>{X.refetch()},children:"Retry results"})]}):w.isError?null:e.jsx(Cp,{detail:oe,isLoading:X.isFetching,onReviewForTracking:s})]})}const ws="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 jp(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:o}=t,i=ms(),[c,d]=l.useState("once"),[u,h]=l.useState(""),[m,b]=l.useState(""),[p,x]=l.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[g,f]=l.useState(null),[N,S]=l.useState([]),[q,R]=l.useState(""),[y,j]=l.useState({}),[A,E]=l.useState(null),[D,F]=l.useState([]),[V,B]=l.useState(null),[w,G]=l.useState(!1),[L,ee]=l.useState(!1),[O,X]=l.useState(""),[oe,k]=l.useState(""),I=l.useRef(null),$=l.useRef(!1),te=l.useRef(null),le=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";l.useEffect(()=>{x(le),E(null)},[le]);const pe=t.scopeOptions.filter(C=>C.kind==="market"||C.kind==="property"),ie=c==="markets"?"market":"property",Ne=pe.filter(C=>C.kind===ie),Y=C=>({kind:C.kind,key:C.id,label:C.label,planRevision:o??t.initialScope?.planRevision??0}),z=C=>C===Pn?null:n.find(Ce=>Ce.label===C),ne=g??t.defaultLocation??Pn,Z=pe.find(C=>`${C.kind}:${C.id}`===p),be=Z?Y(Z):null,ce=c==="once"?[{scope:be,location:z(ne)}]:c==="locations"?N.map(C=>({scope:null,location:z(C)})):N.map(C=>Ne.find(Ce=>`${Ce.kind}:${Ce.id}`===C)).map(C=>C?{scope:Y(C),location:z(y[`${C.kind}:${C.id}`]??Pn)}:null),De=[...new Map([...D,...t.templates].map(C=>[C.id,C])).values()],we=A?De.find(C=>C.id===A.id):null,Se=A!==null&&we?.version!==A.version,Je=c==="once"?u:m,Ue=Je.split(/\r?\n/).filter(C=>C.trim()),Be=Ni(Ue),ze=[...new Set([...m.matchAll(/\{([^{}]+)\}/g)].map(C=>C[1]))],Oe=/[{}]/.test(m.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),_=[];Ue.length||_.push(c==="once"?"Enter at least one query.":"Enter at least one query pattern."),Ue.some(C=>C.length>4e3)&&_.push("Keep each query under 4,001 characters."),c!=="once"&&Oe&&_.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),ce.length||_.push(c==="locations"?"Select at least one location.":"Select at least one destination."),ce.some(C=>!C||C.location===void 0)&&_.push("A selected destination or location is no longer available. Update your selection.");const U=c==="once"&&p!=="project"||c==="markets"||c==="properties";U&&(t.scopePending||t.scopeError||!o||ce.some(C=>!C?.scope))&&_.push("Load the current published markets and properties before running scoped research.");const H=(c==="once"?Be.length:Ue.length)*ce.length;if(ce.length>ya&&_.push(`Select at most ${ya} destinations.`),H>er&&_.push(`${H} queries selected. Reduce the selection to ${er} or fewer.`),Se&&_.push("This saved pattern changed. Select its current version from Saved patterns."),c!=="once"&&!Oe){for(const C of ce)if(!(!C||C.location===void 0))try{Za(A??{pattern:m,variables:ze},C.scope,C.location)}catch{_.push(`Choose a location for {location}, or use only variables available for ${c==="markets"?"markets":c==="properties"?"properties":"locations"}.`);break}}const Ie=JSON.stringify({mode:c,source:Je,contexts:ce,provider:a,resolvedModel:r,template:A,...U?{planRevision:o}:{}}),Ge=V!==null&&V.signature!==Ie,se=c==="once"?Be.map((C,Ce)=>({id:String(Ce),query:C,scope:be,location:ce[0]?.location??null})):V?.rows??[],Xe=Sp(se),ut=[];c!=="once"&&V&&(Ge&&ut.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),se.some(C=>!C.query.trim()||C.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(C.query))&&ut.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),se.some(C=>C.location&&!n.some(Ce=>JSON.stringify(Ce)===JSON.stringify(C.location)))&&ut.push("A preview location changed. Regenerate the preview."),Xe.some(C=>Ni(C.queries).length!==C.queries.length)&&ut.push("Remove duplicate queries within each destination and location."),Xe.length>ya&&ut.push(`The preview exceeds ${ya} runs.`));const mt=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!_.length&&!ut.length&&(c==="once"||V!==null),Ve=()=>({runs:Xe.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}}:{},...A?{template:{templateId:A.id,templateVersion:A.version}}:{}}))}),Fe=()=>{if(G(!0),_.length)return;const C=ce.flatMap((Ce,ve)=>Ue.map((Ye,yt)=>({id:`${ve}:${yt}`,scope:Ce.scope,location:Ce.location,query:Za({pattern:Ye,variables:[...new Set([...Ye.matchAll(/\{([^{}]+)\}/g)].map(tt=>tt[1]))]},Ce.scope,Ce.location).output})));B({signature:Ie,rows:C})},ht=C=>{d(C),S([]),E(null),R(""),G(!1)},Ze=C=>{if(k(""),c==="once")try{h(Za(C,be,z(ne)).output)}catch{k("Select a matching market, property, or location before using this pattern.");return}else b(C.pattern);E(C)},Ae=C=>{const Ce=te.current,ve=Ce?.selectionStart??m.length,Ye=Ce?.selectionEnd??ve;b(`${m.slice(0,ve)}{${C}}${m.slice(Ye)}`),E(null),requestAnimationFrame(()=>{Ce?.focus(),Ce?.setSelectionRange(ve+C.length+2,ve+C.length+2)})},at=Pt({...ud(),onSuccess:async C=>{const Ce={id:C.id,version:C.updatedAt,label:C.name,pattern:C.pattern,variables:C.variables};F(ve=>[...ve.filter(Ye=>Ye.id!==C.id),Ce]),E(Ce),ee(!1),X(""),k(""),I.current=null,await i.invalidateQueries({queryKey:dd({client:W,path:{name:s}})}),Te({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>k("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{$.current=!1}}),kt=()=>{if(!t.canWrite||t.isEmbed||$.current)return;const C=c==="once"?u:m,Ce=c==="once"?[]:ze;if(!O.trim()||!C.trim()||C.length>4e3||c!=="once"&&Oe){k("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const ve={name:O.trim(),pattern:C,variables:Ce},Ye=JSON.stringify(ve);I.current?.fingerprint!==Ye&&(I.current={fingerprint:Ye,id:crypto.randomUUID()}),$.current=!0,at.mutate({client:W,path:{name:s,templateId:I.current.id},body:ve})},Mt=[...new Set([...w||Je.trim()?_:[],...ut])],Ee=De.filter(C=>{const Ce=c==="once"?wi(be,z(ne)):wi(c==="markets"?{kind:"market",label:"Market"}:c==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return C.variables.every(ve=>Ce[ve]!==void 0)});return e.jsxs(fe,{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||at.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:ws,value:c,disabled:t.isPending,onChange:C=>ht(C.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!pe.some(C=>C.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!pe.some(C=>C.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),c==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(pe.length>0||p!=="project")&&e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Save results under"}),e.jsxs("select",{className:ws,value:p,onChange:C=>{x(C.target.value),E(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),p!=="project"&&!Z&&e.jsx("option",{value:p,disabled:!0,children:"Selected destination unavailable"}),pe.map(C=>e.jsxs("option",{value:`${C.kind}:${C.id}`,children:[C.label," (",C.kind,")"]},`${C.kind}:${C.id}`))]})]}),e.jsx(Hr,{label:"Answer engine location",value:ne,locations:n,onChange:C=>{f(C),E(null)}})]}),c!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:c==="locations"?"Select locations":`Select ${c}`}),e.jsx("p",{className:"text-sm text-secondary",children:"Choose each destination explicitly. Each selected destination gets its own saved research run."}),e.jsx("input",{type:"search","aria-label":"Search destinations",className:ws,placeholder:`Search ${c}`,value:q,onChange:C=>R(C.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(c==="locations"?n.map(C=>({key:C.label,label:C.label})):Ne.map(C=>({key:`${C.kind}:${C.id}`,label:C.label}))).filter(C=>C.label.toLocaleLowerCase().includes(q.toLocaleLowerCase())).map(C=>{const Ce=N.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:Ce,onChange:()=>S(ve=>Ce?ve.filter(Ye=>Ye!==C.key):[...ve,C.key])}),C.label]}),Ce&&c!=="locations"&&e.jsx(Hr,{label:`Answer engine location for ${C.label}`,value:y[C.key]??Pn,locations:n,onChange:ve=>j(Ye=>({...Ye,[C.key]:ve}))})]},C.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[N.length," selected. A market or property name changes query text, not the answer engine's location."]})]}),t.scopeError&&e.jsxs("p",{className:"text-sm text-caution",children:["Markets and properties could not load. Whole-site and location research remain available. ",e.jsx(P,{variant:"outline",onClick:t.onRetryScope,children:"Retry destinations"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block",htmlFor:"research-query-editor",children:e.jsx("span",{className:"text-sm font-medium text-heading",children:c==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:c==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${c==="markets"?"market":c==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:te,className:`${ws} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:Je,placeholder:c==="once"?ls.queryPlaceholder:c==="markets"?"Best apartments in {market}":c==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:C=>{c==="once"?h(C.target.value):(b(C.target.value),E(null))}}),c!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(P,{size:"sm",variant:"outline",onClick:()=>Ae(c==="markets"?"market":c==="properties"?"property":"location"),children:["Insert ",c==="markets"?"market":c==="properties"?"property":"location"," name"]}),e.jsx("span",{className:"self-center text-sm text-secondary",children:"One pattern per line."})]}),e.jsxs("p",{id:"research-query-count",className:"mt-2 text-sm text-secondary",children:[H," / ",er," queries",c==="once"?"":` across ${ce.length} destinations`]})]}),c!=="once"&&e.jsxs("details",{className:"border-t border-default pt-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading focus-visible:outline focus-visible:outline-2",children:["Saved patterns ",e.jsx("span",{className:"font-normal text-secondary",children:"(optional)"})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries."}),Ee.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:Ee.map(C=>e.jsx(P,{size:"sm",variant:"outline",onClick:()=>Ze(C),children:C.label},C.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),A&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",A.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(P,{size:"sm",variant:"outline",onClick:()=>ee(!L),children:L?"Cancel save":"Save as a pattern"}),L&&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:ws,value:O,maxLength:120,onChange:C=>X(C.target.value)})]}),e.jsx(P,{size:"sm",disabled:at.isPending||!O.trim()||!Je.trim(),onClick:kt,children:at.isPending?"Saving…":"Save pattern"})]})]}),oe&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:oe})]})]}),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:ws,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:ws,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:ws,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(wp,{errors:Mt}),c!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:Fe,children:[e.jsx(Zn,{size:14}),V?ls.refreshPreview:"Preview queries"]}),V&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Queries to run"}),e.jsxs("p",{className:"text-sm text-secondary",children:[se.length," query executions in ",Xe.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(Np,{rows:se,locations:n,onChange:(C,Ce)=>B(ve=>ve&&{...ve,rows:ve.rows.map(Ye=>Ye.id===C?{...Ye,...Ce}:Ye)})})]})]}),t.errorMessage&&e.jsxs("p",{role:"alert",className:"text-sm text-negative",children:[t.errorMessage," Your entries are preserved. Retry unchanged entries to avoid duplicate work."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!t.isEmbed&&e.jsxs(P,{size:"sm",disabled:!mt,onClick:()=>{if(mt){const C=Ve();t.onSubmit(C,JSON.stringify({projectName:s,...C}))}},children:[e.jsx(Ka,{size:14}),t.isPending?"Starting…":ls.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[c==="once"?`${Be.length} queries`:`${se.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function Hr({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:ws,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 Np({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:`${ws} 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(Hr,{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 wp({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 Sp(t){const s=new Map;for(const n of t){const a=JSON.stringify({scope:n.scope,location:n.location}),r=s.get(a)??{scope:n.scope,location:n.location,queries:[]};r.queries.push(n.query),s.set(a,r)}return[...s.values()]}function Cp({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(fe,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":"Research results",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 ${Pp(t.id)}`:ls.resultsEmpty})]}),t&&e.jsx(de,{tone:Fl(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:ls.templateProvenance}),e.jsxs("dl",{className:"mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Saved pattern"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.template})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Names used"}),e.jsx("dd",{children:Object.entries(t.template.bindings).map(([i,c])=>`${i}: ${c}`).join(" · ")||"No variables"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Original resolved text"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.output})]})]}),e.jsx("p",{className:"mt-2",children:"The queries below are the final text sent to the answer engine, including any edits."}),e.jsxs("p",{className:"mt-2 font-mono text-xs",children:[t.template.templateId," · ",t.template.templateVersion]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:ls.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:ls.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(de,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?ls.brandedQuery:i.queryClass==="non-brand"?ls.discoveryQuery:ls.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(de,{tone:Rp(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(de,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===xn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===xn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(de,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===xn.failed?"negative":"caution",children:i.citationState===null?i.status===xn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(kp,{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 kp({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})]}),!ae()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(We,{type:"button",size:"sm",onClick:()=>a({researchRunQueryId:t.id,scope:n}),children:"Review for tracking"}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Only this saved query text enters tracking review. Its answer remains research evidence."})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("div",{className:"mt-1 max-w-prose text-sm leading-6 text-secondary [&_h1]:text-base [&_h2]:text-base [&_h3]:text-sm",children:e.jsx(_m,{components:{p:({children:r})=>e.jsx("p",{className:"mb-3 whitespace-pre-wrap last:mb-0",children:r}),ul:({children:r})=>e.jsx("ul",{className:"mb-3 ml-5 list-disc space-y-1",children:r}),ol:({children:r})=>e.jsx("ol",{className:"mb-3 ml-5 list-decimal space-y-1",children:r}),pre:({children:r})=>e.jsx("pre",{className:"mb-3 overflow-x-auto whitespace-pre-wrap",children:r}),a:({children:r,href:o})=>{const i=Ts(o);return i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"text-link underline",children:r}):e.jsx("span",{children:r})},img:({alt:r})=>e.jsx("span",{children:r})},children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===xn.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r},r))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r.replace(/^www\./,"")},r))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-1",children:t.groundingSources.map((r,o)=>{const i=Ts(r.uri),c=r.title||r.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:c}):e.jsx("span",{className:"truncate text-secondary",children:c}),i&&e.jsx(Im,{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 Ap(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 Pp(t){return t.length>8?t.slice(0,8):t}function Fl(t){return t===Yn.completed?"positive":t===Yn.partial?"caution":t===Yn.failed?"negative":"neutral"}function Rp(t){return t===xn.completed?"positive":t===xn.failed?"negative":"neutral"}async function Ip(t){await Ct(t,"researchRuns")}const Wr=new Set(["queued","seeding","probing"]);function $p({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:o={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d}){const{account:u}=Ln(),[h,m]=l.useState("tracked"),[b,p]=l.useState("find"),[x,g]=l.useState(null),f=u?.role==="viewer"?md():null,N=u?.role!=="viewer"||f!==null,S=s??h,q=S==="research"&&!N?"tracked":S,R=a??b,y=E=>{s===void 0&&m(E),n?.(E)},j=E=>{a===void 0&&p(E),r?.(E)},A=(E,D)=>{const F=D===void 0?{...o}:{...o,measurementScope:D?.kind??"project",measurementScopeKey:D?.key};g({...E,trackingSelection:F}),D!==void 0&&i?.({measurementScope:F.measurementScope,measurementScopeKey:F.measurementScopeKey}),y("tracked")};return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"queries-heading",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"queries-heading",children:"Queries"})}),e.jsxs("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Query workspace",children:[e.jsx(Va,{active:q==="tracked",label:"Tracked",onClick:()=>y("tracked")}),N?e.jsx(Va,{active:q==="research",label:"Research",onClick:()=>y("research")}):null]}),e.jsx("div",{className:"mt-4",children:q==="tracked"?e.jsx(Zp,{projectName:t,selection:o,onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d,pendingTrackingSource:x,onPendingTrackingSourceHandled:()=>g(null)}):e.jsx(Tp,{projectName:t,selection:o,mode:R,onModeChange:j,onReviewSavedSource:A,onSelectionChange:i,viewerResearchConfig:f})})]})}function Va({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 Tp({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:o}){const{canWrite:i}=Ln(),c=!i||n==="test",d=$e({...tl({client:W,path:{name:t}}),enabled:c,staleTime:6e4}),u=$e({...sl({client:W,path:{name:t}}),enabled:c,staleTime:6e4}),h=l.useMemo(()=>{const p=d.data;if(!p)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const x=new Map(p.targets.map(f=>[f.stableKey,[]]));for(const f of p.groups)for(const N of f.targetKeys)x.get(N)?.push(f.stableKey);const g=new Map(p.markets.map(f=>[f.stableKey,new Set]));for(const f of p.markets)for(const N of f.usageEdges)for(const S of x.get(N.targetKey)??[])g.get(f.stableKey)?.add(S);return[{id:"project",label:"Whole site",kind:"project",targetCount:p.targets.length},...p.groups.map(f=>({id:f.stableKey,label:f.label,kind:"group",targetCount:f.targetKeys.length,...f.parentGroupKey?{parentGroupIds:[f.parentGroupKey]}:{}})),...p.markets.map(f=>{const N=[...g.get(f.stableKey)??[]];return{id:f.stableKey,label:f.label,kind:"market",targetCount:0,...N.length?{parentGroupIds:N}:{}}}),...p.targets.map(f=>({id:f.stableKey,label:f.label,kind:"property",targetCount:1,...x.get(f.stableKey)?.length?{parentGroupIds:x.get(f.stableKey)}:{}}))]},[d.data]),m=l.useMemo(()=>(u.data?.templates??[]).map(p=>({id:p.id,version:p.updatedAt,label:p.name,pattern:p.pattern,variables:p.variables})),[u.data]),b={projectName:t,scopeOptions:h,planRevision:d.data?.active?.revision??null,selectedScope:(()=>{const p=h.find(g=>g.kind===s.measurementScope&&g.id===s.measurementScopeKey),x=d.data?.active?.revision;return p&&x&&(p.kind==="market"||p.kind==="property")?{kind:p.kind,key:p.id,label:p.label,planRevision:x,expectedPlanRevision:x}:(s.measurementScope==="market"||s.measurementScope==="property")&&s.measurementScopeKey?{kind:s.measurementScope,key:s.measurementScopeKey,label:s.measurementScopeKey,planRevision:x??0,expectedPlanRevision:x??0}:null})(),scopePending:d.isPending||d.isFetching,scopeError:d.isError,onRetryScope:()=>{d.refetch()},templates: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(Va,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(Va,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(eg,{projectName:t,onReviewDiscoveryProbe:p=>r({source:"discovery",discoveryProbeId:p})}):e.jsx(lo,{...b,onReviewForTracking:({researchRunQueryId:p,scope:x})=>r({source:"research",researchRunQueryId:p},x??null)})})]}):e.jsx(lo,{...b,viewerResearchConfig:o})}function Mp({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:c,preview:d,isPreviewing:u,isCommitting:h,onPreview:m,onCommit:b}){const[p,x]=l.useState(null),[g,f]=l.useState(()=>Ea(s)),[N,S]=l.useState(null),q=l.useRef(null),R=l.useRef(null),y=Dp(t,s),j=l.useMemo(()=>Op(t.tracked,s,t.mode),[s,t.mode,t.tracked]),A=fn({rows:j,getSearchText:L=>`${L.queryText} ${L.provenance?.source??"legacy"} ${L.assignments.map(ee=>ee.queryClass??"unknown").join(" ")}`});l.useEffect(()=>{if(y)return;if(!a){R.current=null;return}const L=`${a}:${br(s)}`;if(R.current===L)return;const ee=t.tracked.find(O=>O.queryId===a);ee&&(R.current=L,x({kind:"edit",row:ee,audience:t.mode==="advanced"?fr(s):void 0,scopeLabel:yr(s,t)}),f(co(ee,s)),S(null))},[s,a,y,t]),l.useEffect(()=>{if(y||!o)return;const L=Ea(o.trackingSelection??s);x({kind:"add"}),f(o.source==="research"?{...L,source:"research",researchRunQueryId:o.researchRunQueryId}:{...L,source:"discovery",discoveryProbeId:o.discoveryProbeId}),S(null),i()},[i,o,s,y]),l.useEffect(()=>{y&&(x(null),S(null),a!==void 0&&r?.(void 0))},[r,a,y]),l.useEffect(()=>{if(!p||p.kind==="remove")return;const L=q.current;L&&(L.scrollIntoView?.({block:"start"}),L.focus({preventScroll:!0}))},[p]);function E(L="manual"){x({kind:"add"}),f({...Ea(s),source:L}),S(null),r?.(void 0)}function D(L){R.current=`${L.queryId}:${br(s)}`,x({kind:"edit",row:L,audience:t.mode==="advanced"?fr(s):void 0,scopeLabel:yr(s,t)}),f(co(L,s)),S(null),r?.(L.queryId)}function F(L){R.current=`${L.queryId}:${br(s)}`,x({kind:"remove",row:L,audience:t.mode==="advanced"?fr(s):void 0,scopeLabel:yr(s,t)}),S(null),r?.(L.queryId)}function V(){x(null),S(null),r?.(void 0)}const B=p?Lp(p,g,t.mode):null,w=p!==null&&p.kind==="add"&&t.mode==="advanced"&&!oi(g),G=B!==null&&(!w||g.contexts.length>0)&&!u;return y?e.jsx("div",{className:"query-tracking-workspace space-y-4",children:e.jsxs("section",{"aria-label":"Tracked queries",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["This saved ",s.measurementScope," filter is unavailable in the current measurement."]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>n?.({measurementScope:"project",measurementScopeKey:void 0}),children:"Show whole site"})]})}):e.jsxs("div",{className:"query-tracking-workspace space-y-4",children:[e.jsxs("section",{"aria-label":"Tracked queries",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsx(Gp,{workspace:t,selection:s,onSelectionChange:n}),t.mode==="advanced"?e.jsx(Fp,{selection:s,onSelectionChange:n}):null,e.jsx(Qs,{value:A.query,onChange:A.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!ae()&&e.jsxs(We,{type:"button",size:"sm",onClick:()=>E(),children:[e.jsx($m,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[A.totalRows.toLocaleString("en-US")," saved query ",A.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."}),A.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:A.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:A.rows.map(L=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:L.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:e.jsx(_p,{row:L,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Bp,{row:L})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:Kp(L)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(Vp,{row:L,outsidePlan:t.mode==="advanced"&&L.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!ae()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(We,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${L.queryText}`,onClick:()=>D(L),children:[e.jsx(Tm,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(We,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${L.queryText}`,onClick:()=>F(L),children:[e.jsx(ml,{"aria-hidden":"true",size:13})," Remove"]})]})})]},L.queryId))})]})}),e.jsx(qs,{page:A.page,pageSize:A.pageSize,visibleRows:A.rows.length,totalRows:A.totalRows,itemLabel:"queries",onPageChange:A.setPage})]}),p&&!ae()&&e.jsx(zp,{workspace:t,templates:c,action:p,draft:g,onDraftChange:L=>{f(L),S(null)},onClose:V,canReview:G,isPreviewing:u,editorHeadingRef:q,onReview:()=>{B&&(S(B),m(B))}}),d&&N&&p&&e.jsx(Yp,{preview:d,workspace:t,isCommitting:h,onConfirm:()=>{b({...N,expectedWorkspaceVersion:d.workspaceVersion,previewToken:d.previewToken,reviewedAt:d.reviewedAt})}})]})}function Ea(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 co(t,s){return{...Ea(s),text:t.queryText,queryClass:"keep"}}function Lp(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=qp(s);if(!a||Yr(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=Ep(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!oi(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function qp(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 Ep(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 oi(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function Yr(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function fr(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 Dp(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 yr(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 li(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 Op(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=>li(r,s)))}function Fp({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 br(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function Gp({workspace:t,selection:s,onSelectionChange:n}){const a=l.useMemo(()=>{const o=new Map(t.targets.map(i=>[i.stableKey,[]]));for(const i of t.groups)for(const c of i.targetKeys)o.get(c)?.push(i.stableKey);return[{id:"project",label:"Whole site",kind:"project",targetCount:t.targets.length},...t.groups.map(i=>({id:i.stableKey,label:i.label,kind:"group",targetCount:i.targetKeys.length,...i.parentGroupKey?{parentGroupIds:[i.parentGroupKey]}:{}})),...t.markets.map(i=>({id:i.stableKey,label:i.label,kind:"market",targetCount:0})),...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(Tl,{options:a,selected:r,onSelect:o=>{n?.({measurementScope:o.kind,measurementScopeKey:o.kind==="project"?void 0:o.id})}})}function Kp(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 Gl(t,s,n){const a=new Map(s.targets.map(g=>[g.stableKey,g.label])),r=new Map(s.groups.map(g=>[g.stableKey,g.label])),o=new Map(s.markets.map(g=>[g.stableKey,g.label])),i=new Set(t.assignments.map(g=>g.targetKey));if(i.size===0)return"Whole site";const c=n?t.assignments.filter(g=>li(g,n)):t.assignments,d=new Set(c.map(g=>g.targetKey));if(n?.measurementScope==="group"){const g=d.size,f=Math.max(0,i.size-g);return[`${g} ${g===1?"property":"properties"} in this group`,...f?[`Shared with ${f} other ${f===1?"property":"properties"}`]:[]].join(" · ")}const u=new Set,h=new Set;for(const g of c)g.groupKeys.forEach(f=>u.add(f)),g.marketKeys.forEach(f=>h.add(f));const b=n?.measurementScope==="property"&&i.has(n.measurementScopeKey??"")?i.size===1?["This property only"]:["This property",`Shared with ${i.size-1} other ${i.size===2?"property":"properties"}`]:d.size===1?[a.get([...d][0])??[...d][0]]:[`${d.size} properties`],p=u.size===1?r.get([...u][0])??[...u][0]:null,x=h.size===1?o.get([...h][0])??[...h][0]:null;return p&&x&&p===x?b.push(`${p} (group and market)`):(p?b.push(`Group: ${p}`):u.size>1&&b.push(`${u.size} groups`),x?b.push(`Market: ${x}`):h.size>1&&b.push(`${h.size} markets`)),b.join(" · ")}function _p({row:t,workspace:s,selection:n}){const a=Up(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:Gl(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 Up(t,s,n){const a=new Map(s.targets.map(d=>[d.stableKey,d.label])),r=new Map(s.groups.map(d=>[d.stableKey,d.label])),o=new Map(s.markets.map(d=>[d.stableKey,d.label])),c=t.assignments.filter(d=>li(d,n)).map(d=>{const u=a.get(d.targetKey)??d.targetKey??"Whole site",h=n.measurementScope==="group"&&n.measurementScopeKey?d.groupKeys.filter(b=>b===n.measurementScopeKey).map(b=>r.get(b)??b):d.groupKeys.map(b=>r.get(b)??b),m=n.measurementScope==="market"&&n.measurementScopeKey?d.marketKeys.filter(b=>b===n.measurementScopeKey).map(b=>o.get(b)??b):d.marketKeys.map(b=>o.get(b)??b);return[u,h.length?`Groups: ${h.join(", ")}`:null,m.length?`Markets: ${m.join(", ")}`:null].filter(b=>b!==null).join(" · ")});return[...new Set(c)].length?[...new Set(c)]:["Whole site"]}function Bp({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(de,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function Vp({row:t,outsidePlan:s=!1}){return s?e.jsx(de,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(de,{tone:"positive",children:"Measured"}):e.jsx(de,{tone:"caution",children:"Awaiting sweep"})}function zp({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:o,canReview:i,isPreviewing:c,editorHeadingRef:d,onReview:u}){const h=s.length>0;return n.kind==="remove"?e.jsxs(fe,{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(vr,{canReview:i,isPreviewing:c,onCancel:o,onReview:u})]}):n.kind==="edit"?e.jsxs(fe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Edit query"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:o,children:"Cancel"})]}),e.jsxs("p",{className:"mt-3 text-sm leading-6 text-secondary",children:[n.audience?`Changes apply only to assignments in ${n.scopeLabel}.`:"Changes apply to every assignment of this query."," Earlier results stay unchanged."]}),e.jsxs("div",{className:"mt-4 max-w-2xl space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Query text"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.text,onChange: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(vr,{canReview:i,isPreviewing:c,onCancel:o,onReview:u})]}):e.jsxs(fe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Add query"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:o,children:"Cancel"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-[minmax(250px,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[a.source==="manual"?e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Question"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",placeholder:"e.g. How do teams compare AEO platforms?",value:a.text,onChange:m=>r({...a,text:m.target.value})})]}):null,a.source==="template"?e.jsx(Qp,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(uo,{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(uo,{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":h?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"}),h?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)":""]})]})]}),h?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(Wp,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!oi(a)?e.jsx("div",{className:"mt-4",children:e.jsx(Hp,{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(vr,{canReview:i,isPreviewing:c,onCancel:o,onReview:u})]})}function Qp({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":Yr(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]}),Yr(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 uo({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 ci(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function Qn(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 Kl(t){return[...new Map(t.map(s=>[Qn(s),s])).values()]}function di(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 Hp({workspace:t,draft:s,onDraftChange:n}){const a=l.useMemo(()=>Kl([...t.defaultContexts.map(ci),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?Qn(s.contexts[0]):s.contexts.length>1?"__existing__":"";return e.jsxs("label",{className:"block",htmlFor:"tracking-query-context",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location and engines"}),e.jsxs("select",{id:"tracking-query-context","aria-label":"Location and engines",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:r,onChange:o=>{const i=a.find(d=>Qn(d)===o.target.value),c=o.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:c})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(o=>e.jsx("option",{value:Qn(o),children:di(o)},Qn(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 Wp({workspace:t,draft:s,onDraftChange:n}){const[a,r]=l.useState(""),[o,i]=l.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),c=l.useMemo(()=>[...t.targets.map(p=>({kind:"target",key:p.stableKey,label:p.label,detail:"Property"})),...t.groups.map(p=>({kind:"group",key:p.stableKey,label:p.label,detail:"Group"})),...t.markets.map(p=>({kind:"market",key:p.stableKey,label:p.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),d=a.trim().toLocaleLowerCase(),u=d?c.filter(p=>`${p.label} ${p.detail}`.toLocaleLowerCase().includes(d)):c,h=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function m(p,x,g){const f=p==="target"?"targetKeys":p==="group"?"groupKeys":"marketKeys",N=s[f];n({...s,wholeSite:!1,[f]:g?[...N,x]:N.filter(S=>S!==x)})}function b(p,x){return(p==="target"?s.targetKeys:p==="group"?s.groupKeys:s.marketKeys).includes(x)}if(!o){const p=t.targets.find(x=>x.stableKey===s.targetKeys[0]);return e.jsxs("fieldset",{className:"self-start rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-sm text-strong",children:["Property: ",p?.label??s.targetKeys[0]]}),e.jsx(P,{type:"button",variant:"ghost",size:"sm","aria-label":"Change tracking destination",onClick:()=>i(!0),children:"Change"})]})]})}return e.jsxs("fieldset",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Choose where this question should be tracked."}),e.jsxs("label",{className:"mt-3 flex min-h-9 items-center gap-2 rounded px-1 text-sm text-strong",children:[e.jsx("input",{type:"checkbox",checked:s.wholeSite,onChange:p=>{n({...s,wholeSite:p.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),"Whole site"]}),!s.wholeSite&&!h?e.jsx("p",{role:"status",className:"mt-2 text-sm text-caution",children:"Choose Whole site or at least one property, group, or market."}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:"Group: properties grouped together. Market: search context."}),e.jsx(Qs,{value:a,onChange:r,label:"Filter assignments",placeholder:"Search Properties, Groups, Markets",className:"mt-3"}),e.jsx("div",{className:"mt-3 max-h-64 space-y-1 overflow-y-auto pr-1",children:u.length===0?e.jsx("p",{className:"px-1 py-2 text-sm text-muted",children:"No assignment matches that search."}):u.map(p=>e.jsxs("label",{className:"flex min-h-9 items-center gap-2 rounded px-1 py-1 text-sm text-strong hover:bg-surface-hover",children:[e.jsx("input",{type:"checkbox","aria-label":`${p.label}, ${p.detail}`,checked:b(p.kind,p.key),onChange:x=>m(p.kind,p.key,x.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:p.label}),e.jsx("span",{className:"text-xs text-muted",children:p.detail})]},`${p.kind}:${p.key}`))})]})}function vr({canReview:t,isPreviewing:s,onCancel:n,onReview:a}){return e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[e.jsx(We,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),e.jsx("p",{className:"text-sm leading-5 text-secondary",children:"Publishing does not run a sweep."})]})}function Yp({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=l.useRef(null);l.useEffect(()=>{const c=r.current;c&&(typeof c.scrollIntoView=="function"&&c.scrollIntoView({block:"start"}),c.focus({preventScroll:!0}))},[t]);const o=!t.diff.noOp,i=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(c=>c.rows.length>0);return e.jsxs(fe,{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(de,{tone:o?"caution":"neutral",children:o?"Ready to confirm":"No-op"})]}),i.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:i.map(c=>e.jsx(mo,{label:c.label,rows:c.rows,workspace:s,tracked:t.tracked},c.label))}):null,t.diff.unchanged.length>0?e.jsxs("details",{className:"mt-4 border-t border-default pt-2 text-sm text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3",children:[t.diff.unchanged.length," unchanged ",t.diff.unchanged.length===1?"query":"queries"]}),e.jsx(mo,{label:"Unchanged",rows:t.diff.unchanged,workspace:s,tracked:t.tracked})]}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Next sweep workload"}),e.jsxs("p",{className:"leading-6",children:["Next sweep: ",t.workload.nextSweepProviderCalls," provider requests (+",t.workload.addedProviderCalls,", −",t.workload.removedProviderCalls,")."]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:e.jsx(We,{type:"button",size:"sm",disabled:!o||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function mo({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`:Xp(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(Jp,{row:a.find(o=>o.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function Jp({row:t,workspace:s}){if(!t?.assignments.length)return null;const n=new Set(t.assignments.map(a=>a.targetKey)).size;return e.jsxs("details",{className:"mt-2 text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:["Classifications · ",n," ",n===1?"property":"properties"]}),e.jsx("ul",{className:"mt-1 max-h-40 space-y-1 overflow-y-auto",children:t.assignments.map((a,r)=>{const o=s.targets.find(d=>d.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",c=a.contexts.map(d=>di(ci(d))).join("; ");return e.jsx("li",{children:[o,i,c].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function Xp(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=Kl(a.assignments.flatMap(i=>i.contexts).map(ci)),o=r.length===1?di(r[0]):r.length>1?`${r.length} contexts`:null;return[Gl(a,n),o].filter(i=>i!==null).join(" · ")}function Zp({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i}){const c=ms(),[d,u]=l.useState(null),h=$e({...tl({client:W,path:{name:t}})}),m=$e({...sl({client:W,path:{name:t}}),staleTime:6e4}),b=Pt({...xd(),onSuccess:x=>u(x),onError:async x=>{u(null),await c.invalidateQueries({queryKey:hd({client:W,path:{name:t}})}),Te({title:"Could not review tracking changes",detail:x instanceof Error?x.message:"Update the draft and review it again.",tone:"negative"})}}),p=Pt({...pd(),onSuccess:async x=>{u(null),r?.(void 0),await Si(c,t),Te({title:x.committed?"Tracked queries updated":"No tracked-query change",detail:x.active?`Measurement revision ${x.active.revision}.`:"No measurement revision is published yet.",tone:x.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async x=>{u(null),await Si(c,t),Te({title:"Could not confirm tracking changes",detail:x instanceof Error?x.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return h.isLoading?e.jsx(fe,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):h.isError||!h.data?e.jsxs(fe,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{h.refetch()},children:"Try again"})]}):e.jsx(Mp,{workspace:h.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:m.data?.templates??[],preview:d,isPreviewing:b.isPending,isCommitting:p.isPending,onPreview:x=>{u(null),b.mutate({client:W,path:{name:t},body:{...x,expectedWorkspaceVersion:h.data.workspaceVersion}})},onCommit:x=>p.mutate({client:W,path:{name:t},body:x})})}function eg({projectName:t,onReviewDiscoveryProbe:s}){const n=ms(),[a,r]=l.useState(null),[o,i]=l.useState(""),[c,d]=l.useState("100"),u=$e({...gd({client:W,path:{name:t},query:{limit:"10"}}),refetchInterval:S=>S.state.data?.some(R=>Wr.has(R.status))?3e3:!1}),h=u.data??[];l.useEffect(()=>{!a&&h[0]&&r(h[0].id)},[a,h]);const m=h.find(S=>S.id===a)??null,b=$e({...fd({client:W,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:m&&Wr.has(m.status)?3e3:!1}),p=b.data??null,x=Pt({mutationFn:()=>{const S={},q=o.trim();q&&(S.icpDescription=q);const R=Number.parseInt(c,10);return Number.isFinite(R)&&R>0&&(S.maxProbes=R),yd(t,S)},onSuccess:async S=>{r(S.sessionId),i(""),await ag(n,t,S.sessionId),Te({title:"Discovery started",detail:`Run ${jr(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"})}}),g=p??m,f=l.useMemo(()=>(p?.probes??[]).slice(0,30),[p?.probes]);async function N(){try{const S=await u.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:ae()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:u.isFetching,onClick:()=>{N()},children:[e.jsx(Zn,{className:`size-3.5 ${u.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(fe,{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(de,{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:c,onChange:S=>d(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."})]}),!ae()&&e.jsxs(We,{type:"button",size:"sm",disabled:x.isPending,onClick:()=>x.mutate(),children:[e.jsx(Ka,{size:14}),x.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(fe,{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"})]}),u.isFetching&&e.jsx(de,{tone:"neutral",children:"Loading"})]}),h.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:h.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:jr(S.id)}),e.jsx(de,{tone:ho(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(fe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:g?jr(g.id):"No run selected"})]}),g&&e.jsx(de,{tone:ho(g.status),children:g.status})]}),g?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ca,{label:"Questions tested",value:g.probeCount??0}),e.jsx(Ca,{label:"Cited queries",value:g.citedCount??0,tone:"positive"}),e.jsx(Ca,{label:"Worth tracking",value:g.aspirationalCount??0,tone:"caution"}),e.jsx(Ca,{label:"Skip",value:g.wastedCount??0,tone:"negative"})]}),g.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:g.error}),g.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:g.warning}),g.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:g.icpDescription})]}),g.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:g.competitorMap.slice(0,8).map(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."})]}),g?.status==="completed"&&e.jsxs(fe,{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(fe,{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(de,{tone:"neutral",children:"Loading"})]}),f.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Tracking review"})})]})}),e.jsx("tbody",{children:f.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.query}),e.jsx("td",{children:e.jsx(de,{tone:tg(S.bucket),children:ng(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:!ae()&&s&&(S.bucket==="cited"||S.bucket==="aspirational")&&e.jsx(We,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(S.id),children:"Review for tracking"})})]},S.id))})]})})]})]})]})]})}function Ca({label:t,value:s,tone:n="neutral"}){const a=n==="positive"?"text-positive":n==="caution"?"text-caution":n==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s})]})}function ho(t){return t==="completed"?"positive":t==="failed"?"negative":Wr.has(t)?"caution":"neutral"}function tg(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const sg={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function ng(t){return t?sg[t]:"Not classified"}function jr(t){return t.length>8?t.slice(0,8):t}async function ag(t,s,n){await Promise.all([Ct(t,"discovery"),t.invalidateQueries({queryKey:bd({client:W})})])}function xo(t){return`${(t*100).toFixed(1)}%`}function rg({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),c=$e({...vd({client:W,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=$e({...jd({client:W,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),u=(d.data??[]).filter(f=>(f.status==="completed"||f.status==="partial")&&f.trigger!=="probe").reverse(),h=o??u[0]?.id??"",m=a??u.find(f=>f.id!==h)?.id??"",b=!!(m&&h&&m!==h),p=$e({...Nd({client:W,path:{name:t},query:{run1:m,run2:h}}),enabled:s==="compare"&&b}),x=c.data??[],g=p.data?.diff.filter(f=>f.changed||f.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([f,N])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===f,className:`filter-chip ${s===f?"filter-chip-active":""}`,onClick:()=>n(f),children:N},f))}),s==="changes"?e.jsx(Um,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),c.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!c.isLoading&&x.length===0?e.jsxs(fe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:Ut()?Js:"Complete an answer visibility sweep to create the first snapshot."})]}):null,x.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:x.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(f.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.mentionedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:xo(f.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.citedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:xo(f.overallCitedRate)})]},f.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:m,onChange:f=>r(f.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:u.map(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:h,onChange:f=>i(f.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:u.map(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]})]}),d.isLoading||p.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!d.isLoading&&u.length<2?e.jsxs(fe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:Ut()?Js:"Run another answer visibility sweep before comparing historical evidence."})]}):null,p.data&&g.length===0?e.jsxs(fe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,g.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:g.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:f.query??"Archived query"}),e.jsx("td",{children:e.jsxs(de,{tone:f.changed?"caution":"neutral",children:[f.run1State??"none"," → ",f.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(de,{tone:f.visibilityChanged?"caution":"neutral",children:[f.run1MentionState??"none"," → ",f.run2MentionState??"none"]})})]},f.queryId??f.query??"unknown"))})]})}):null]}):null]})}const po={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},ig={contract:null,assessment:null,googleAds:po,gtm:po,snapshots:[]};function og(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":ug(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function lg(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 cg(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 dg(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 _l(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"&&mg(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 ug(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function mg(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Ul(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 hg(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 xg(t,s){return t==="configured"?s==="not-configured"?"Not declared":s==="contract-selection-required"?"Choose conversion":"Declared":t==="static"?s==="assessment-unavailable"?"Unavailable":s==="assessment-loading"?"Checking":s==="static-mismatch"?"Mismatch":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"Consistent":s==="configured"?"Needs review":"Not checked":s==="observed"?"Observed":s==="runtime-unverified"?"Not observed":"Not checked"}function on(t){return t.length<=12?t:`…${t.slice(-10)}`}function pg(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 gg(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 Nr={"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 go(t){return t.outcome==="pass"?{label:Nr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Nr[t.code],tone:"negative",outcome:"Fail"}:{label:Nr[t.code],tone:"caution",outcome:"Unknown"}}function fg(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function yg(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 bg(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function fo({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=Ul(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(de,{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 ${Qt(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const vg="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.",jg="Available once Google Ads and Tag Manager are connected.",Ng="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 wg({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:o}){const i=t.googleAds.state==="connected",c=t.gtm.state==="connected",d=t.googleAds.state==="unavailable",u=t.gtm.state==="unavailable",h=d||u||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&&!c,p=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:d?m:cg(t)},{title:"Tag Manager",state:t.gtm.state,ready:c,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:u?m:dg(t)}],x=i&&c&&!h?_l(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(_e,{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:Ng}):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(_e,{text:vg})]}),x&&s?e.jsx(We,{type:"button",disabled:r,onClick:()=>s(x.id),children:r?"Working…":x.label}):e.jsx("p",{className:"text-sm text-secondary",children:jg})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:p.map(g=>{const f=g.ready?{label:"Ready",tone:"positive"}:Ul(g.state),N=g.action;return e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-heading",children:g.title}),e.jsx(de,{tone:f.tone,children:f.label}),g.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:g.summary}):null,N&&s?N.id==="retry-connection-status"?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(N.id),children:r?"Working…":N.label}):e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(N.id),children:r?"Working…":N.label}):null,g.summary&&g.onChange?e.jsx(We,{type:"button",variant:"ghost",size:"sm","aria-label":g.changeLabel,disabled:r,onClick:g.onChange,children:"Change"}):null]},g.title)})}),o?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:o}):null]})]})}function Sg({workspace:t=ig,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:o=null,onSelectContract:i,contractError:c=null,onRetryContracts:d,onRetryEvidence:u,onChangeGoogleAdsSelection:h,onChangeGtmSelection:m,onAddContract:b}){const p=og(t),x=lg(p),g=_l(t),f=t.assessment?.findings??[],N=f.filter(y=>y.outcome!=="pass"),S=f.filter(y=>y.outcome==="pass"),q=N.some(y=>y.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&c===null?e.jsx(wg,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:h,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(de,{tone:x.tone,children:x.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Qt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:x.detail}),t.assessmentEvidenceSnapshots?.length?e.jsxs("details",{className:"inline-disclosure mt-3 max-w-2xl",children:[e.jsx("summary",{children:"Evidence used for this assessment"}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm leading-6 text-secondary",children:t.assessmentEvidenceSnapshots.map(y=>e.jsxs("li",{className:"break-words",children:[bg(y)," ",y.kind,", captured ",Qt(y.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",y.id,")"]})]},y.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?g.id==="review-findings"||g.id==="review-runtime-verification"||g.id==="retry-connection-status"||g.id==="select-contract"||g.id==="retry-integrity"||g.id==="waiting-for-integrity"?e.jsx(P,{type:"button",disabled:n||g.id==="waiting-for-integrity",onClick:()=>s(g.id),children:n?"Working…":g.label}):e.jsx(We,{type:"button",disabled:n,onClick:()=>s(g.id),children:n?"Working…":g.label}):g.id==="review-findings"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):p==="runtime-unverified"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:g.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),r.length>0&&b?e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:b,children:"Add conversion"}):null]}),r.length>1?e.jsxs("label",{htmlFor:"conversion-integrity-contract-select",className:"mb-5 block max-w-xl text-sm font-medium text-secondary",children:["Conversion to inspect",e.jsxs("select",{id:"conversion-integrity-contract-select",className:"mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",value:o??"",onChange:y=>i?.(y.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(y=>e.jsx("option",{value:y.id,children:y.name},y.id))]})]}):null,t.contract?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Website event"}),e.jsx("dd",{className:"mt-1 text-sm font-medium text-heading",children:t.contract.eventName})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Google Ads goal"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:pg(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:gg(t.contract)})]})]}),e.jsxs("details",{className:"inline-disclosure mt-5",children:[e.jsx("summary",{children:"Show declared identifiers"}),e.jsxs("dl",{className:"mt-3 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads customer"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:on(t.contract.googleAds.customerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads conversion action"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:on(t.contract.googleAds.conversionActionId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager container"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:on(t.contract.gtm.containerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager tag"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:on(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),c?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:c}),d?e.jsx(P,{type:"button",variant:"outline",onClick:d,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),N.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(de,{tone:q,children:[N.length," ",N.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:N.map(y=>{const j=go(y);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:j.label}),e.jsx(de,{tone:j.tone,children:j.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",y.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",y.code]}),y.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",y.evidenceIds.join(", ")]}):null]},`${y.code}:${y.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(_e,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(y=>{const j=hg(y.key,p);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${j==="positive"?"bg-positive-fill":j==="caution"?"bg-caution-fill":j==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:y.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:y.detail}),e.jsx(de,{tone:j,children:xg(y.key,p)})]},y.key)})})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-connections-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection evidence"}),e.jsx("h3",{id:"conversion-integrity-connections-title",className:"text-base font-semibold text-heading",children:"Google Ads and Tag Manager"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads and Tag Manager connection and stored evidence state"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Connection"}),e.jsx("th",{scope:"col",children:"Selection"}),e.jsx("th",{scope:"col",children:"Stored evidence"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsxs("tbody",{children:[fo({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:h}:{},actionPending:n}),fo({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)&&u?e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:u,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:y.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:y.kind}),e.jsx("td",{className:"text-secondary",children:Qt(y.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:on(y.id)})]},y.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(y=>{const j=go(y);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:j.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",y.code]}),y.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",y.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(de,{tone:j.tone,children:j.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:y.subject})]},`${y.code}:${y.subject}`)})})]})})]}):null,p==="runtime-unverified"?e.jsxs("section",{id:"conversion-integrity-runtime-guidance",className:"page-section-divider","aria-labelledby":"conversion-integrity-runtime-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Runtime verification"}),e.jsx("h3",{id:"conversion-integrity-runtime-title",className:"text-base font-semibold text-heading",children:"Runtime verification checklist"})]})}),e.jsxs("ol",{className:"max-w-2xl list-decimal space-y-2 pl-5 text-sm leading-6 text-secondary marker:text-muted",children:[e.jsxs("li",{children:["Use a controlled browser session on ",fg(t.contract)," and complete the conversion that emits ",e.jsx("span",{className:"font-mono text-heading",children:t.contract.eventName}),"."]}),e.jsxs("li",{children:["In Tag Manager preview or debugging, confirm tag ",e.jsx("span",{className:"font-mono text-heading",children:on(t.contract.gtm.tagId)})," fires with ",yg(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:on(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const ln=3e4,yo={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},$t="mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",os="text-sm font-medium text-secondary";function bo(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:ft(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function ka(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function Cg(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 kg(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Ag(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:kg(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 Pg(t,s,n){return{name:t.name.trim(),eventName:t.eventName.trim(),googleAds:{customerId:s,conversionActionId:t.conversionActionId.trim(),...t.conversionId.trim()?{conversionId:t.conversionId.trim()}:{},...t.conversionLabel.trim()?{conversionLabel:t.conversionLabel.trim()}:{},campaignIds:ka(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:ka(t.triggerIds),variableIds:ka(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:ka(t.productionHosts)}}}function vo(t,s){const n=window.open(t,"_blank","width=600,height=700");if(!n){window.location.assign(t);return}const a=window.setInterval(()=>{n.closed&&(window.clearInterval(a),s())},1e3)}function Aa(t,s,n){if(!s)return null;const a=s.totalAccessible===1?t:`${t}s`;return s.truncated?`Incomplete result: showing ${n} of ${s.totalAccessible} accessible ${a}. Use the CLI or API if the resource is not shown.`:`${s.totalAccessible} accessible ${a} found.`}function Pa(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Ra({id:t,label:s,value:n,onChange:a,children:r,disabled:o=!1}){return e.jsxs("label",{htmlFor:t,className:os,children:[s,e.jsx("select",{id:t,className:$t,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 jo({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(null),u=l.useRef(null),h=l.useRef(null),m=l.useRef(!1);l.useEffect(()=>{const g=m.current;m.current=a,a?h.current?.focus():g&&u.current?.querySelector("button")?.focus()},[a]);function b(){d(null),r(!0)}function p(){d(null),r(!1)}async function x(){i(!0),d(null);try{await n()}catch(g){d(ft(g)),i(!1)}}return e.jsx("div",{ref:u,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(P,{ref:h,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:o,onClick:p,children:"Keep connected"}),e.jsx(We,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||o,onClick:()=>{x()},children:o?"Disconnecting…":`Disconnect ${t}`})]}),c?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:c}):null]}):e.jsxs(We,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:b,children:["Disconnect ",t]})})}function No({id:t,label:s,options:n,synced:a,loading:r,failed:o,onRetry:i,emptyHint:c,value:d,onChange:u}){const h=n.some(g=>g.id===d),[m,b]=l.useState(!1),p=m||d!==""&&!h&&n.length>0,x=e.jsx("label",{htmlFor:t,className:os,children:s});return r?e.jsxs("div",{children:[x,e.jsx("select",{id:t,className:$t,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):o?e.jsxs("div",{children:[x,e.jsx("input",{id:t,required:!0,className:$t,value:d,onChange:g=>u(g.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:i,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[x,e.jsx("input",{id:t,required:!0,className:$t,value:d,onChange:g=>u(g.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":c})]}):e.jsxs("div",{children:[x,p?e.jsx("input",{id:t,required:!0,className:$t,value:d,onChange:g=>u(g.target.value)}):e.jsxs("select",{id:t,required:!0,className:$t,value:d,onChange:g=>u(g.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(g=>e.jsxs("option",{value:g.id,children:[g.name,g.detail?` (${g.detail})`:"",g.active?"":" — inactive"]},g.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{b(!p),u("")},children:p?"Choose from synced list":"Enter an ID manually"})]})}function Rg({projectId:t,projectName:s}){const n=Ln(),[a,r]=l.useState(null),[o,i]=l.useState(null),[c,d]=l.useState(!1),[u,h]=l.useState(""),[m,b]=l.useState(null),[p,x]=l.useState(!1),[g,f]=l.useState(!1),[N,S]=l.useState(""),[q,R]=l.useState(""),[y,j]=l.useState(""),[A,E]=l.useState(""),[D,F]=l.useState(""),[V,B]=l.useState(!1),[w,G]=l.useState(yo),[L,ee]=l.useState(null),O=l.useRef(null),X=$e({...wd({client:W,path:{name:s}}),staleTime:ln}),oe=$e({...Sd({client:W,path:{name:s}}),staleTime:ln}),k=$e({...Cd({client:W,path:{name:s}}),staleTime:ln}),I=$e({...kd({client:W,path:{name:s}}),staleTime:ln}),$=I.data,te=$e({...Ad({client:W,path:{name:s},query:{limit:5}}),staleTime:ln}),le=$e({...Pd({client:W,path:{name:s},query:{limit:5}}),staleTime:ln}),pe=k.data??[],Ne=(L?pe.find(T=>T.id===L)??null:null)??(pe.length===1?pe[0]??null:null),Y=pe.length>1&&!Ne,z=$e({...Rd({client:W,path:{name:s,contractId:Ne?.id??""}}),enabled:!!Ne,staleTime:ln}),ne=$e({...Id({client:W,path:{name:s}}),enabled:m==="google-ads"&&X.data?.connected===!0,staleTime:0}),Z=$e({...$d({client:W,path:{name:s}}),enabled:m==="gtm"&&oe.data?.connected===!0,staleTime:0}),be=$e({...Td({client:W,path:{name:s,accountId:y}}),enabled:m==="gtm"&&!!y,staleTime:0}),ce=$e({...Md({client:W,path:{name:s,accountId:y,containerId:A}}),enabled:m==="gtm"&&!!y&&!!A,staleTime:0}),De=Pt(Ld({client:W})),we=Pt(qd({client:W})),Se=Pt(Ed({client:W})),Je=Pt(Dd({client:W})),Ue=Pt(Od({client:W})),Be=Pt(Fd({client:W})),ze=Pt(Gd({client:W})),Oe=Pt(Kd({client:W})),_=Pt(_d({client:W}));l.useEffect(()=>{if(m!=="google-ads"||p||!X.isSuccess)return;const T=X.data.connection?.selection;S(T?.customerId??""),R(T?.loginCustomerId??""),x(!0)},[p,X.data,X.isSuccess,m]),l.useEffect(()=>{if(m!=="gtm"||g||!oe.isSuccess)return;const T=oe.data.selection;j(T?.accountId??""),E(T?.containerId??""),F(T?.workspaceId??""),f(!0)},[g,oe.data,oe.isSuccess,m]),l.useEffect(()=>{!L||!k.data||k.data.some(T=>T.id===L)||ee(null)},[k.data,L]);const U=l.useMemo(()=>{const T=te.data?.snapshots??[],xe=le.data?.snapshots??[],dt=[...T.map(Ft=>({id:Ft.id,provider:"google-ads",kind:Ft.kind,capturedAt:Ft.capturedAt})),...xe.map(Ft=>({id:Ft.id,provider:"gtm",kind:Ft.kind,capturedAt:Ft.capturedAt}))].sort((Ft,Jt)=>Jt.capturedAt.localeCompare(Ft.capturedAt)).slice(0,5),Me=[],bt=z.data?.googleAdsSnapshot,vs=z.data?.gtmSnapshot;return bt&&Me.push({id:bt.id,provider:"google-ads",kind:bt.kind,capturedAt:bt.capturedAt}),vs&&Me.push({id:vs.id,provider:"gtm",kind:vs.kind,capturedAt:vs.capturedAt}),{contract:z.data?.assessment.contract??Ne,assessment:z.data?.assessment??null,contractSelectionRequired:Y,assessmentState:Ne?z.isError?"unavailable":z.isLoading?"loading":void 0:void 0,assessmentError:z.isError?ft(z.error):null,googleAds:Cg(X.data,bo(te.data?.total??0,te.isLoading,te.isError,te.error),X.isError),gtm:Ag(oe.data,bo(le.data?.total??0,le.isLoading,le.isError,le.error),oe.isError),snapshots:dt,assessmentEvidenceSnapshots:Me}},[Ne,Y,te.data,te.error,te.isError,te.isLoading,X.data,X.isError,le.data,le.error,le.isError,le.isLoading,oe.data,oe.isError,z.data,z.error,z.isError,z.isLoading]),H=l.useSyncExternalStore(Zo,Da,Da),Ie=Object.values(H.runs).some(T=>T.projectId===t&&(T.kind===Ys["google-ads-sync"]||T.kind===Ys["gtm-sync"])),Ge=De.isPending||we.isPending||Se.isPending||Je.isPending||Ue.isPending||Be.isPending||ze.isPending||Oe.isPending||_.isPending||Ie;async function se(){await Promise.all([X.refetch(),oe.refetch(),k.refetch(),te.refetch(),le.refetch(),I.refetch(),Ne?z.refetch():Promise.resolve()])}async function Xe(T){await se();for(let xe=0;xe<10&&!T();xe+=1)await new Promise(dt=>setTimeout(dt,1500)),await se()}function ut(){const T=document.activeElement;O.current=T instanceof HTMLElement?T:null}function mt(T){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(T);return}globalThis.setTimeout(T,0)}function Ve(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Fe(T){if(!T)return;!T.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!T.hasAttribute("tabindex")&&(T.tabIndex=-1),T.focus({preventScroll:!0})}function ht(T,xe=T){const dt=document.getElementById(T);dt instanceof HTMLDetailsElement&&(dt.open=!0);const Me=dt?.scrollIntoView;typeof Me=="function"&&Me.call(dt,{behavior:Ve()?"auto":"smooth",block:"start"}),Fe(document.getElementById(xe)??dt)}function Ze(T,xe){ut(),mt(()=>ht(T,xe))}function Ae(){const T=O.current;O.current=null,T&&mt(()=>{T.isConnected&&T.focus({preventScroll:!0})})}function at(){r(null),d(!1),Ae()}function kt(){r(null),b(null),Ae()}function Mt(){r(null),B(!1),Ae()}function Ee(){r(null),b(null),d(!0),Ze("google-ads-connect-panel","google-ads-connect-title")}function C(){r(null),S(""),R(""),x(!1),b("google-ads"),d(!1),Ze("google-ads-selection-panel","google-ads-selection-title")}function Ce(){r(null),j(""),E(""),F(""),f(!1),b("gtm"),d(!1),Ze("gtm-selection-panel","gtm-selection-title")}function ve(){r(null),B(!0),Ze("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Ye(T,xe){Xo({id:T.id,projectId:T.projectId,kind:T.kind,projectLabel:s,sourceAction:xe}),Te({title:xe==="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:${T.id}`,dedupeMode:"replace"})}async function yt(){js(n),r(null);try{const T=await De.mutateAsync({path:{name:s},body:{provider:"google-ads",...u.trim()?{developerToken:u.trim()}:{}}});h(""),d(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),vo(T.authorizationUrl,()=>{se(),i(null),Ae()})}catch(T){r(ft(T))}}async function tt(){js(n),r(null);try{const T=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."),vo(T.authorizationUrl,()=>{se(),i(null),Ae()})}catch(T){r(ft(T))}}async function Lt(){if(js(n),!N){r("Select a Google Ads customer before saving.");return}r(null);try{await Se.mutateAsync({path:{name:s},body:{customerId:N,...q.trim()?{loginCustomerId:q.trim()}:{}}}),b(null),Ae(),await Xe(()=>X.data?.selectedCustomer!=null)}catch(T){r(ft(T))}}async function Qe(){if(js(n),!y||!A){r("Select a Tag Manager account and container before saving.");return}r(null);try{await Je.mutateAsync({path:{name:s},body:{accountId:y,containerId:A,...D?{workspaceId:D}:{}}}),b(null),Ae(),await Xe(()=>oe.data?.status==="connected")}catch(T){r(ft(T))}}async function J(){js(n),r(null),await ze.mutateAsync({path:{name:s}}),b(null),d(!1),S(""),R(""),x(!1),i(null),await se(),Te({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),O.current=null,mt(()=>Fe(document.getElementById("conversion-integrity-title")))}async function qe(){js(n),r(null),await Oe.mutateAsync({path:{name:s}}),b(null),j(""),E(""),F(""),f(!1),i(null),await se(),Te({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),O.current=null,mt(()=>Fe(document.getElementById("conversion-integrity-title")))}async function Pe(){js(n),r(null);try{const T=await Ue.mutateAsync({path:{name:s}});Ye(T,"google-ads-sync")}catch(T){r(ft(T))}}async function Re(){js(n),r(null);try{const T=await Be.mutateAsync({path:{name:s}});Ye(T,"gtm-sync")}catch(T){r(ft(T))}}async function Ht(){js(n),r(null);try{const T=await Promise.allSettled([Ue.mutateAsync({path:{name:s}}),Be.mutateAsync({path:{name:s}})]),[xe,dt]=T;xe.status==="fulfilled"&&Ye(xe.value,"google-ads-sync"),dt.status==="fulfilled"&&Ye(dt.value,"gtm-sync");const Me=T.find(bt=>bt.status==="rejected");if(Me?.status==="rejected")throw Me.reason}catch(T){r(ft(T))}}async function jt(){js(n);const T=X.data?.connection?.selection.customerId,xe=oe.data?.selection;if(!T||!xe?.accountId||!xe.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const dt=await _.mutateAsync({path:{name:s},body:Pg(w,T,{accountId:xe.accountId,containerId:xe.containerId})});G(yo),B(!1),Ae(),(await k.refetch()).data?.some(bt=>bt.id===dt.id)&&ee(dt.id)}catch(dt){r(ft(dt))}}function Rt(T){switch(T){case"connect-google-ads":Ee();return;case"connect-gtm":ut(),tt();return;case"select-google-ads":C();return;case"select-gtm":Ce();return;case"sync-google-ads":Pe();return;case"sync-gtm":Re();return;case"sync-static-evidence":Ht();return;case"declare-contract":ve();return;case"review-findings":Ze("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":Ze("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":se();return;case"select-contract":Ze("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":z.refetch();return;case"waiting-for-integrity":return}}const qt=ne.data?.customers??[],xt=Z.data?.accounts??[],Et=be.data?.containers??[],ts=ce.data?.workspaces??[],rt=!!N&&!qt.some(T=>T.customerId===N),Vt=!!y&&!xt.some(T=>T.id===y),Nt=!!A&&!Et.some(T=>T.id===A),ss=!!D&&!ts.some(T=>T.id===D),it=rt&&ne.isSuccess&&ne.data.truncated===!1,Dt=Vt&&Z.isSuccess&&Z.data.truncated===!1,Wt=Nt&&be.isSuccess&&be.data.truncated===!1,It=ss&&ce.isSuccess&&ce.data.truncated===!1,hs=Dt||Wt||It,Yt=Dt?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Wt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":It?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,wt=Pa(it,ne.data,ne.isError),As=Pa(Dt,Z.data,Z.isError),gt=Pa(Wt,be.data,be.isError),Ot=Pa(It,ce.data,ce.isError),ys=ne.isError?ft(ne.error):null,xs=Z.isError?ft(Z.error):be.isError?ft(be.error):ce.isError?ft(ce.error):null,zt=m==="google-ads"?ys:m==="gtm"?xs:null,K=Aa("customer",ne.data,qt.length),re=Aa("account",Z.data,xt.length),je=Aa("container",be.data,Et.length),ue=Aa("draft workspace",ce.data,ts.length),me=Z.isError||be.isError||ce.isError&&!!D,Ke=c||m!==null||V;function ns(){ne.refetch()}function ot(){if(Z.isError){Z.refetch();return}if(be.isError){be.refetch();return}ce.isError&&ce.refetch()}return X.isLoading||oe.isLoading||k.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(T=>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"})]},T))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):k.isError&&!k.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",ft(k.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{k.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Sg,{workspace:U,onPrimaryAction:Rt,actionPending:Ge,actionError:Ke?null:a,contracts:pe,selectedContractId:Ne?.id??null,onSelectContract:T=>ee(T||null),contractError:k.isError?ft(k.error):null,onRetryContracts:()=>{k.refetch()},onRetryEvidence:()=>{Promise.all([te.refetch(),le.refetch()])},onChangeGoogleAdsSelection:C,onChangeGtmSelection:Ce,onAddContract:()=>Rt("declare-contract")}),o?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:o}):null,c?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:He(async T=>{T.preventDefault(),await yt()}),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:u,onChange:T=>h(T.target.value),className:$t,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"submit",disabled:De.isPending,children:De.isPending?"Starting…":"Continue to Google"}),e.jsx(P,{type:"button",variant:"outline",onClick:at,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"})]})}),zt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:zt}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:ns,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,it?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:"The saved customer is no longer accessible. Choose another customer before saving."}):null,e.jsxs("div",{className:"grid max-w-2xl gap-4 sm:grid-cols-2",children:[e.jsxs(Ra,{id:"google-ads-customer",label:"Customer account",value:N,onChange:T=>{x(!0),S(T);const xe=qt.find(dt=>dt.customerId===T);R(xe?.parentCustomerId??"")},disabled:ne.isLoading,children:[e.jsx("option",{value:"",children:ne.isLoading?"Loading accessible customers…":"Select a customer"}),rt?e.jsxs("option",{value:N,disabled:it,children:["Saved customer ",N," (",wt,")"]}):null,qt.map(T=>e.jsx("option",{value:T.customerId,children:T.descriptiveName??`Customer ${T.customerId}`},T.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:$t,value:q,onChange:T=>{x(!0),R(T.target.value)},placeholder:"Use only when a manager context is required"})]})]}),K?e.jsx("p",{role:"status",className:`mt-3 text-sm ${ne.data?.truncated?"text-caution":"text-secondary"}`,children:K}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"button",disabled:Se.isPending||ne.isLoading||ne.isError||it||!N,onClick:He(Lt),children:Se.isPending?"Saving…":"Save customer selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:kt,children:"Cancel"})]}),X.data?.connected?e.jsx(jo,{providerLabel:"Google Ads",disabled:Ge,onDisconnect:J}):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"})]})}),zt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:zt}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:ot,children:Z.isError?"Retry account list":be.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Yt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Yt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Ra,{id:"gtm-account",label:"Account",value:y,onChange:T=>{f(!0),T!==y&&(E(""),F("")),j(T)},disabled:Z.isLoading,children:[e.jsx("option",{value:"",children:Z.isLoading?"Loading accounts…":"Select an account"}),Vt?e.jsxs("option",{value:y,disabled:Dt,children:["Saved account ",y," (",As,")"]}):null,xt.map(T=>e.jsx("option",{value:T.id,children:T.name},T.id))]}),e.jsxs(Ra,{id:"gtm-container",label:"Container",value:A,onChange:T=>{f(!0),T!==A&&F(""),E(T)},disabled:!y||be.isLoading,children:[e.jsx("option",{value:"",children:be.isLoading?"Loading containers…":"Select a container"}),Nt?e.jsxs("option",{value:A,disabled:Wt,children:["Saved container ",A," (",gt,")"]}):null,Et.map(T=>e.jsx("option",{value:T.id,children:T.name},T.id))]}),e.jsxs(Ra,{id:"gtm-workspace",label:"Draft workspace (optional)",value:D,onChange:T=>{f(!0),F(T)},disabled:!A||ce.isLoading,children:[e.jsx("option",{value:"",children:ce.isLoading?"Loading workspaces…":"No draft workspace"}),ss?e.jsxs("option",{value:D,disabled:It,children:["Saved draft workspace ",D," (",Ot,")"]}):null,ts.map(T=>e.jsx("option",{value:T.id,children:T.name},T.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[re?e.jsx("p",{role:"status",className:Z.data?.truncated?"text-caution":"text-secondary",children:re}):null,je?e.jsx("p",{role:"status",className:be.data?.truncated?"text-caution":"text-secondary",children:je}):null,ue?e.jsx("p",{role:"status",className:ce.data?.truncated?"text-caution":"text-secondary",children:ue}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"button",disabled:Je.isPending||Z.isLoading||be.isLoading||ce.isLoading&&!!D||me||hs||!y||!A,onClick:He(Qe),children:Je.isPending?"Saving…":"Save container selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:kt,children:"Cancel"})]}),oe.data?.connected?e.jsx(jo,{providerLabel:"Tag Manager",disabled:Ge,onDisconnect:qe}):null]}):null,V?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:He(async T=>{T.preventDefault(),await jt()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:os,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:$t,value:w.name,onChange:T=>G(xe=>({...xe,name:T.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:$t,value:w.eventName,onChange:T=>G(xe=>({...xe,eventName:T.target.value})),placeholder:"booking_complete"})]}),e.jsx(No,{id:"contract-conversion-action",label:"Google Ads conversion action",options:$?.googleAds.conversionActions??[],synced:$?.googleAds.syncedAt!=null,loading:I.isLoading,failed:I.isError,onRetry:()=>{I.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:w.conversionActionId,onChange:T=>G(xe=>({...xe,conversionActionId:T}))}),e.jsx(No,{id:"contract-gtm-tag",label:"Tag Manager tag",options:$?.gtm.tags??[],synced:$?.gtm.syncedAt!=null,loading:I.isLoading,failed:I.isError,onRetry:()=>{I.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:w.tagId,onChange:T=>G(xe=>({...xe,tagId:T}))})]}),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:$t,value:w.conversionId,onChange:T=>G(xe=>({...xe,conversionId:T.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:os,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:$t,value:w.conversionLabel,onChange:T=>G(xe=>({...xe,conversionLabel:T.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:os,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:$t,value:w.triggerIds,onChange:T=>G(xe=>({...xe,triggerIds:T.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:$t,value:w.variableIds,onChange:T=>G(xe=>({...xe,variableIds:T.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:$t,value:w.campaignIds,onChange:T=>G(xe=>({...xe,campaignIds:T.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:$t,value:w.productionHosts,onChange:T=>G(xe=>({...xe,productionHosts:T.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:w.requirePrimaryAction,onChange:T=>G(xe=>({...xe,requirePrimaryAction:T})),children:"Google Ads action is primary"}),e.jsx(wn,{id:"contract-biddable-goal",checked:w.requireBiddableGoal,onChange:T=>G(xe=>({...xe,requireBiddableGoal:T})),children:"Google Ads goal is biddable"}),e.jsx(wn,{id:"contract-runtime-verification",checked:w.verificationRequired,onChange:T=>G(xe=>({...xe,verificationRequired:T})),children:"Runtime proof is required"}),e.jsx(wn,{id:"contract-transaction-id",checked:w.requireTransactionId,onChange:T=>G(xe=>({...xe,requireTransactionId:T})),children:"Transaction ID is required"}),e.jsx(wn,{id:"contract-value",checked:w.requireValue,onChange:T=>G(xe=>({...xe,requireValue:T})),children:"Conversion value is required"}),e.jsx(wn,{id:"contract-currency",checked:w.requireCurrency,onChange:T=>G(xe=>({...xe,requireCurrency:T})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"submit",disabled:_.isPending,children:_.isPending?"Saving…":"Save conversion contract"}),e.jsx(P,{type:"button",variant:"outline",onClick:Mt,children:"Cancel"})]})]})]}):null]})}const Ig=6e4,$g=["7d","14d","30d"],ui="not available",Tg='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%.',Mg="No Google Ads snapshot stored yet",Lg="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.",qg="No closed days yet",Eg="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.",Dg={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},_s=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),wr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Bl=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),Og=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Sn(t,s){return t===null||!Number.isFinite(t)?ui:s===null?Og.format(t/1e6):ah(t,s)}function Sr(t){if(t===null||!Number.isFinite(t))return ui;const s=t*100;return s>0&&s<.1?"<0.1%":`${Bl.format(s)}%`}function Fg(t,s){if(t===null||!Number.isFinite(t))return`${ui} 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%":`${Bl.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function Gg(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function Kg(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function _g(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 Ug({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=$e({...Ud({client:W,path:{name:t},query:{window:s}}),staleTime:Ig}),i=o.data,c=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(_e,{text:Tg})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Bt(i.startDate)," to ",Bt(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(Ha,{windows:$g,value:s,onChange:n,label:"Google Ads time period"})]});if(o.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[c,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(y=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-20"}),e.jsx("div",{className:"skeleton-text-sm w-28"})]},y))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(o.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",ft(o.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{o.refetch()},children:"Retry performance"})]});const{totals:d,daily:u,campaigns:h,comparison:m,comparisonUnavailableReason:b,source:p}=i;if(!p){const y=b==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:y?qg:Mg}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:y?Eg:Lg})]})]})}const x=p.currencyCode,g=p.campaignsInInventory>0&&p.campaignsQueried<p.campaignsInInventory?{queried:p.campaignsQueried,inInventory:p.campaignsInInventory}:null,f=d.costMicros>0&&d.conversions===0,N=[{key:"spend",comparable:!0,label:"Spend",value:Sn(d.costMicros,x),change:m?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:wr.format(d.conversions),change:m?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:f?"no conversions":Sn(d.costPerConversionMicros,x),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Sr(d.conversionRate),change:m?.change.conversionRate??null,direction:"up-good",seriesKey:null}],S=[{key:"clicks",label:"Clicks",value:_s.format(d.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:_s.format(d.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Sr(d.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:Sn(d.cpcMicros,x),seriesKey:null}],q={costMicros:{label:"Spend",color:nt[1],axisId:"spend",formatValue:y=>Sn(y,x)},conversions:{label:"Conversions",color:nt[0],axisId:"conversions",formatValue:y=>wr.format(y)},clicks:{label:"Clicks",color:nt[2],axisId:"clicks",formatValue:y=>_s.format(y)},impressions:{label:"Impressions",color:nt[3],axisId:"impressions",formatValue:y=>_s.format(y)}},R=[...a].map(y=>({dataKey:y,...q[y]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,g!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",_s.format(g.queried)," of"," ",_s.format(g.inInventory)," campaigns, so they are a subset of the account."]}):null,p.truncated?e.jsx("p",{role:"status",className:"mt-3 text-sm text-caution",children:"The provider returned a bounded result, so some rows are missing from the figures below."}):null,!m&&b==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:Dg["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:N.map(y=>{const j=y.seriesKey!==null&&a.has(y.seriesKey),A=j&&a.size===1,E=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[y.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:j?q[y.seriesKey].color:"var(--color-mono-600)"}}):null,y.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:y.value}),m&&y.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${_g(y.change,y.direction)}`,children:Fg(y.change,m.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:y.comparable?`no prior ${s} period stored`:" "})]});return y.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:E},y.key):e.jsx("button",{type:"button","aria-pressed":j,disabled:A,onClick:()=>r(D=>{const F=new Set(D);return F.has(y.seriesKey)?F.delete(y.seriesKey):F.add(y.seriesKey),F.size===0?D:F}),className:`rounded-md border px-3 py-2 text-left transition-colors ${j?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${A?"cursor-default":""}`,children:E},y.key)})}),e.jsx("dl",{className:"mt-2 flex flex-wrap gap-x-6 gap-y-1 rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:S.map(y=>{const j=y.seriesKey!==null&&a.has(y.seriesKey),A=j&&a.size===1,E=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[y.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:j?q[y.seriesKey].color:"var(--color-mono-600)"}}):null,y.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:y.value})]});return y.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:E},y.key):e.jsx("button",{type:"button","aria-pressed":j,disabled:A,onClick:()=>r(D=>{const F=new Set(D);return F.has(y.seriesKey)?F.delete(y.seriesKey):F.add(y.seriesKey),F.size===0?D:F}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${A?"cursor-default":"hover:bg-surface-hover"}`,children:E},y.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(xl,{data:u,xKey:"date",series:R,xTickFormatter:yn,labelFormatter:Bt}),e.jsx("ul",{className:"sr-only",children:u.map(y=>e.jsxs("li",{children:[Bt(y.date),":"," ",R.map(j=>`${j.label} ${q[j.dataKey].formatValue(y[j.dataKey])}`).join(", "),y.origin==="filled"?", no delivery reported":""]},y.date))})]}),e.jsxs("div",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"By campaign"}),e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Campaign performance"})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads campaign performance for the selected window"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Campaign"}),e.jsx("th",{className:"text-left",children:"Status"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Clicks"}),e.jsx("th",{className:"text-right",children:"Spend"}),e.jsx("th",{className:"text-right",children:"Conversions"}),e.jsx("th",{className:"text-right",children:"CTR"}),e.jsx("th",{className:"text-right",children:"Cost / conv."})]})}),e.jsx("tbody",{children:h.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):h.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:y.name??y.campaignId,children:y.name??e.jsx("span",{className:"font-mono text-secondary",children:y.campaignId})}),e.jsx("td",{children:e.jsx(de,{tone:Gg(y.status),children:Kg(y.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:_s.format(y.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:_s.format(y.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Sn(y.totals.costMicros,x)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:wr.format(y.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Sr(y.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:y.totals.costMicros>0&&y.totals.conversions===0?e.jsx(de,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:Sn(y.totals.costPerConversionMicros,x)})})]},y.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Hs(Ds(p.capturedAt))," · ","customer ",p.customerId," · ","latest closed day ",Bt(p.asOfDate),p.openDate?e.jsxs(e.Fragment,{children:[" · ",Bt(p.openDate)," still open, excluded"]}):null,p.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",p.timeZone]}):null]})]})]})}const Cr=20,Ms=50,Bg=50,Vg=50;function mi(t){return t==="viewer"}function hi(t){return t?.status==="unavailable"}function Vl(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function zl(t,s){const n=new Map(s.map(r=>[r.id,r.label])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function Ia(t,s,n){if(t.kind==="all")return s.map(o=>o.id);if(t.kind==="specific")return s.filter(o=>t.propertyIds.includes(o.id)).map(o=>o.id);const a=new Set(t.groupIds),r=new Set(n.filter(o=>a.has(o.id)).flatMap(o=>o.propertyIds));return s.filter(o=>r.has(o.id)).map(o=>o.id)}function zg(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 kr(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 wo(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function So(t){return t==="matched"?"Matched":t==="duplicate"?"Duplicate":t==="ambiguous"?"Ambiguous":t==="proposed"?"Property needs review":t==="excluded"?"Property excluded":t==="invalid"?"Invalid row":"Not matched"}function $a(t){return t.status==="duplicate"&&t.duplicateOfRow?`Duplicates row ${t.duplicateOfRow}.`:t.status==="matched"?null:t.reason==="group-label-ambiguous"?`More than one group matches “${t.group}”. Rename duplicate groups, then preview again.`:t.status==="ambiguous"?"More than one Property matches this row. Add an exact URL to choose one.":t.status==="unmatched"?"No included Property matches this row.":t.reason==="group-key-conflict"?`The group name “${t.group}” conflicts with an existing setup identity. Rename the group, then preview again.`:t.status==="invalid"?"Check the Property, group, and optional URL fields.":t.status==="proposed"?"Review this proposed Property before importing it.":t.status==="excluded"?"Include this Property before importing it.":t.reason??null}function Jr(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Ar(t){return Jr(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function Xr({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[o,i]=l.useState(""),[c,d]=l.useState(!1),u=o.trim().toLocaleLowerCase(),h=u?t.filter(x=>x.label.toLocaleLowerCase().includes(u)):t,m=c?h:h.slice(0,Bg),b=m.length<h.length;function p(){const x=new Set([...s,...m.map(g=>g.id)]);n(t.filter(g=>x.has(g.id)).map(g=>g.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:o,onChange:x=>i(x.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:m.length===0,onClick:p,children:"Select all shown"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),h.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 ",h.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(x=>{const g=s.includes(x.id);return e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-sm text-primary",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{"aria-label":`Select ${x.label}`,checked:g,type:"checkbox",onChange:f=>n(Vl(s,x.id,f.currentTarget.checked))}),e.jsx("span",{children:x.label})]}),x.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[x.urlCount," URLs"]})]},x.id)})}),b?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function xi(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(de,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function pi({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(de,{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 Qg({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,i]=l.useState(null),c=t.preview,d=c?.counts.needsAttention??0,u=c?.rows.filter(A=>A.status==="matched")??[],h=c?.rows??[],m=h.filter(A=>A.status!=="matched"),b=Math.max(1,Math.ceil(h.length/Ms)),p=Math.min(s,b-1),x=h.slice(p*Ms,(p+1)*Ms),g=Math.max(1,Math.ceil(m.length/Ms)),f=Math.min(a,g-1),N=m.slice(f*Ms,(f+1)*Ms),S=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,q=u.length>0&&!t.isApplying,R=c!==null&&o===c.previewChecksum,y=m.length>0&&f===g-1;l.useEffect(()=>{n(0),r(0),i(null)},[c?.previewChecksum]);async function j(A){if(A)try{t.onCsvChange(await A.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:A=>{j(A.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:A=>t.onCsvChange(A.currentTarget.value),placeholder:`property,group,url
3
- Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!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]}),c?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[c.counts.matchedRows," matched · ",c.counts.groupsReady," group",c.counts.groupsReady===1?"":"s"," ready",d>0?` · ${d} need${d===1?"s":""} attention`:""]}),c.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:c.groupChanges.map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:A.label}),e.jsx("td",{className:"text-secondary",children:A.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:A.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[A.addedTargetKeys.length,A.unchangedTargetKeys.length>0?` · ${A.unchangedTargetKeys.length} already members`:""]})]},A.groupKey))})]})}):null,c.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",c.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:x.map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:A.dataRow}),e.jsx("td",{className:"text-heading",children:A.property}),e.jsx("td",{className:"text-secondary",children:A.group}),e.jsxs("td",{children:[e.jsx(de,{tone:wo(A.status),children:So(A.status)}),$a(A)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:$a(A)}):null]})]},A.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",p+1," of ",b," · ",c.rows.length," rows"]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===0,onClick:()=>n(A=>Math.max(0,A-1)),children:"Previous 50 rows"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===b-1,onClick:()=>n(A=>Math.min(b-1,A+1)),children:"Next 50 rows"})]})]}):null,d>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",d," row",d===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:N.map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:A.dataRow}),e.jsx("td",{className:"text-heading",children:A.property}),e.jsx("td",{className:"text-secondary",children:A.group}),e.jsxs("td",{children:[e.jsx(de,{tone:wo(A.status),children:So(A.status)}),$a(A)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:$a(A)}):null]})]},A.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",f+1," of ",g]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===0,onClick:()=>r(A=>Math.max(0,A-1)),children:"Previous 50 exceptions"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===g-1,onClick:()=>r(A=>Math.min(g-1,A+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:R,disabled:t.isApplying||!y,onChange:A=>i(A.currentTarget.checked?c.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",d," row",d===1?"":"s"," will be skipped."]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!q||!R,onClick:()=>{t.onApply(u.map(A=>A.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${u.length} matched row${u.length===1?"":"s"}`})]}):e.jsx(P,{type:"button",className:"mt-3 min-h-11",disabled:!q,onClick:()=>{t.onApply(u.map(A=>A.dataRow))},children:t.isApplying?"Creating groups…":`Create ${c.counts.groupsReady} group${c.counts.groupsReady===1?"":"s"} with ${u.length} membership${u.length===1?"":"s"}`})]}):null]})}const Hg="—";function Wg({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:o=!1,isBusy:i=!1,canContinue:c=!0,onSelectedQueryIdsChange:d,onApplySelectedQueries:u,onClearQueryAssignments:h,onRemoveQuery:m,onCreateQueries:b,onCreateAndPairQuestions:p,isCreatingQueries:x=!1,createQueriesError:g=null,onManageProjectQueries:f,groups:N,audience:S,onAudienceChange:q,assignmentImpact:R=null,isPreviewingAssignmentImpact:y=!1,assignmentImpactError:j=null,onRetryAssignmentImpact:A,assignmentNotice:E=null,onReplaceAssignments:D,isReplacingAssignments:F=!1,onBack:V,onContinue:B}){const[w,G]=l.useState(""),[L,ee]=l.useState(!1),[O,X]=l.useState(!1),[oe,k]=l.useState(""),[I,$]=l.useState(""),[te,le]=l.useState(null);if(hi(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(pi,{message:s.message})});const pe=mi(t),ie=S,Ne=q,Y=Ia(ie,n,N),z=Y.length,ne=z>0&&r.length>0&&!o&&!i&&!y&&R!==null&&j===null,Z=h??m,be=w.trim().toLocaleLowerCase(),ce=be?a.filter(H=>Ar(H).toLocaleLowerCase().includes(be)):a,De=ce.filter(H=>(H.propertyIds?.length??0)===0),we=O?De:ce,Se=L?we:we.slice(0,Vg),Je=Se.filter(H=>!Jr(H)),Ue=[...new Set(oe.split(`
4
- `).map(H=>H.trim()).filter(Boolean))],Be=[...I.matchAll(/\{([a-z][\w-]*)\}/gi)].map(H=>H[1]),ze=n.filter(H=>Y.includes(H.id)),Oe=Be.length===0||I.trim()===""?[]:ze.map(H=>({propertyId:H.id,text:Be.reduce((Ie,Ge)=>Ie.replaceAll(`{${Ge}}`,H.label),I.trim())})),_=[...new Set(Oe.map(H=>H.text))];function U(){const H=new Set([...r,...Je.map(Ie=>Ie.id)]);d(a.filter(Ie=>H.has(Ie.id)).map(Ie=>Ie.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."})]})}),pe?e.jsx(xi,{}):null,pe?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:ie.kind==="all"?"all":ie.kind==="specific"?"specific":`group:${ie.groupIds[0]??""}`,onChange:H=>{const Ie=H.currentTarget.value;Ie==="all"?Ne({kind:"all"}):Ie==="specific"?Ne({kind:"specific",propertyIds:[]}):Ie.startsWith("group:")&&Ne({kind:"groups",groupIds:[Ie.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]}),N.length>0?e.jsx("optgroup",{label:"Groups",children:N.map(H=>{const Ie=Ia({kind:"groups",groupIds:[H.id]},n,N).length;return e.jsx("option",{value:`group:${H.id}`,disabled:Ie===0,children:kr(H,n)},H.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),ie.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:ie.groupIds.map(H=>{const Ie=N.find(Ge=>Ge.id===H);return Ie?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:[kr(Ie,n),e.jsx("button",{type:"button","aria-label":`Remove ${Ie.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 Ge=ie.groupIds.filter(se=>se!==Ie.id);Ne(Ge.length>0?{kind:"groups",groupIds:Ge}:{kind:"all"})},children:"×"})]},Ie.id):null})}),N.some(H=>!ie.groupIds.includes(H.id)&&Ia({kind:"groups",groupIds:[H.id]},n,N).length>0)?e.jsxs("label",{className:"block max-w-sm",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Add another group"}),e.jsxs("select",{"aria-label":"Add another group",value:"",onChange:H=>{H.currentTarget.value&&Ne({kind:"groups",groupIds:[...ie.groupIds,H.currentTarget.value]})},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",children:"Choose a group"}),N.filter(H=>!ie.groupIds.includes(H.id)).map(H=>{const Ie=Ia({kind:"groups",groupIds:[H.id]},n,N).length;return e.jsx("option",{value:H.id,disabled:Ie===0,children:kr(H,n)},H.id)})]})]}):null,z===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,ie.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(Xr,{legend:"Specific Properties",properties:n,selectedPropertyIds:ie.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:H=>{Ne({kind:"specific",propertyIds:H})}})}):null,e.jsx("p",{className:"mt-3 max-w-2xl text-sm text-secondary",children:"Groups are shortcuts resolved when you assign. Changing membership later does not rewrite existing assignments, and a Property added later does not receive earlier group queries."})]}),pe||!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:oe,onChange:H=>k(H.currentTarget.value),placeholder:`best apartments in dallas
5
- luxury apartments atlanta
6
- pet friendly apartments austin`}),g?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:g}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ue.length===0||x||i,onClick:()=>{Promise.resolve(b(Ue)).then(()=>k(""),()=>{})},children:x?"Adding…":`Add ${Ue.length||""} ${Ue.length===1?"query":"queries"}`.replace(" "," ")}),f?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:f,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:I,onChange:H=>$(H.target.value),placeholder:"apartments near {property}"}),I.trim()===""?null:Be.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."]}):ze.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:[_.length," ",_.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:_.slice(0,3).map(H=>e.jsx("li",{className:"text-sm text-strong",children:H},H))}),_.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",_.length-3," more"]}):null]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Oe.length===0||x||i||!p,onClick:()=>{p&&Promise.resolve(p(Oe)).then(()=>$(""),()=>{})},children:x?"Adding…":`Add ${Oe.length||""} ${Oe.length===1?"query":"queries"}`.replace(" "," ")}),Oe.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"," ",Oe.length," assignment",Oe.length===1?"":"s","."]}):null]})]})]}),pe?null:e.jsx("div",{className:"space-y-3 border-y border-default py-4",children:a.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:Je.length===0,onClick:U,children:"Select all shown queries"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>d([]),children:"Clear query selection"}),e.jsx(P,{type:"button",size:"sm",className:"min-h-11",disabled:!ne,onClick:()=>{u({queryIds:r,propertyIds:Y,...ie.kind==="groups"?{groupIds:ie.groupIds}:{}})},children:o?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${zg(ie,N,z)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[y?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,R?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",R.assignmentCount," Property assignment",R.assignmentCount===1?"":"s"," · ",R.addedAssignments," new, ",R.alreadyPresentAssignments," already assigned"," · ",R.fullRunProviderCalls," provider request",R.fullRunProviderCalls===1?"":"s"," per full run"," · ",R.addedProviderCalls," new",ie.kind==="groups"?` · ${R.resolvedPropertyCount} unique ${R.resolvedPropertyCount===1?"Property":"Properties"}${R.overlapCount>0?`, ${R.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}),A?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:A,children:"Retry impact"}):null,V?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:V,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",z," Properties = ",r.length*z," assignments"]})]}),E?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:E}):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:w,onChange:H=>{G(H.currentTarget.value),ee(!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,"," ",ce.length-De.length," of ",ce.length," applied"]}),pe||De.length===0?null:e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{X(H=>!H),ee(!1)},children:O?"Show all queries":`Show the ${De.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:[pe?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),pe?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:Se.map(H=>{const Ie=Jr(H),Ge=Ar(H),se=r.includes(H.id),Xe=(H.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[pe?null:Ie?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 ${Ge}`,checked:se,type:"checkbox",onChange:ut=>d(Vl(r,H.id,ut.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:Ge})}),e.jsx("td",{className:"text-secondary",children:zl(H.propertyIds??[],n)}),pe?null:e.jsx("td",{className:"text-right",children:Xe?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[D?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||F,onClick:()=>le({queryId:H.id,propertyIds:[...H.propertyIds??[]]}),"aria-label":`Replace query assignments for ${Ge}`,children:"Replace assignments"}):null,e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{Z(H.id)},"aria-label":`Clear query assignments for ${Ge}`,children:"Clear assignments"})]}):null})]},H.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,pe||!te?null:(()=>{const H=a.find(se=>se.id===te.queryId),Ie=H?Ar(H):"this query",Ge=te.propertyIds.filter(se=>n.some(Xe=>Xe.id===se));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 “",Ie,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(Xr,{legend:"Properties for this query",properties:n,selectedPropertyIds:Ge,onSelectedPropertyIdsChange:se=>le(Xe=>Xe&&{...Xe,propertyIds:[...se]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:F||i,onClick:()=>le(null),children:"Keep current assignments"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ge.length===0||F||i||!D,onClick:()=>{D&&Promise.resolve(D({queryId:te.queryId,propertyIds:Ge}))},children:F?"Replacing assignments…":`Replace with ${Ge.length} ${Ge.length===1?"Property":"Properties"}`})]})]})})(),Se.length<we.length?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>ee(!0),children:"Show all queries"}):null,pe?null:e.jsxs(e.Fragment,{children:[c?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${V?"justify-between":"justify-end"}`,children:[V?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:V,children:"Back"}):null,e.jsx(P,{type:"button",variant:ne?"outline":"default",className:"min-h-11",disabled:!c||i,onClick:B,children:"Continue"})]})]})]})}function Yg({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:o=!1,onGroupDraftChange:i,onSaveGroup:c,onEditGroup:d,onRemoveGroup:u,onClearGroupDraft:h,membershipImport:m,onBack:b,onContinue:p}){if(hi(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(pi,{message:s.message})});const x=mi(t),g=r.name.trim().length>0&&r.propertyIds.length>0&&!o,f=n.filter(R=>r.propertyIds.includes(R.id)).length,N=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,S=!x&&(d!==void 0||u!==void 0);function q(){if(h){h();return}i({name:"",propertyIds:[],competitorDomains:""})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-groups-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-groups-title",children:"Groups"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Use groups to assign queries by market and compare competitors."})]})}),x?e.jsx(xi,{}):null,x||!m?null:e.jsx(Qg,{value:m}),x?null:e.jsxs("div",{className:"space-y-4 border-y border-default py-4",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Group name"}),e.jsx("input",{"aria-label":"Group name",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.name,onChange:R=>i({...r,name:R.currentTarget.value}),placeholder:"Waterfront venues"})]}),e.jsxs("details",{children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:[f," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(Xr,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:R=>i({...r,propertyIds:R})})})]}),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:R=>i({...r,competitorDomains:R.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!g,onClick:()=>{c(r)},children:o?"Saving group…":"Save group"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!N,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."})]}),N?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(R=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:R.name}),e.jsx("td",{className:"text-secondary",children:zl(R.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:R.competitors.length>0?R.competitors.join(", "):"None"}),S?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[d?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${R.name}`,onClick:()=>d(R),children:"Edit"}):null,u?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${R.name}`,onClick:()=>{u(R.id)},children:"Remove"}):null]})}):null]},R.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,x?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${b?"justify-between":"justify-end"}`,children:[b?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:b,children:"Back"}):null,e.jsx(P,{type:"button",className:"min-h-11",disabled:N,onClick:p,children:a.length===0&&!N?"Continue without groups":"Continue"})]})]})}function Jg({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:o,onReviewChanges:i,isReviewing:c=!1,canReviewChanges:d=!0,reviewedChanges:u,reviewChangesError:h,canPublish:m,isPublishing:b=!1,onPublish:p}){const[x,g]=l.useState(Cr),[f,N]=l.useState(Cr),[S,q]=l.useState(Cr);if(hi(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(pi,{message:s.message})});const R=mi(t),y=r?.items??[],j=r?.coverageItems??[],A=y.slice(0,x),E=j.slice(0,f),D=a.slice(0,S),F=i!==void 0,V=u!=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."})]})}),R?e.jsx(xi,{}):null,r?e.jsx("section",{"aria-labelledby":"advanced-measurement-sitemap-review-title",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:e.jsxs("div",{className:"max-w-2xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{id:"advanced-measurement-sitemap-review-title",className:"text-sm font-medium text-heading",children:"Sitemap changes need review"}),r.exceptionCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.exceptionCount," sitemap ",r.exceptionCount===1?"entry needs":"entries need"," review."]}):null,r.coverageReviewCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.coverageReviewCount," ",r.coverageReviewCount===1?"Property has":"Properties have"," URL coverage changes."]}):null]}),r.exceptionCount>0?e.jsxs("details",{className:"border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["URLs not added to Properties (",r.exceptionCount,")"]}),y.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:A.map(B=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:B.url}),e.jsx("p",{className:"mt-1 text-secondary",children:B.reason})]},`${B.url}-${B.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 ",A.length," of ",y.length]}),A.length<y.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>g(B=>B+Ms),children:"Show next 50 URLs"}):null]})]}):null,R?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,")"]}),E.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[E.map(B=>e.jsxs("section",{"aria-label":`${B.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:B.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:B.savedUrls.map(w=>e.jsx("li",{className:"break-all text-secondary",children:w},w))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),B.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:B.currentSitemapUrls.map(w=>e.jsx("li",{className:"break-all text-secondary",children:w},w))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},B.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",E.length," of ",j.length]}),E.length<j.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>N(B=>B+Ms),children:"Show next 50 URL changes"}):null]})]}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected Properties before confirming."})]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="keep-existing",onChange:()=>r.onCoverageResolutionChange("keep-existing")}),"Keep existing Property URLs"]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="replace-with-imported",onChange:()=>r.onCoverageResolutionChange("replace-with-imported")}),"Use current sitemap URLs"]})]}):null,e.jsx(P,{type:"button",className:"min-h-11",onClick:()=>{r.onResolve()},children:"Confirm sitemap changes"})]})]})}):null,e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Groups"}),e.jsx("th",{children:"Assignments"}),e.jsx("th",{children:"Provider requests / run"})]})}),e.jsx("tbody",{children:e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-heading",children:n.properties}),e.jsx("td",{className:"tabular-nums text-heading",children:n.queries}),e.jsx("td",{className:"tabular-nums text-heading",children:n.groups}),e.jsx("td",{className:"tabular-nums text-heading",children:n.assignments??"—"}),e.jsx("td",{className:"tabular-nums text-heading",children:n.providerCalls??Hg})]})})]})}),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,u?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:u.title}),u.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:u.items.map((B,w)=>e.jsx("li",{children:B},`${B}-${w}`))}):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:D.map(B=>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:B.title}),B.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:B.detail}):null]}),e.jsx(de,{tone:B.tone??"caution",children:"Needs attention"})]},B.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",D.length," of ",a.length]}),D.length<a.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>q(B=>B+Ms),children:"Show next 50 exceptions"}):null]})]})]}),R?null:e.jsxs(e.Fragment,{children:[F&&h?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:h}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${o?"justify-between":"justify-end"}`,children:[o?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:o,children:"Back"}):null,i!==void 0&&!V?e.jsx(P,{type:"button",className:"min-h-11",disabled:c||!d,onClick:()=>{i()},children:c?"Reviewing changes…":"Review changes"}):e.jsx(P,{type:"button",className:"min-h-11",disabled:!m||b,onClick:()=>{p()},children:b?"Publishing setup…":"Publish setup"})]})]})]})}const Xg={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function Zg(t){return t.trim().toLocaleLowerCase()}function ef(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function tf({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 sf({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const o=!t||r==="reviewing",i=o||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function c(d,u){n({...s,[d]:u})}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(de,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:d=>{d.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:o,onChange:d=>c("sitemapUrl",d.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:o,onChange:d=>c("examplePropertyUrl",d.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:o,onChange:d=>c("preferredHost",d.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:o,onChange:d=>c("propertyPathPattern",d.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:o,onChange:d=>c("additionalHost",d.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:o,onChange:d=>c("additionalPathPattern",d.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:o,onChange:d=>c("excludedPaths",d.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(P,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function nf({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:o,onSelectedPropertyIdsChange:i,onContinue:c,isContinuing:d=!1,onRetryProperties:u,onReturnToImport:h,maxVisibleProperties:m,onShowAllProperties:b}){const p=Zg(a),x=s.filter(D=>ef(D,p)),g=Math.max(1,m??x.length),f=x.slice(0,g),N=new Set(o),S=s.filter(D=>N.has(D.id)).map(D=>D.id),q=f.length<x.length;function R(D){const F=new Set(D);i(s.filter(V=>F.has(V.id)).map(V=>V.id))}function y(D,F){if(!t||d)return;const V=new Set(S);F?V.add(D):V.delete(D),R(V)}function j(){!t||d||R([...S,...f.map(D=>D.id)])}function A(){!t||d||i([])}function E(){!t||d||S.length===0||c(S)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||d,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:u,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:u,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:h,children:"Review sitemap"})]}):null,n==="ready"&&s.length>0?e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:a,disabled:d,onChange:D=>r(D.target.value),className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),t?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:d,onClick:j,children:"Select all shown"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:d||S.length===0,onClick:A,children:"Clear selection"})]}):null]}),x.length===0?e.jsxs("div",{className:"mt-4 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties match this search."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Clear the search or review the sitemap again."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:h,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",f.length," of ",x.length," Properties"]}),e.jsxs("p",{children:[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:f.map(D=>{const F=Xg[D.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:D.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(tf,{property:D})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(de,{tone:F.tone,children:F.label})}),t?e.jsx("td",{className:"p-0 text-right",children:e.jsx("label",{className:"ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{type:"checkbox","aria-label":`Select ${D.name}`,checked:S.includes(D.id),disabled:d,onChange:V=>y(D.id,V.target.checked),className:"size-6 accent-accent"})})}):null]},D.id)})})]})}),q&&b?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:d,onClick:b,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(P,{type:"button",variant:"ghost",disabled:d,onClick:h,children:"Back"}),e.jsx(P,{type:"button",disabled:d||S.length===0,onClick:E,children:d?"Saving Properties…":"Continue"})]}):null]}):null]})}function af(t){return t.activeStep==="import"?e.jsx(sf,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(nf,{...t})}const rf=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function of({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:o}){const i=l.useRef(null),c=l.useRef(null),d=l.useRef(null),u=l.useRef(null),h=l.useRef(!1),[m,b]=l.useState(!1);return l.useEffect(()=>{s||b(!1)},[s]),l.useEffect(()=>{const p=h.current;h.current=m,m?d.current?.focus():p&&u.current?.focus()},[m]),l.useEffect(()=>{const p=i.current;if(i.current=t,p===null||p===t)return;const x=c.current?.querySelector('h1, h2, h3, [role="heading"]');x&&(x.tabIndex=-1,x.focus())},[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 w-full sm:flex-1",children:[e.jsx("h2",{children:"Advanced measurement setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties and queries you want to measure."})]}),s?e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end",children:[e.jsx(de,{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(P,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>b(!1),children:"Keep editing"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(P,{ref:u,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:rf.map(p=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===p.id?"step":void 0,onClick:()=>r(p.id),className:`block min-h-11 border-b-2 bg-transparent px-1 py-3 text-left text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${t===p.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:p.label}):e.jsx("span",{"aria-current":t===p.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===p.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:p.label})},p.id))})}),e.jsx("div",{ref:c,children:o})]})}function lf(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(af,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(Wg,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(Yg,{...t.groups,access:s}):"review"in t?e.jsx(Jg,{...t.review,access:s}):null}function Ta(t){return e.jsx(of,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:lf(t)})}function Ql(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Kt(t){return{"If-Match":t,"Idempotency-Key":Ql()}}function cn(t){return t instanceof pn&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function is(t,s){return t instanceof pn?s:(t instanceof Error?t.message.trim():"")||s}function cf(t){const s="Could not calculate assignment impact.";if(!(t instanceof pn)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const df={loadSetup:t=>pt(()=>uu({client:W,path:{name:t}})),loadDraft:t=>pt(()=>du({client:W,path:{name:t}})),createDraft:(t,s)=>pt(()=>cu({client:W,path:{name:t},headers:{"Idempotency-Key":Ql()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>pt(()=>lu({client:W,path:{name:t},headers:Kt(s),body:n})),applySitemapSelection:(t,s,n,a)=>pt(()=>ou({client:W,path:{name:t},headers:Kt(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>pt(()=>iu({client:W,path:{name:t},body:s})),applyAssignments:(t,s,n)=>pt(()=>ru({client:W,path:{name:t},headers:Kt(s),body:n})),replaceAssignments:(t,s,n)=>pt(()=>au({client:W,path:{name:t},headers:Kt(s),body:n})),applyPairedAssignments:(t,s,n)=>pt(()=>nu({client:W,path:{name:t},headers:Kt(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>pt(()=>su({client:W,path:{name:t},headers:Kt(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>pt(()=>tu({client:W,path:{name:t},headers:Kt(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>pt(()=>eu({client:W,path:{name:t},headers:Kt(s),body:{target:n}})),upsertGroup:(t,s,n)=>pt(()=>Zd({client:W,path:{name:t},headers:Kt(s),body:{group:n}})),removeGroup:(t,s,n)=>pt(()=>Xd({client:W,path:{name:t},headers:Kt(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>pt(()=>Jd({client:W,path:{name:t},headers:Kt(s),body:n})),removeCompetitor:(t,s,n,a)=>pt(()=>Yd({client:W,path:{name:t},headers:Kt(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>pt(()=>Wd({client:W,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>pt(()=>Hd({client:W,path:{name:t},headers:Kt(s),body:n})),compilePreview:t=>pt(()=>Qd({client:W,path:{name:t}})),diffPreview:t=>pt(()=>zd({client:W,path:{name:t}})),publish:(t,s,n)=>pt(()=>Vd({client:W,path:{name:t},headers:Kt(s),body:n})),discard:(t,s)=>pt(()=>Bd({client:W,path:{name:t},headers:Kt(s)}))},Co={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},Bn={name:"",propertyIds:[],competitorDomains:""},ko=50;function Hn(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function uf(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 Ao(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 mf(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,c=i.startsWith("*"),d=i.endsWith("*"),u=i.slice(c?1:0,d?-1:void 0).trim();if(!u)throw new Error("Ignored URL patterns must include text besides *.");const h=c&&d?"contains":c?"suffix":d?"prefix":"exact",m=`${h}:${u}`;n.has(m)||(n.add(m),s.push({kind:h,value:u}))}return s}function hf(t){const s=uf(t.sitemapUrl),n=t.examplePropertyUrl.trim()?Hn(t.examplePropertyUrl):null,a=Hn(t.preferredHost)??n??Hn(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=Hn(t.additionalHost),o=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(o!==i||o&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const c=mf(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:Ao(t)},...r?{aliases:[{host:r,pathTemplate:Ao({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...c.length>0?{excludedSlugPatterns:c}:{}}}}function xf(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 pf(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 Po(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function gf(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Pr(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function Zr(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function Ro(t){return Hn(t)}function Hl(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 Wl(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 Yl(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Jl(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function ff(t,s){const n=Hl(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 yf(t,s){const n=Wl(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=Jl(t.authoring,n.targetKeys[r]);return`${n.label} — ${o}`}return n.label}function bf(t,s){const n=Yl(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${Jl(t.authoring,n.targetKey)} — ${a}`}function vf(t,s){return s.path[0]==="identities"?"Project domain":ff(t,s)??yf(t,s)??bf(t,s)}function Io(t,s,n){const a=Yl(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 jf(t,s){const n=vf(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,Io(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,Io(s,t,"locations")].filter(Boolean).join(" — ")||void 0};case"target-without-aliases":return{title:"Add Property aliases",detail:"Add a name or alias to measure mentions.",tone:"caution",affected:n};case"duplicate-group-key":return{title:"Resolve duplicate groups",detail:"Two groups use the same setup identifier. Rename one group, then review again.",tone:"negative",affected:n};case"group-unknown-target":return{title:"Fix group Properties",detail:"This group contains a Property that is no longer in setup. Remove it or add the Property back.",tone:"negative",affected:n};case"group-excluded-target":return{title:"Include or remove a grouped Property",detail:"This group contains an excluded Property. Include it or remove it from the group.",tone:"negative",affected:n};case"competitor-invalid-domain":return{title:"Fix a competitor domain",detail:"Enter a valid competitor domain.",tone:"negative",affected:n};case"competitor-matches-project":return{title:"Remove a project domain",detail:"A competitor cannot use the project domain.",tone:"negative",affected:n};case"competitor-duplicate":return{title:"Remove a duplicate competitor",detail:"List each competitor domain only once in a group.",tone:"negative",affected:n};case"duplicate-assignment":return{title:"Remove a duplicate query",detail:"Assign each query to a Property only once.",tone:"negative",affected:n};case"assignment-unknown-target":return{title:"Fix a query assignment",detail:"This query is assigned to a Property that is no longer in setup. Remove the assignment or add the Property back.",tone:"negative",affected:n};case"assignment-excluded-target":return{title:"Include or unassign a Property",detail:"This query is assigned to an excluded Property. Include it or remove the assignment.",tone:"negative",affected:n};case"assignment-unknown-query":return{title:"Remove an unavailable query",detail:"This assignment refers to a tracked query that is no longer available. Remove it or add the query back to the project.",tone:"negative",affected:n};case"assignment-unclassified":return{title:"Classify a query",detail:"Choose Branded or Non-brand for this query before publishing.",tone:"negative",affected:n};case"query-limit-exceeded":return{title:"Reduce queries",detail:"This setup exceeds the distinct-query publishing limit. Remove some query assignments, then review again.",tone:"negative"};case"target-without-assignments":return{title:"Assign queries",detail:"Assign at least one query to measure a Property.",tone:"caution",affected:n};case"invalid-compiled-plan":return{title:"Fix setup details",detail:"A setup value could not be validated. Review the affected item, then review again.",tone:"negative",affected:n};case"compiled-plan-too-large":return{title:"Reduce setup size",detail:"This setup is too large to publish. Remove Properties, queries, or groups, then review again.",tone:"negative"};case"active-revision-schema-v1":return{title:"Historical results will be kept",detail:"Existing results remain visible after you publish this setup.",tone:"neutral"}}return{title:t.severity==="fail"?"An unexpected setup issue blocks publishing":"An unexpected setup issue needs review",detail:t.severity==="fail"?"Review the affected item, make a correction, and review again. If it remains blocked, contact support.":"Review the affected item before publishing. If it remains, contact support.",tone:t.severity==="fail"?"negative":"caution",affected:n}}function Ma(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function Xl(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 Nf(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${Ma(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${Ma(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${Ma(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${Ma(n,"item")} need review.`:s}})()}${Xl(a)}`}function wf(t,s){const n=new Map;for(const a of t){const r=jf(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:Nf(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function Rr(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function Ir(t,s,n){const a=Hl(n,t.path),r=Wl(n,t.path),o=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=o?n?.targets.find(h=>h.stableKey===o):void 0,c=a?.label??r?.label,d=Xl(c?[c]:[]),u={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...u,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${d}`};case"excluded-target-has-assignments":return{...u,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${d}`};case"group-unknown-target":return{...u,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${d}`};case"measurement.discovery.proposed_new_target":{const h=Rr(a)??"the proposed Property";return{...u,title:"Review a new Property",detail:`Review ${h}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const h=Rr(a)??"the proposed Property",m=i?.label??"an existing Property";return{...u,title:"Review a moved Property",detail:`Review ${h}. It may be the same Property as ${m}.`}}case"measurement.discovery.rebind_ambiguous":{const h=Rr(a)??"the proposed Property",m=i?.label??"an existing Property";return{...u,title:"Choose an existing Property",detail:`Review ${h}. It may match ${m}; choose the correct Property.`}}default:return{...u,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function Sf(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 Ns(t){return[...new Set(t)]}function zs(t){return Ns(t).sort()}function Cf(t,s,n){return t.kind==="groups"?{groupKeys:zs(t.groupIds),queryIds:zs(n)}:{targetKeys:zs(t.kind==="all"?s:t.propertyIds),queryIds:zs(n)}}function kf(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 $o(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function Af(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($o).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($o).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:Zr(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function Pf({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:o,canEdit:i=!0,onCreateQueries:c,onManageProjectQueries:d,onPublished:u,service:h=df}){const[m,b]=l.useState(null),[p,x]=l.useState(null),[g,f]=l.useState("import"),[N,S]=l.useState(!0),[q,R]=l.useState(null),[y,j]=l.useState(null),[A,E]=l.useState([]),[D,F]=l.useState({...Co}),[V,B]=l.useState("idle"),[w,G]=l.useState(""),[L,ee]=l.useState(ko),[O,X]=l.useState([]),[oe,k]=l.useState([]),[I,$]=l.useState({kind:"all"}),[te,le]=l.useState(null),[pe,ie]=l.useState(null),[Ne,Y]=l.useState(!1),[z,ne]=l.useState(null),[Z,be]=l.useState(0),[ce,De]=l.useState(null),[we,Se]=l.useState({...Bn}),[Je,Ue]=l.useState(null),[Be,ze]=l.useState(""),[Oe,_]=l.useState(null),[U,H]=l.useState(!1),[Ie,Ge]=l.useState(!1),[se,Xe]=l.useState(null),[ut,mt]=l.useState(null),[Ve,Fe]=l.useState(null),[ht,Ze]=l.useState(null),[Ae,at]=l.useState(null),kt=l.useRef(0),Mt=l.useRef(0),Ee=p?.draft??null,C=p?.etag??null,Ce=l.useMemo(()=>!i&&o?{baseActiveRevision:o.revision,authoring:Af(o)}:null,[i,o]),ve=Ee??Ce;async function Ye(K){const re=++kt.current;S(!0),R(null);try{let[je,ue]=await Promise.all([h.loadSetup(t),h.loadDraft(t)]);if(!ue.draft&&K&&i&&(await h.createDraft(t,je.activeRevision),[je,ue]=await Promise.all([h.loadSetup(t),h.loadDraft(t)])),re!==kt.current)return;b(je),x(ue),f(xf(ue.draft));const me=Pr(ue.draft);X(me)}catch(je){if(re!==kt.current)return;R(is(je,"Could not load advanced measurement setup."))}finally{re===kt.current&&S(!1)}}l.useEffect(()=>(Ye(!0),()=>{kt.current+=1}),[t,i,h]),l.useEffect(()=>{!N&&!Ee&&Ce&&f("properties")},[Ee,N,Ce]);async function yt(){const K=await h.loadDraft(t);return x(K),K}async function tt(K){at(null);try{const[re,je]=await Promise.all([h.loadSetup(t),h.loadDraft(t)]);b(re),x(je);const ue=Pr(je.draft);X(ue),f(me=>pf(je.draft,me)),j(K)}catch(re){j(is(re,K))}}async function Lt(K,re,je,ue={}){const{preserveBusyAction:me=!1}=ue;if(!i||!C||Ve&&!me)return null;me||Fe(K),j(null),at(null);try{const Ke=await re(C),ns=await yt();return E((Ke.warnings??[]).map((ot,bs)=>Ir(ot,bs,ns.draft?.authoring))),ns}catch(Ke){return cn(Ke)?await tt("This setup changed in another session. The latest draft is loaded; review your changes again."):j(is(Ke,je)),null}finally{me||Fe(null)}}const Qe=l.useMemo(()=>(ve?.authoring.targets??[]).map(K=>{const re=Po(K);return{id:K.stableKey,name:K.label,url:re[0]??"No URL",urls:re,state:gf(K.status)}}),[ve]),J=l.useMemo(()=>ve?.authoring.targets.filter(K=>K.status==="included")??[],[ve]),qe=l.useMemo(()=>J.map(K=>({id:K.stableKey,label:K.label,urlCount:Po(K).length})),[J]),Pe=ve?.authoring.assignments.length??0,Re=l.useMemo(()=>{if(!ve)return[];const K=new Set(s.map(ue=>ue.id)),re=s.map(ue=>({id:ue.id,text:ue.query,source:"saved-project-queries",propertyIds:Ns(ve.authoring.assignments.filter(me=>me.queryId===ue.id).map(me=>me.targetKey))})),je=Ns(ve.authoring.assignments.map(ue=>ue.queryId).filter(ue=>!K.has(ue))).map(ue=>({id:ue,source:"unavailable-tracked-query",state:"missing",propertyIds:Ns(ve.authoring.assignments.filter(me=>me.queryId===ue).map(me=>me.targetKey))}));return[...re,...je]},[s,ve]),Ht=l.useMemo(()=>(ve?.authoring.groups??[]).map(K=>({id:K.stableKey,name:K.label,propertyIds:K.targetKeys,competitors:K.competitors.map(re=>re.domain)})),[ve]),jt=l.useMemo(()=>{if(oe.length===0)return null;const K=Cf(I,qe.map(je=>je.id),oe);return(K.groupKeys?.length??K.targetKeys?.length??0)>0?K:null},[I,qe,oe]),Rt=jt?JSON.stringify(jt):"";l.useEffect(()=>{const K=jt,re=++Mt.current;if(!i||!Ee||!C||!K){le(null),ie(null),ne(null),Y(!1);return}le(null),ie(null),ne(null),Y(!0);const je=window.setTimeout(()=>{h.previewAssignments(t,K).then(ue=>{if(re===Mt.current){if(ue.draftEtag!==C){le(null),ie(null),ne("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}le(ue),ie(Rt)}}).catch(ue=>{re===Mt.current&&(le(null),ie(null),ne(cf(ue)))}).finally(()=>{re===Mt.current&&Y(!1)})},250);return()=>{window.clearTimeout(je),Mt.current+=1}},[jt,Rt,Z,i,Ee,C,t,h]);const qt=l.useMemo(()=>[...Pe===0?[{id:"no-query-assignments",title:"Assign at least one query",detail:"Apply a tracked query to at least one Property before publishing.",tone:"negative"}]:[],...ve?.authoring.assignments.some(K=>K.queryClass==="unclassified")&&!(Ce&&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"}]:[],...A],[Pe,Ce,o,A,ve]),xt=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 Et(K){let re;try{re=hf(K)}catch(ue){j(is(ue,"Check the sitemap details and try again."));return}F(K),B("reviewing");const je=await Lt("import",ue=>h.importSitemap(t,ue,re),"Could not review this sitemap.");if(je?.draft){const ue=je.draft.authoring.targets.filter(Ke=>Ke.status==="proposed").map(Ke=>Ke.stableKey),me=je.draft.authoring.targets.filter(Ke=>Ke.status==="included").map(Ke=>Ke.stableKey);X([...me,...ue]),G(""),ee(ko),f("properties"),B("idle")}else B("error")}async function ts(K){if(!c||K.length===0||Ve)return[];Fe("create-queries"),Ze(null);try{return await c(K)}catch(re){throw Ze(ft(re)),re}finally{Fe(null)}}async function rt(K){if(!Ee||!C||Ve)return;const re=new Set(K),ue=Ee.authoring.targets.filter(Ke=>Ke.status==="proposed"&&Ke.discoveryIdentity).map(Ke=>({discoveryIdentity:Ke.discoveryIdentity,action:re.has(Ke.stableKey)?"create":"ignore"})),me=ue.length>0||Ee.authoring.targets.some(Ke=>Ke.status!=="proposed"&&Ke.status==="included"!==re.has(Ke.stableKey));Fe("properties"),j(null),at(null);try{if(!me){X([...re]),$({kind:"all"}),f("groups");return}await h.applySitemapSelection(t,C,ue,[...re]);const Ke=await yt(),ns=Pr(Ke.draft);X(ns),$({kind:"all"}),f("groups")}catch(Ke){cn(Ke)?await tt("This setup changed in another session. The latest Properties are loaded."):j(is(Ke,"Could not save the selected Properties."))}finally{Fe(null)}}async function Vt(K){const re=K.groupIds&&K.groupIds.length>0?{groupKeys:zs(K.groupIds),queryIds:zs(K.queryIds)}:{targetKeys:zs(K.propertyIds),queryIds:zs(K.queryIds)};if(!te||pe!==JSON.stringify(re)||!C||te.draftEtag!==C){j("Review the latest assignment impact before assigning queries.");return}await Lt("assignments",ue=>h.applyAssignments(t,ue,re),"Could not apply these queries.")&&(k([]),De(`${te.assignments.added} new assignment${te.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function Nt(K){if(K.propertyIds.length===0)return;await Lt("replace-assignments",je=>h.replaceAssignments(t,je,{targetKeys:Ns(K.propertyIds),queryIds:[K.queryId]}),"Could not replace this query assignment.")&&(k(je=>je.filter(ue=>ue!==K.queryId)),De("Query assignments replaced."))}async function ss(K,re=!1){if(K.length===0)return;if(!await Lt("paired-assignments",ue=>h.applyPairedAssignments(t,ue,[...K]),"Could not assign these queries.",{preserveBusyAction:re}))throw new Error("Could not assign these queries.")}async function it(K){if(!(!i||!c||K.length===0||Ve)){Fe("create-and-pair-questions"),Ze(null);try{let re;try{re=await c(Ns(K.map(me=>me.text)))}catch(me){throw Ze(ft(me)),me}const je=new Map(re.map(me=>[me.query,me.id])),ue=K.map(me=>({targetKey:me.propertyId,queryId:je.get(me.text)})).filter(me=>me.queryId!==void 0);if(ue.length!==K.length){const me=new Error("The created queries could not be matched to their Properties.");throw Ze("The queries were added, but could not be paired with every Property. Try again to pair them."),me}try{await ss(ue,!0)}catch(me){throw Ze("The queries were added, but could not be assigned to their Properties. Try again to pair them."),me}}finally{Fe(null)}}}async function Dt(K){if(!Ee)return;const re=Ns(Ee.authoring.assignments.filter(ue=>ue.queryId===K).map(ue=>ue.targetKey));if(re.length===0)return;await Lt(`remove-${K}`,ue=>h.removeAssignment(t,ue,re,K),"Could not clear this query assignment.")&&k(ue=>ue.filter(me=>me!==K))}async function Wt(K){if(!Ee||!C||Ve)return;const re=K.name.trim();if(!re)return;const je=Je??Zr(re,"group"),ue=Ee.authoring.groups.find(ot=>ot.stableKey===je);if(ue&&Je===null){j(`A group named "${ue.label}" already exists. Edit it or choose a different name.`);return}const me=K.competitorDomains.split(/[\s,]+/).map(ot=>ot.trim()).filter(Boolean),Ke=me.find(ot=>Ro(ot)===null);if(Ke){j(`"${Ke}" is not a valid competitor domain.`);return}const ns=Ns(me.map(ot=>Ro(ot)));Fe("group"),j(null),at(null);try{const ot=await h.upsertGroup(t,C,{stableKey:je,label:re,targetKeys:Ns(K.propertyIds),competitors:ns.map(T=>ue?.competitors.find(xe=>xe.domain===T)??{stableKey:Zr(T,"competitor"),label:T,domain:T,aliases:[]})}),bs=await yt();E(ot.warnings.map((T,xe)=>Ir(T,xe,bs.draft?.authoring))),Se({...Bn}),Ue(null)}catch(ot){cn(ot)?await tt("This setup changed in another session. The latest groups are loaded."):j(is(ot,"Could not save this group."))}finally{Fe(null)}}function It(K){const re=Ee?.authoring.groups.find(je=>je.stableKey===K);re&&(Ue(K),Se({name:re.label,propertyIds:[...re.targetKeys],competitorDomains:re.competitors.map(je=>je.domain).join(", ")}))}async function hs(K){await Lt("remove-group",je=>h.removeGroup(t,je,K),"Could not remove this group.")&&($(je=>je.kind==="groups"&&je.groupIds.includes(K)?{kind:"all"}:je),Je===K&&(Ue(null),Se({...Bn})))}function Yt(K){ze(K),_(null),Xe(null),mt(null)}async function wt(){if(!(!i||!Be.trim()||U||Ie)){H(!0),Xe(null),mt(null);try{_(await h.previewGroupMembership(t,{csv:Be}))}catch(K){_(null),Xe(is(K,"Could not review this CSV."))}finally{H(!1)}}}async function As(K){if(!(!i||!C||!Oe||K.length===0||Ve)){if(Oe.draftEtag!==C){Xe("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}Ge(!0),Fe("group-import"),Xe(null),mt(null),at(null);try{const re=await h.applyGroupMembership(t,C,{csv:Be,sourceChecksum:Oe.sourceChecksum,previewChecksum:Oe.previewChecksum,acceptedRows:Ns(K.map(String)).map(Number)}),je=await yt();E(re.warnings.map((ue,me)=>Ir(ue,me,je.draft?.authoring))),ze(""),_(null),mt(`${re.addedMemberships} membership${re.addedMemberships===1?"":"s"} added${re.unchangedMemberships>0?`; ${re.unchangedMemberships} already present`:""}.`)}catch(re){cn(re)?(await tt("This setup changed in another session. The latest draft is loaded; review the CSV again."),Xe("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Xe(is(re,"Could not apply this CSV."))}finally{Fe(null),Ge(!1)}}}async function gt(){if(!(!Ee||!C||Ve||Pe===0)){Fe("review"),j(null),at(null);try{const[K,re]=await Promise.all([h.compilePreview(t),h.diffPreview(t)]),je=[...K.checks,...re.checks],ue=je.some(me=>me.ruleId==="active-revision-schema-v1");if(E(wf(je.filter(me=>me.ruleId!=="active-revision-schema-v1"),{authoring:ve?.authoring,queries:s})),!K.ok||!re.ok)return;if(re.diff.activeRevision!==Ee.baseActiveRevision){await tt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(K.compiledChecksum!==re.compiledChecksum){j("The setup changed while it was being reviewed. Review the latest changes again.");return}at({etag:C,baseActiveRevision:Ee.baseActiveRevision,compiledChecksum:K.compiledChecksum,changes:Sf(re.diff,ue),providerCalls:K.plan.executionNodes.reduce((me,Ke)=>me+Ke.expectedSnapshots,0)})}catch(K){j(is(K,"Could not review this setup."))}finally{Fe(null)}}}async function Ot(){if(!(!Ee||!C||!Ae||Ve)){if(C!==Ae.etag||Ee.baseActiveRevision!==Ae.baseActiveRevision){at(null),j("The setup changed after review. Review the latest changes before publishing.");return}Fe("publish"),j(null);try{await h.publish(t,C,{expectedActiveRevision:Ae.baseActiveRevision,expectedCompiledChecksum:Ae.compiledChecksum}),x({draft:null,etag:null}),at(null),u?.()}catch(K){cn(K)?await tt("The setup changed before it could be published. Review the latest draft and publish again."):j(is(K,"Could not publish this setup."))}finally{Fe(null)}}}async function ys(){if(!(!C||Ve)){Fe("discard"),j(null);try{await h.discard(t,C),x({draft:null,etag:null}),at(null),u?.()}catch(K){cn(K)?await tt("This setup changed in another session. The latest draft is loaded."):j(is(K,"Could not discard these changes."))}finally{Fe(null)}}}async function xs(){if(!(!Ee||!C||!m||Ve)){Fe("restart"),j(null),at(null);try{await h.discard(t,C),await h.createDraft(t,m.activeRevision),F({...Co}),G(""),X([]),k([]),$({kind:"all"}),le(null),ne(null),De(null),Se({...Bn}),Ue(null),ze(""),_(null),Xe(null),mt(null),await Ye(!1)}catch(K){cn(K)?await tt("The setup changed again. Reloaded the latest draft and published setup."):j(is(K,"Could not restart this setup."))}finally{Fe(null)}}}if(N)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(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Ye(!0)},children:"Try again"})]})]});if(!ve||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&&Ee&&m&&Ee.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(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:Ve==="restart",onClick:()=>{xs()},children:Ve==="restart"?"Restarting…":"Discard draft and restart"})]}),y?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:y}):null]});const zt=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:r,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[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,y?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:y}):null,zt,g==="import"||g==="properties"?e.jsx(Ta,{currentStep:g,hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{ys()},importProperties:{importDraft:D,onImportDraftChange:K=>{F(K),B("idle"),j(null)},onReviewSitemap:K=>{Et(K)},reviewState:V,properties:Qe,propertiesState:"ready",propertiesSearch:w,onPropertiesSearchChange:G,maxVisibleProperties:L,onShowAllProperties:()=>ee(Qe.length),selectedPropertyIds:O,onSelectedPropertyIdsChange:K=>X([...K]),onContinue:K=>{rt(K)},isContinuing:Ve==="properties",onRetryProperties:()=>{yt()},onReturnToImport:()=>f("import")}}):g==="queries"?e.jsx(Ta,{currentStep:"queries",hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{ys()},onManageProjectQueries:d,queries:{onCreateQueries:c?K=>ts(K):void 0,isCreatingQueries:Ve==="create-queries"||Ve==="create-and-pair-questions",isBusy:Ve!==null,createQueriesError:ht,availability:xt,properties:qe,queries:Re,selectedQueryIds:oe,isApplying:Ve==="assignments"||Ve==="paired-assignments",onSelectedQueryIdsChange:K=>k([...K]),onApplySelectedQueries:K=>Vt(K),groups:Ht,audience:I,onAudienceChange:K=>{$(K),De(null)},assignmentImpact:te&&pe===Rt?kf(te):null,isPreviewingAssignmentImpact:Ne,assignmentImpactError:z,onRetryAssignmentImpact:()=>be(K=>K+1),assignmentNotice:ce,onReplaceAssignments:Nt,isReplacingAssignments:Ve==="replace-assignments",onCreateAndPairQuestions:i&&c?it:void 0,onClearQueryAssignments:Dt,onRemoveQuery:Dt,canContinue:Pe>0,onBack:()=>f("groups"),onContinue:()=>f("review")}}):g==="groups"?e.jsx(Ta,{currentStep:"groups",hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{ys()},groups:{properties:qe,groups:Ht,groupDraft:we,isSaving:Ve==="group",onGroupDraftChange:Se,onSaveGroup:Wt,onEditGroup:K=>It(K.id),onRemoveGroup:hs,onClearGroupDraft:()=>{Ue(null),Se({...Bn})},membershipImport:{csv:Be,preview:Oe,isReviewing:U,isApplying:Ie,error:se,notice:ut,onCsvChange:Yt,onReview:wt,onApply:As},onBack:()=>{f("properties")},onContinue:()=>f("queries")}}):e.jsx(Ta,{currentStep:"review",hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{ys()},review:{counts:{properties:J.length,queries:new Set(ve.authoring.assignments.map(K=>K.queryId)).size,groups:ve.authoring.groups.length,assignments:ve.authoring.assignments.length,providerCalls:Ae?.providerCalls},flaggedExceptions:qt,reviewedChanges:Ae?.changes,isReviewing:Ve==="review",canReviewChanges:Pe>0&&!Ve,onReviewChanges:gt,onBack:()=>f("queries"),canPublish:Ae!==null&&!Ve,isPublishing:Ve==="publish",onPublish:Ot}})]})}const Rf=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function To(t){return t.label!=="Complete"}const dn="__all_properties__",If=50,Zl=50,$f=20,Tf=50,Mf=250,Lf=5,qf=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Ef={"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"},ec={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."},Df={numerator:null,denominator:null,reason:"plan_v1"};function Jn(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 Of(t){return Jn(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function tc(t){if(Jn(t))return"";const s=t.reason??"unavailable";return ec[s]??s}function Mo(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 Ff(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function Gf(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function Kf(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function Wn({metric:t,compact:s=!1}){const n=s?Jn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Jn(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",...Jn(t)?{}:{title:tc(t)},children:e.jsx("span",{className:n,children:Of(t)})})}function gi({shown:t,total:s,onShowAll:n,itemLabel:a}){return t>=s?null:e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",t," of ",s]}),e.jsxs(P,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Lo({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,o]=l.useState(Zl),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((c,d)=>e.jsx("li",{className:a,children:c},`${c}:${d}`))}),e.jsx(gi,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>o(Number.MAX_SAFE_INTEGER)})]})]})}function _f({evidence:t,state:s="ready",onRetry:n}){const[a,r]=l.useState(Zl),o=t.slice(0,a);return e.jsxs("section",{"aria-label":"Evidence",children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:"Evidence"}),s==="loading"?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Loading evidence…"}):s==="error"?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsx("span",{children:"Evidence could not be loaded."}),n?e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:n,children:"Retry evidence"}):null]}):t.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"No source evidence is available."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[640px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children:o.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(de,{tone:i.tone,children:Ef[i.kind]}),i.historical?e.jsx(de,{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(gi,{shown:o.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function Uf({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Lo,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Lo,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(_f,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function Bf({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(Wn,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function qo({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function o(i){if(r)return;const c=n.findIndex(h=>h.value===s);let d=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?d=(c+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?d=(c-1+n.length)%n.length:i.key==="Home"?d=0:i.key==="End"&&(d=n.length-1),d===null)return;i.preventDefault();const u=n[d];a(u.value),i.currentTarget.querySelectorAll('[role="radio"]')[d].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:o,children:n.map(i=>{const c=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":c,tabIndex:c?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${c?"segmented-option-active":""}`,children:i.label},i.value)})})}function Vf({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(_e,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function zf({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:o=!1,isViewLoading:i=!1,isLoadingMore:c=!1,isLoadMoreError:d=!1,viewSearch:u,onViewChange:h,onLoadMore:m,onPropertyExpand:b,onRetryEvidence:p,renderPropertyLink:x}){const g=t.currentView!=null,f=t.classReporting==="available"&&(g||t.classScopes!=null),[N,S]=l.useState(t.currentView?.queryClass??"all"),[q,R]=l.useState(t.currentView?.scope.key??dn),[y,j]=l.useState(u??""),[A,E]=l.useState(If),[D,F]=l.useState($f),[V,B]=l.useState(t.currentView?.sort??"label-asc"),[w,G]=l.useState(null),L=l.useRef(u??""),ee=f&&!g&&N!=="all"?N==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,O=g?{aggregate:t.currentView.aggregate,groups:[]}:ee,X=l.useCallback(_=>{if(!g||!h)return;const U=_.scope??(q===dn?"all":"group"),H=_.search??y;L.current=H,h({scope:U,...U==="group"?{groupKey:_.groupKey??q}:{},queryClass:_.queryClass??N,...H?{search:H}:{},..._.sort?{sort:_.sort}:{}})},[h,y,N,q,g]);l.useEffect(()=>{!t.currentView||i||(S(t.currentView.queryClass),R(t.currentView.scope.key??dn),t.currentView.sort&&B(t.currentView.sort))},[i,t.currentView]),l.useEffect(()=>{u!==void 0&&(L.current=u,j(_=>_.trim()===u.trim()?_:u))},[u]),l.useEffect(()=>{if(!g||!h||y===L.current)return;const _=window.setTimeout(()=>X({search:y}),Mf);return()=>window.clearTimeout(_)},[h,X,y,g]);const oe=t.availableGroups??O.groups;l.useEffect(()=>{q===dn||oe.some(_=>_.id===q)||R(dn)},[oe,q]);const k=g?void 0:O.groups.find(_=>_.id===q),I=k?.aggregate??O.aggregate,$=_=>f?_:Df,te=V,le=y.trim().toLocaleLowerCase(),pe=l.useMemo(()=>!g&&le?I.properties.filter(_=>_.name.toLocaleLowerCase().includes(le)):I.properties,[I.properties,le,g]),ie=g?pe:pe.slice(0,A),Ne=(g?t.currentView?.scope.kind==="group":k!=null)&&N==="non-brand"&&f&&(g||k.confirmedCompetitorCount>0)&&(I.shareOfVoice?.length??0)>0,Y=f?I.unavailablePropertyCount??0:0,z=t.flaggedResults.reduce((_,U)=>_+(U.count??1),0),ne=t.flaggedResultsTotal??z,Z=[$(I.metrics.propertiesMentioned),$(I.metrics.mentionCoverage),$(I.metrics.citationCoverage)].map(tc).find(Boolean),be=f?t.nextActionText??Z??(Y>0?`${Y} ${Y===1?"property is":"properties are"} unavailable.`:ne>0?`${ne} flagged ${ne===1?"result needs":"results need"} review.`:null):ec.plan_v1,we=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?Ff(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Se=Gf(t.latestMeasurement.date),Je=[{value:dn,label:"All properties"},...oe.map(_=>({value:_.id,label:_.label}))],Ue=oe.length>Lf;function Be(_){R(_),X(_===dn?{scope:"all"}:{scope:"group",groupKey:_})}function ze(_){S(_),X({queryClass:_})}function Oe(_){const U=w!==_;G(U?_:null),U&&b?.(_)}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(de,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(de,{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,be?e.jsx("span",{className:"text-sm text-secondary",children:be}):null,s&&f&&n?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!f?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||o,children:o?"Opening setup…":"Republish setup"}):null]})})}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4 border-b border-default pb-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-group-label",htmlFor:Ue?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),Ue?e.jsx("select",{id:"advanced-measurement-group",value:q,onChange:_=>Be(_.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:Je.map(_=>e.jsx("option",{value:_.value,children:_.label},_.value))}):e.jsx(qo,{ariaLabelledBy:"advanced-measurement-group-label",value:q,options:Je,onChange:Be})]}),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(qo,{ariaLabelledBy:"advanced-measurement-class-label",value:N,options:qf,onChange:ze,disabled:!f})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:y,onChange:_=>j(_.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&&Ne?e.jsx(Bf,{values:I.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(_e,{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??pe.length," ",(t.currentView?.propertyTotal??pe.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(Vf,{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:[Rf.map(_=>{const U=te.startsWith(`${_.key}-`),H=U&&te.endsWith("-desc")?"descending":U?"ascending":"none";return e.jsx("th",{"aria-sort":H,className:(_.numeric,void 0),children:h?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const Ie=`${_.key}-${U&&te.endsWith("-asc")?"desc":"asc"}`;B(Ie),X({sort:Ie})},"aria-label":`Sort by ${_.label.toLowerCase()}`,children:[_.label,e.jsx(gn,{className:`h-3 w-3 transition-transform ${U?"opacity-100":"opacity-0"} ${H==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):_.label},_.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[ie.map(_=>{const U=w===_.id;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:H=>{Kf(H.target)||Oe(_.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[x?x({id:_.id,name:_.name}):_.name,To(_.status)||_.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[To(_.status)?e.jsx(de,{tone:_.status.tone,children:_.status.label}):null,_.historical?e.jsx(de,{tone:"caution",children:"Historical"}):null]}):null,Mo(_)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Mo(_)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(Wn,{metric:_.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Wn,{metric:_.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{size:"icon",variant:"ghost","aria-expanded":U,"aria-label":U?`Hide details for ${_.name}`:`Show details for ${_.name}`,onClick:()=>Oe(_.id),children:e.jsx(gn,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${U?"rotate-180":""}`,"aria-hidden":"true"})})})]},_.id),U?(_.providers??[]).map(H=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:H.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(Wn,{metric:H.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Wn,{metric:H.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${_.id}:${H.provider}`)):null,U?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(Uf,{property:_,onRetryEvidence:p})})},`${_.id}:details`):null]},_.id)}),ie.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"py-8 text-center text-sm text-secondary",children:"No properties match this search."})}):null]})]})}),g&&t.currentView.nextCursor&&m?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",ie.length," of ",t.currentView.propertyTotal]}),d?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(P,{size:"sm",variant:"outline",disabled:c,onClick:()=>m(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more properties":"Show 50 more"})]}):g?ie.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",ie.length," of ",t.currentView.propertyTotal]}):null:e.jsx(gi,{shown:ie.length,total:pe.length,itemLabel:"properties",onShowAll:()=>E(Number.MAX_SAFE_INTEGER)})]}),!i&&!le&&ne>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 (",ne,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,D).map(_=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(de,{tone:_.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:_.property}),e.jsx("span",{className:"text-secondary",children:_.summary})]},_.id))}),D<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,D).reduce((_,U)=>_+(U.count??1),0)," of ",ne," flagged results"]}),e.jsx(P,{size:"sm",variant:"outline",onClick:()=>F(_=>Math.min(t.flaggedResults.length,_+Tf)),children:"Show 50 more"})]}):z<ne?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",z," of ",ne," flagged results"]}),g&&t.currentView.nextCursor&&m?e.jsx(P,{size:"sm",variant:"outline",disabled:c,onClick:()=>m(t.currentView.nextCursor),children:c?"Loading…":d?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function sc(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function Qf(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 Hf({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:o,onRunMeasurement:i,onRetryReport:c,onViewChange:d,onLoadMore:u,onPropertyExpand:h,onRetryEvidence:m,renderPropertyLink:b,isRunningMeasurement:p,isOpeningSetup:x,isViewLoading:g,isLoadingMore:f,isLoadMoreError:N,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(P,{type:"button",size:"sm",disabled:x,onClick:o,children:x?"Opening setup…":sc(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,r==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):r==="error"&&!a?e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load the advanced measurement report."}),c?e.jsx(P,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:c,children:"Retry report"}):null]}):a?e.jsx(zf,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:o,onViewChange:d,onLoadMore:u,onPropertyExpand:h,onRetryEvidence:m,renderPropertyLink:b,isRunningMeasurement:p,isRepublishingSetup:x,isViewLoading:g,isLoadingMore:f,isLoadMoreError:N,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 Wf(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Eo(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function Yf(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function Jf(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Xf(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 Zf(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function ey(t){const s=new Map;for(const n of t){const a=Zf(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function ty(t,s){if(t.plan.schemaVersion!==1)throw new Error("Version-one report adapter received a different setup version.");const n=t.plan,a=new Map(n.targets.map(x=>[x.stableKey,x])),r=new Map(n.querySnapshots.map(x=>[x.queryId,x.queryText])),o=new Map;for(const x of n.targetQuerySelections){const g=o.get(x.targetKey)??[];g.push(...x.queryIds.map(f=>r.get(f)).filter(f=>!!f)),o.set(x.targetKey,[...new Set(g)])}const i=ey(s.evidence),c=n.executionNodes.reduce((x,g)=>x+g.expectedSnapshots,0),d=s.run?.status==="completed"&&c>0,u=d?c:0,h=d?c:0,m=s.targets.map(x=>{const g=a.get(x.id),f=i.get(x.id)??[],N=f.map(R=>({id:`${R.observationId}:${R.usageEdgeId}:${R.sourceUrl}`,kind:Yf(R.classification),query:R.queryText,url:R.sourceUrl,tone:Jf(R.classification),historical:R.historical||R.bridged})),S=f.some(R=>R.historical||R.bridged),q=s.run?x.completeness.complete?g?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${x.completeness.executed} of ${x.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:x.id,name:x.label,mentionCoverage:Eo(x.mentionCoverage),citationCoverage:Eo(x.citationCoverage),status:q,assignedQueries:o.get(x.id)??[],urls:g?.urls.map(Wf)??[],evidence:N,historical:S}}),b=new Map(m.map(x=>[x.id,x])),p=new Map(n.groups.map(x=>[x.stableKey,x]));return{classReporting:"plan-v1",latestMeasurement:{status:s.run?.status==="completed"?{label:"Complete",tone:"positive"}:s.run?.status==="partial"?{label:"Partial result",tone:"caution"}:{label:"Not measured",tone:"neutral"},completedSlots:u,totalSlots:h,date:Xf(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(x=>({id:x.id,label:x.label,confirmedCompetitorCount:p.get(x.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Cn,mentionCoverage:Cn,citationCoverage:Cn},properties:x.targetIds.map(g=>b.get(g)).filter(g=>!!g)}}))},flaggedResults:[]}}const sy={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function vt(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 ny(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 ay(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function ry({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[o,i]=l.useState(mu),c=$e({...hu({client:W,path:{name:t},query:{period:o}}),placeholderData:ei});async function d(){n(!0),r(null);try{await pu(t,"client",o)}catch(h){const m=h instanceof pn||h instanceof Error?h.message:"Download failed";r(m)}finally{n(!1)}}if(c.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(c.error){const h=c.error instanceof Error?c.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-negative-400",children:h})})}const u=c.data;return u?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:u.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[u.meta.project.canonicalDomain," · ",u.meta.project.country," / ",u.meta.project.language.toUpperCase(),u.meta.location?` · Location: ${ay(u.meta.location)}`:" · No location set"," · ","Last ",u.meta.periodDays," days"," · ","Generated ",ny(u.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(oy,{period:o,onChange:i}),e.jsxs(P,{variant:"secondary",size:"sm",onClick:He(d),disabled:s,children:[e.jsx(dl,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(xy,{report:u}),e.jsx(iy,{report:u}),e.jsx(vy,{report:u,audience:"client"}),e.jsx(dy,{report:u}),e.jsx(fy,{report:u,audience:"client",projectName:t}),e.jsx(yy,{report:u})]}):null}function iy({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:gu(n.percent,n.queryClass,n)}),n.reason?e.jsx("p",{children:zo(n.reason)}):null]},n.queryClass):null)})}function oy({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:xu.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 Do="AI Visibility — Server-Side",Oo="AI engine attention",ly=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,cy="Live telemetry from your server logs.";function dy({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(na,{eyebrow:Oo,title:Do,subtitle:cy}),e.jsx("p",{className:"text-sm text-muted",children:"Your server-side traffic source is connected. Numbers will appear after the next sync."})]});const n={current:s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,prior:s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior,deltaPct:Wm(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,r=`vs prior ${a} days`,o=nr(n,"requests",r),i=`${vt(s.verifiedCrawlerHits.current)} verified · ${vt(s.unverifiedCrawlerHits.current)} unverified${o?` · ${o}`:""}`,c=nr(s.aiUserFetchHits,"requests",r),d=nr(s.referralArrivals,"sessions",r),u=s.referralRedirects>0?`${vt(s.referralRedirects)} blocked by redirects`:"",h=[d,s.referralArrivalsClassSummary,u].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(na,{eyebrow:Oo,title:Do,subtitle:ly(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Mr,{label:"AI bot requests observed",value:vt(n.current),subtitle:i}),e.jsx(Mr,{label:"AI user-fetch requests",value:vt(s.aiUserFetchHits.current),subtitle:c||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(Mr,{label:"AI referral sessions",value:vt(s.referralArrivals.current),subtitle:h})]}),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:vt(b.verifiedHits+b.unverifiedHits)}),e.jsx("td",{children:vt(b.userFetchHits)}),e.jsx("td",{children:vt(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 uy(t,s){return t.audience==="both"||t.audience===s}const my={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function za(t){return my[t]??t.charAt(0).toUpperCase()+t.slice(1)}function hy(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 xy({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,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 answers"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer queries about your business.",i=hy(t.whatsChanged.mentionRate),c=n.providers.length>0?n.providers.map(za).join(", "):`${vt(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($r,{label:"AI mentions your name",value:`${s.mentionRate}%`,subtitle:a>0?`Says your name in ${s.mentionedQueryCount} of ${a} ${a===1?"answer":"answers"}`:"No data yet"}),e.jsx($r,{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?"answer":"answers"}`:"No data yet"}),e.jsx($r,{label:"AI tools tested",value:vt(s.providerCount),subtitle:c})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-bg/40 px-4 py-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-semibold text-strong",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-strong",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-strong",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Customer queries we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["These are the ",n.queries.length," ",n.queries.length===1?"query we asked":"queries we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((d,u)=>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(u+1).padStart(2,"0")}),e.jsxs("span",{children:['"',d,'"']})]},u))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"How often each AI tool mentions you"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Higher is better. Each bar shows the share of customer queries where the AI named you in the answer."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(d=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:za(d.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-positive-500/70",style:{width:`${Math.max(d.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[d.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",d.mentionedCount,"/",d.totalCount,")"]})]})]},d.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((d,u)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:d},u))})]})}function $r({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 py(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function gy(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function fy({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=>uy(m,s)),r=th(t,a),o=s==="client",i=fu(),[c,d]=l.useState(new Set),u=c.size>0?r.filter(m=>!m.targetRef||!c.has(m.targetRef)):r,h=m=>{if(!m.targetRef)return;const b=m.targetRef;d(p=>new Set(p).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:p=>{Te({tone:"negative",title:`Couldn't dismiss "${m.title}"`,detail:String(p)}),d(x=>{const g=new Set(x);return g.delete(b),g})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(na,{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."}),u.length===0?e.jsx(bi,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:u.map((m,b)=>{const p=m.evidence.length>0?m.evidence:m.why,x=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(de,{tone:bu(m),children:o?py(m.horizon):yu(m.horizon)}),!o&&e.jsx(de,{tone:"neutral",children:vu(m.category)}),e.jsx(de,{tone:"neutral",children:o?gy(m.confidence):`${ju(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(jy,{items:p,limit:3,className:"mt-3"}),x&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:o?"See the data behind this":"Evidence details"}),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((g,f)=>e.jsx("li",{children:g},f))})]}),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((g,f)=>e.jsx("li",{children:g},f))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:o?"What success looks like:":"Win condition:"})," ",m.successMetric]}),m.targetRef&&!ae()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>h(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 Fo({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 yy({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=sh(t).slice(0,5),o=s.length>0?Math.max(...s.map(d=>d.count)):0,i=n?Math.max(...n.topQueries.slice(0,5).map(d=>d.impressions),1):0,c=s.length>0||n!==null||a!==null||r.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(na,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),c?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"The websites AI tools cited most often when answering customer queries about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(d=>e.jsx(Fo,{label:d.domain+(d.isCompetitor?" (competitor)":""),value:d.count,displayValue:`${vt(d.count)}×`,max:o,barClass:"bg-mono-400/70"},d.domain))})]}),a&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${a.indexedPct>=90?"text-positive-400":a.indexedPct>=70?"text-caution-400":"text-negative-400"}`,children:[a.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[vt(a.indexed)," of ",vt(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:vt(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:vt(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:vt(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(d=>e.jsx(Fo,{label:d.query,value:d.impressions,displayValue:`${vt(d.impressions)} ${d.impressions===1?"search":"searches"}`,max:i,barClass:"bg-info-500/70"},d.query))})]}),r.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Customer queries where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:r.map((d,u)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:d.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[Nu(d.action),d.winnabilityClass==="ceded"&&e.jsx(de,{tone:"caution",children:"Ceded surface"})]})]},u))})]})]}):e.jsx(bi,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function fi(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function yi(t){return t==="up"?"↑":t==="down"?"↓":"→"}function Tr({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=fi(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}%`:Ym(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:yi(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function Go({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=fi(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=Jm(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:[vt(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:yi(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function by({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=fi(r.direction),c=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?za(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:c,children:[o,r.deltaAbs.toFixed(1),"% ",yi(r.direction)]})]},r.provider)})})]})})]})}function Ko({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(de,{tone:sy[o.severity],children:wu(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?za(o.provider):o.provider})]},o.id))})]})})]})}function vy({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(na,{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(bi,{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(Tr,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(Tr,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(Tr,{label:a?"Queries AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(Go,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(Go,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(by,{movements:n.providerMovements,audience:s}),e.jsx(Ko,{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(Ko,{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 Mr({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 na({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 jy({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 bi({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function Ny({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(null),[u,h]=l.useState(t.displayName),[m,b]=l.useState(t.canonicalDomain),[p,x]=l.useState(t.country),[g,f]=l.useState(t.language),[N,S]=l.useState(t.ownedDomains??[]),[q,R]=l.useState(""),[y,j]=l.useState(t.aliases??[]),[A,E]=l.useState(""),[D,F]=l.useState(null),[V,B]=l.useState(!1),[w,G]=l.useState(!1),[L,ee]=l.useState(""),[O,X]=l.useState(""),[oe,k]=l.useState(""),[I,$]=l.useState(""),[te,le]=l.useState(""),[pe,ie]=l.useState(null),[Ne,Y]=l.useState(null);l.useEffect(()=>{a||(h(t.displayName),b(t.canonicalDomain),x(t.country),f(t.language),S(t.ownedDomains??[]),j(t.aliases??[]))},[t,a]);function z(){r(!1),d(null),h(t.displayName),b(t.canonicalDomain),x(t.country),f(t.language),S(t.ownedDomains??[]),j(t.aliases??[]),R(""),E("")}function ne(){const U=q.trim();U&&(N.includes(U)||S([...N,U]),R(""))}function Z(U){S(N.filter(H=>H!==U))}function be(){const U=A.trim();if(!U)return;const H=U.toLowerCase();y.some(Ie=>Ie.toLowerCase()===H)||j([...y,U]),E("")}function ce(U){j(y.filter(H=>H!==U))}async function De(){if(!(!u.trim()||!m.trim()||!p.trim()||!g.trim())){i(!0),d(null);try{await s(t.name,{displayName:u.trim(),canonicalDomain:m.trim(),ownedDomains:N,aliases:y,country:p.trim(),language:g.trim()}),r(!1),Te({title:"Project settings saved",detail:`${u.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(U){d(U instanceof Error?U.message:"Failed to save")}finally{i(!1)}}}async function we(){const U=L.trim(),H=O.trim(),Ie=oe.trim(),Ge=I.trim();if(!(!U||!H||!Ie||!Ge)){B(!0),F(null);try{const se={label:U,city:H,region:Ie,country:Ge};te.trim()&&(se.timezone=te.trim()),await ku(t.name,se),n(),ee(""),X(""),k(""),$(""),le(""),G(!1),Te({title:"Location added",detail:`${U} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${U}`,dedupeMode:"drop"})}catch(se){F(se instanceof Error?se.message:"Failed to add location")}finally{B(!1)}}}async function Se(U){B(!0),F(null);try{await Cu(t.name,U),n(),Te({title:"Location removed",detail:`${U} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${U}`,dedupeMode:"drop"})}catch(H){F(H instanceof Error?H.message:"Failed to remove location")}finally{B(!1)}}async function Je(U){B(!0),F(null);try{await Su(t.name,U),n(),Te({title:"Default location updated",detail:`${U} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(H){F(H instanceof Error?H.message:"Failed to set default location")}finally{B(!1)}}async function Ue(U){ie(U),Y(null);try{await Au(t.name,U),Te({title:`${U.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(H){Y(H instanceof Error?H.message:"Could not download tracking results.")}finally{ie(null)}}const Be=u!==t.displayName||m!==t.canonicalDomain||p!==t.country||g!==t.language||JSON.stringify(N)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(y)!==JSON.stringify(t.aliases??[]),ze="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",Oe="mb-1 block text-sm font-medium text-secondary",_=L.trim()&&O.trim()&&oe.trim()&&I.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"})]}),!ae()&&!a&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),c&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[c,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>d(null),children:"×"})]}),!ae()&&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:Oe,children:"Display name"}),e.jsx("input",{className:ze,type:"text",value:u,onChange:U=>h(U.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Oe,children:"Canonical domain"}),e.jsx("input",{className:ze,type:"text",value:m,onChange:U=>b(U.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Oe,children:"Country"}),e.jsx("input",{className:ze,type:"text",value:p,onChange:U=>x(U.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Oe,children:"Language"}),e.jsx("input",{className:ze,type:"text",value:g,onChange:U=>f(U.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Oe,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:N.map(U=>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:[U,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Z(U),"aria-label":`Remove ${U}`,children:"×"})]},U))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${ze} flex-1`,type:"text",placeholder:"docs.example.com",value:q,onChange:U=>R(U.target.value),onKeyDown:U=>U.key==="Enter"&&(U.preventDefault(),ne())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!q.trim(),onClick:ne,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Oe,children:"Aliases"}),e.jsx("p",{className:"mb-1.5 text-sm text-secondary",children:"Other brand names that may appear in answers."}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:y.map(U=>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:[U,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>ce(U),"aria-label":`Remove ${U}`,children:"×"})]},U))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${ze} flex-1`,type:"text",placeholder:"Facebook",value:A,onChange:U=>E(U.target.value),onKeyDown:U=>U.key==="Enter"&&(U.preventDefault(),be())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!A.trim(),onClick:be,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(P,{type:"button",disabled:o||!Be||!u.trim()||!m.trim(),onClick:He(De),children:o?"Saving...":"Save changes"}),e.jsx(P,{type:"button",variant:"outline",disabled:o,onClick:z,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(U=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:U},U))}):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(U=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:U},U))}):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:[D&&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:[D,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>F(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-faint",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(U=>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 ${U.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[U.label,U.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:U.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:U.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:U.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:U.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!ae()&&U.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:V,onClick:()=>{Je(U.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${U.label} as default location`,children:"Set default"}),!ae()&&e.jsx("button",{type:"button",disabled:V,onClick:()=>{Se(U.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${U.label}`,children:"Remove"})]})})]},U.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),ae()?null:w?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:ze,type:"text",value:L,onChange:U=>ee(U.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:ze,type:"text",value:O,onChange:U=>X(U.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:ze,type:"text",value:oe,onChange:U=>k(U.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:ze,type:"text",value:I,onChange:U=>$(U.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:ze,type:"text",value:te,onChange:U=>le(U.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(P,{type:"button",size:"sm",disabled:V||!_,onClick:He(we),children:V?"Adding...":"Add location"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:V,onClick:()=>{G(!1),F(null)},children:"Cancel"})]})]}):e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>G(!0),children:"+ Add location"})]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted",children:"Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"max-w-xl text-xs leading-5 text-muted",children:"Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:pe!==null,onClick:He(()=>Ue("csv")),children:pe==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:pe!==null,onClick:He(()=>Ue("json")),children:pe==="json"?"Preparing JSON...":"Download JSON"})]})]}),Ne&&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:Ne})]})]})]})}function Vn(t){return{...t??{}}}function wy(t,s){const n=Object.entries(t).sort(([r],[o])=>r.localeCompare(o)),a=Object.entries(s).sort(([r],[o])=>r.localeCompare(o));return n.length===a.length&&n.every(([r,o],i)=>{const c=a[i];return c?.[0]===r&&c[1]===o})}function Sy({project:t,onSave:s}){const{isAdmin:n}=Ln(),a=$e({queryKey:["settings"],queryFn:Jo,staleTime:6e4,enabled:n&&!ae()}),[r,o]=l.useState(t.providers.length===0),[i,c]=l.useState(t.providers),[d,u]=l.useState(()=>Vn(t.providerModels)),[h,m]=l.useState({providers:t.providers,providerModels:Vn(t.providerModels)}),[b,p]=l.useState(!1),[x,g]=l.useState(!1),[f,N]=l.useState(null),[S,q]=l.useState(null),R=l.useRef(null),y=a.data?.providerCatalog??[],j=l.useMemo(()=>new Set((a.data?.providers??[]).filter(G=>G.configured).map(G=>G.name)),[a.data]),A=l.useMemo(()=>{const G=new Map(a.data?.providers.map(ee=>[ee.name,ee.model])),L=new Map(y.map(ee=>[ee.name,{...ee,defaultModel:G.get(ee.name)||ee.defaultModel}]));for(const ee of Object.keys(d))L.has(ee)||L.set(ee,{name:ee,displayName:ee,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...L.values()].sort((ee,O)=>ee.displayName.localeCompare(O.displayName))},[y,d,a.data?.providers]),E=!wy(d,h.providerModels);l.useEffect(()=>{if(b||x)return;const G={providers:t.providers,providerModels:Vn(t.providerModels)};m(G),o(G.providers.length===0),c(G.providers),u(G.providerModels)},[t]);function D(){g(!0),o(!1),i.length===0&&c([...j])}function F(G,L,ee=!1){g(!0),u(O=>{const X={...O};return L==="__inherit__"?delete X[G]:L==="__custom__"?X[G]=ee?"":X[G]??"":X[G]=L,X}),L==="__custom__"&&queueMicrotask(()=>R.current?.focus())}function V(G,L){g(!0),c(ee=>L?[...new Set([...ee,G])]:ee.filter(O=>O!==G))}function B(){g(!1),o(h.providers.length===0),c(h.providers),u(Vn(h.providerModels)),N(null),q(null)}async function w(){if(!(a.isError||a.isLoading||!r&&i.length===0)){p(!0),N(null),q(null);try{const G=Object.fromEntries(Object.entries(d).filter(([ee,O])=>O.trim()!==""&&(r||i.includes(ee)))),L={providers:r?[]:i,providerModels:G};await s(L),m({providers:[...L.providers],providerModels:Vn(L.providerModels)}),g(!1),q("Engine settings saved. They apply on the next sweep.")}catch(G){N(Xn(G))}finally{p(!1)}}}return ae()||!n?null:a.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):a.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):y.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):j.size===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsxs("p",{className:"text-sm text-secondary",children:["Configure an answer engine in ",e.jsx(ks,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":b,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Execution"}),e.jsx("h2",{children:"Answer engines"})]}),e.jsx("p",{className:"supporting-copy",children:"Changes apply on the next sweep."})]}),e.jsxs("fieldset",{disabled:b,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:r,onChange:()=>{g(!0),o(!0)}})," All configured engines"]}),e.jsx("p",{className:"project-engine-help",children:"Includes engines configured later in global Settings."}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:!r,onChange:D})," Choose engines"]}),!r&&e.jsx("div",{className:"project-engine-list",children:A.map(G=>{const L=i.includes(G.name),ee=j.has(G.name),O=L&&!ee,X=d[G.name],oe=G.knownModels.some(I=>I.id===X),k=X===void 0?"__inherit__":oe?X:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:L,disabled:!ee&&!L,onChange:I=>V(G.name,I.target.checked)})," ",e.jsx("span",{children:G.displayName}),O&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),L&&(G.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${G.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${G.name}`,value:k,onChange:I=>F(G.name,I.target.value,oe),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",G.defaultModel||"default"]}),G.knownModels.map(I=>e.jsx("option",{value:I.id,children:I.displayName},I.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),k==="__custom__"&&e.jsx("input",{ref:R,"aria-label":`${G.displayName} custom model ID`,value:X??"",onChange:I=>{g(!0),u($=>({...$,[G.name]:I.target.value}))},"aria-describedby":`project-model-hint-${G.name}`}),e.jsxs("p",{id:`project-model-hint-${G.name}`,className:"project-engine-help",children:[X?"Project override":"Inherited from instance settings",". ",G.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},G.name)})})]}),!r&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),f&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:f}),S&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:S}),E&&e.jsx("p",{className:"project-engine-warning",children:"Applies on the next sweep. Existing history remains visible. If the recorded model changes, month-to-month comparison may exclude that engine."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{type:"button",onClick:()=>{w()},disabled:b||!r&&i.length===0,children:b?"Saving engines…":"Save engines"}),e.jsx(P,{type:"button",variant:"outline",onClick:B,disabled:b,children:"Cancel"})]})]})}const Cy=[{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"}],_o=["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 Lr(t,s){const n=s==="UTC"?"UTC":s.split("/").pop()?.replace(/_/g," ")??s,a=new Date(`${t.startDate}T00:00:00Z`),r=Number.isNaN(a.getTime())?t.startDate:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(a),[o,i]=t.time.split(":").map(Number),c=Number.isInteger(o)&&Number.isInteger(i)?new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",timeZone:"UTC"}).format(new Date(Date.UTC(1970,0,1,o,i))):t.time;return`Every ${t.everyDays} days starting ${r} at ${c} · ${n}`}function ky({projectName:t}){const s=Ut(),n=!ae()&&!s,a=ms(),[r,o]=l.useState(!1),[i,c]=l.useState("daily"),[d,u]=l.useState(6),[h,m]=l.useState(""),[b,p]=l.useState(14),[x,g]=l.useState(""),[f,N]=l.useState("00:00"),[S,q]=l.useState("UTC"),[R,y]=l.useState(!1),[j,A]=l.useState(""),[E,D]=l.useState(!1),[F,V]=l.useState(!1),[B,w]=l.useState(null),[G,L]=l.useState(void 0),ee=Pu({client:W,path:{name:t}}),O=$e({...nl({client:W,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),X=O.isPending||O.isFetching,oe=O.isError,k=O.data?.find(Z=>Z.kind==="answer-visibility")??null,I=r&&G!==void 0&&(k?.updatedAt??null)!==G,$=Z=>{a.setQueryData(ee,be=>{const ce=(be??[]).filter(De=>De.kind!=="answer-visibility");return Z?[...ce,Z]:ce})},te=Z=>{if(Z){if(Z.recurrence)c("calendar"),p(Z.recurrence.everyDays),g(Z.recurrence.startDate),N(Z.recurrence.time);else{const ce=Tu(Z.preset??null,Z.cronExpr);c(ce.freq),u(ce.hour),m(ce.customCron)}const be=_o.includes(Z.timezone);q(be?Z.timezone:"Other"),y(!be),A(be?"":Z.timezone)}else c("daily"),u(6),m(""),p(14),g(""),N("00:00"),q("UTC"),y(!1),A("");L(Z?.updatedAt??null)},le=()=>{n&&(te(k),w(null),o(!0))},pe=()=>{te(k),w(null)},ie=async()=>{(await O.refetch()).isError?w("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):w(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},Ne=async(Z,be)=>{if(Z instanceof pn&&Z.code==="SCHEDULE_VERSION_CONFLICT"){await ie();return}w(Z instanceof Error?Z.message:be)},Y=async()=>{if(n&&!(I||G===void 0)){D(!0),w(null);try{const Z=await O.refetch();if(Z.isError||Z.data===void 0){w("Canonry could not verify the latest schedule. Try again before saving.");return}if(((Z.data.find(Se=>Se.kind==="answer-visibility")??null)?.updatedAt??null)!==G)return;const De={timezone:R?j.trim()||"UTC":S,expectedUpdatedAt:G};i==="calendar"?De.recurrence={everyDays:b,startDate:x,time:f}:i==="custom"?De.cron=h.trim():De.preset=$u(i,d);const we=await Ci(t,De);o(!1),L(void 0),$(we),Te({title:"Schedule saved",detail:we.recurrence?Lr(we.recurrence,we.timezone):tr(we.preset??null,we.cronExpr,we.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(Z){await Ne(Z,"Failed to save schedule")}finally{D(!1)}}},z=async()=>{if(!n||!k)return;const Z=k.updatedAt;D(!0),w(null);try{const be=await O.refetch();if(be.isError||be.data===void 0){w("Canonry could not verify the latest schedule. Try again before updating it.");return}const ce=be.data.find(Se=>Se.kind==="answer-visibility")??null;if(!ce||ce.updatedAt!==Z){w("This schedule changed elsewhere. Review the latest version and try again.");return}const De={timezone:ce.timezone,enabled:!ce.enabled,expectedUpdatedAt:Z};ce.recurrence?De.recurrence=ce.recurrence:ce.preset?De.preset=ce.preset:De.cron=ce.cronExpr;const we=await Ci(t,De);$(we),Te({title:we.enabled?"Schedule resumed":"Schedule paused",detail:we.recurrence?Lr(we.recurrence,we.timezone):tr(we.preset??null,we.cronExpr,we.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(be){await Ne(be,"Failed to update schedule")}finally{D(!1)}},ne=async()=>{if(!n||!k)return;const Z=k.updatedAt;V(!0),w(null);try{await Iu(t,Z),$(null),o(!1),L(void 0),Te({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(be){await Ne(be,"Failed to remove schedule")}finally{V(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),n&&!X&&!oe&&!r&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:le,children:k?"Edit schedule":"+ Set schedule"})]}),X&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),B&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:B}),!X&&oe&&e.jsxs(fe,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{O.refetch()},children:"Retry"})]}),!X&&!oe&&!r&&k===null&&e.jsx(fe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?Js:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!X&&!oe&&!r&&k!==null&&e.jsx(fe,{className:"surface-card compact-card",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[s&&e.jsx("p",{className:"text-sm text-secondary",children:Js}),e.jsx("p",{className:"text-sm font-medium text-strong",children:k.recurrence?Lr(k.recurrence,k.timezone):tr(k.preset??null,k.cronExpr,k.timezone)}),!k.recurrence&&e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:k.cronExpr})]}),k.enabled&&k.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",Xm(k.nextRunAt,k.timezone)]}),k.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(k.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(de,{tone:k.enabled?"positive":"neutral",children:k.enabled?"Active":"Paused"}),n&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:E,onClick:He(z),children:k.enabled?"Pause":"Resume"}),n&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:F,onClick:He(ne),children:F?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[I&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",role:"alert",children:[e.jsx("p",{children:"This schedule changed elsewhere. Load the latest version before saving."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:pe,children:"Load latest schedule"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Frequency",value:i,onChange:Z=>c(Z.target.value),children:Cy.map(Z=>e.jsx("option",{value:Z.value,children:Z.label},Z.value))})]}),i!=="calendar"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:d,disabled:i==="twice-daily"||i==="custom",onChange:Z=>u(parseInt(Z.target.value)),children:Array.from({length:24},(Z,be)=>e.jsx("option",{value:be,children:Ru(be)},be))})]})]}),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:h,onChange:Z=>m(Z.target.value)})]}),i==="calendar"&&e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Repeat every"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Repeat every days",type:"number",min:"1",max:"3650",value:b,onChange:Z=>p(Number(Z.target.value))}),e.jsx("p",{className:"text-xs text-muted",children:"days"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Start date"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Start date",type:"date",value:x,onChange:Z=>g(Z.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Recurrence time",type:"time",value:f,onChange:Z=>N(Z.target.value)})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none","aria-label":"Timezone",value:R?"Other":S,onChange:Z=>{Z.target.value==="Other"?(y(!0),q("Other")):(y(!1),q(Z.target.value))},children:[_o.map(Z=>e.jsx("option",{value:Z,children:Z},Z)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),R&&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:Z=>A(Z.target.value)})]}),B&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:B}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{o(!1),L(void 0),w(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:E||O.isFetching||oe||I||i==="custom"&&!h.trim()||i==="calendar"&&(!Number.isInteger(b)||b<1||b>3650||!x||!f),onClick:He(Y),children:E?"Saving...":"Save schedule"})]})]})]})}const Ay=[{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 Py({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[o,i]=l.useState(""),[c,d]=l.useState(["citation.lost","citation.gained"]),[u,h]=l.useState(!1),[m,b]=l.useState(null),[p,x]=l.useState({}),[g,f]=l.useState(new Set);l.useEffect(()=>{Mu(t).then(n).catch(()=>n([]))},[t]);const N=y=>{d(j=>j.includes(y)?j.filter(A=>A!==y):[...j,y])},S=async()=>{if(!(!o.trim()||c.length===0)){h(!0),b(null);try{const y=await Lu(t,{channel:"webhook",url:o.trim(),events:c});n(j=>j==="loading"?[y]:[...j,y]),i(""),d(["citation.lost","citation.gained"]),r(!1),Te({title:"Webhook added",detail:`Notifications will be sent to ${y.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(y){b(y instanceof Error?y.message:"Failed to add webhook")}finally{h(!1)}}},q=async y=>{if(!g.has(y)){f(j=>new Set(j).add(y));try{await Eu(t,y),n(j=>j==="loading"?j:j.filter(A=>A.id!==y)),Te({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${y}`,dedupeMode:"drop"})}catch(j){b(j instanceof Error?j.message:"Failed to remove webhook")}finally{f(j=>{const A=new Set(j);return A.delete(y),A})}}},R=async y=>{x(j=>({...j,[y]:{state:"testing"}}));try{const j=await qu(t,y);x(A=>({...A,[y]:{state:j.ok?"ok":"fail",status:j.status}})),j.ok&&Te({title:"Test notification sent",detail:`Webhook returned status ${j.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${y}`,dedupeMode:"replace"})}catch{x(j=>({...j,[y]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),!ae()&&s!=="loading"&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),b(null)},children:a?"Cancel":"+ Add webhook"})]}),!ae()&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:o,onChange:y=>i(y.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Ay.map(y=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:c.includes(y.value),onChange:()=>N(y.value)}),e.jsx("span",{className:"text-sm text-neutral",children:y.label})]},y.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(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),b(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:u||!o.trim()||c.length===0,onClick:He(S),children:u?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(fe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-neutral break-all",title:y.urlHost,children:y.urlDisplay??y.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:y.events.map(j=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-strong bg-surface-inset px-2 py-0.5 text-[10px] font-medium text-secondary uppercase tracking-wide",children:j.replace("."," ")},j))})}),e.jsx("td",{children:e.jsx(de,{tone:y.enabled?"positive":"neutral",children:y.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[p[y.id]&&(()=>{const j=p[y.id],A=j.state==="testing"?"Sending…":j.state==="ok"?`Delivered${j.status?` (${j.status})`:""}`:`Failed${j.status?` (${j.status})`:""}`;return e.jsx(de,{tone:j.state==="ok"?"positive":j.state==="fail"?"negative":"neutral",children:A})})(),!ae()&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:p[y.id]?.state==="testing",onClick:()=>{R(y.id)},children:"Test"}),!ae()&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:g.has(y.id),onClick:()=>{q(y.id)},children:g.has(y.id)?"Removing…":"Remove"})]})})]},y.id))})]}),m&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:m})]})]})}function Ry({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:o}){return ae()||Ut()?null:e.jsx(Ou,{open:t,onOpenChange:n,children:e.jsxs(Fu,{onCloseAutoFocus:i=>{r&&(i.preventDefault(),r())},children:[e.jsxs(Gu,{children:[e.jsx(Ku,{children:"Run AI sweep for the whole project?"}),e.jsxs(_u,{children:["Runs all tracked queries for ",s,". Report filters do not limit the sweep. Provider charges apply."]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsx(P,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(We,{disabled:o,onClick:a,children:"Run project-wide sweep"})]})]})})}const Uo=2e3,Bo=3e5;function Iy(){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 Ty({projectName:t,refreshNonce:s}){const n=ms(),[a,r]=l.useState(null),[o,i]=l.useState([]),[c,d]=l.useState(null),[u,h]=l.useState([]),[m,b]=l.useState([]),[p,x]=l.useState(null),[g,f]=l.useState(""),[N,S]=l.useState(""),[q,R]=l.useState(""),[y,j]=l.useState(!0),[A,E]=l.useState(!1),[D,F]=l.useState(null),[V,B]=l.useState("performance");l.useEffect(()=>{w()},[t,s]);async function w(){j(!0),F(null);try{const $=await n.fetchQuery({...cl({client:W,path:{name:t}}),staleTime:_t});if(r($),$.connected){const[te,le,pe,ie]=await Promise.all([n.fetchQuery({...xm({client:W,path:{name:t}}),staleTime:_t}).catch(()=>null),n.fetchQuery({...pm({client:W,path:{name:t}}),staleTime:_t}).catch(()=>[]),n.fetchQuery({...gm({client:W,path:{name:t}}),staleTime:_t}).catch(()=>[]),$.siteUrl?Promise.resolve([]):n.fetchQuery({...fm({client:W,path:{name:t}}),staleTime:_t}).then(Ne=>Ne.sites).catch(()=>[])]);d(te),h(le),b(pe),i(ie)}else d(null),h([]),b([]),i([])}catch($){F($ instanceof Error?$.message:"Failed to load Bing data")}finally{j(!1)}}async function G(){if(N.trim()){F(null);try{const $=await ym(t,N.trim());await Ct(n,"bing"),S(""),$.availableSites.length>0&&i($.availableSites),await w()}catch($){F($ instanceof Error?$.message:"Failed to connect")}}}async function L(){try{await bm(t),await Ct(n,"bing"),r(null),i([]),d(null),h([]),b([]),x(null),R(""),F(null)}catch($){F($ instanceof Error?$.message:"Failed to disconnect")}}async function ee(){if(q)try{await vm(t,q),await Ct(n,"bing"),await w()}catch($){F($ instanceof Error?$.message:"Failed to set site")}}async function O(){if(g.trim())try{const $=await jm(t,g.trim());await Ct(n,"bing"),x($),h(te=>[$,...te])}catch($){F($ instanceof Error?$.message:"Inspection failed")}}async function X($){E(!0),F(null);try{const te=await Pi(t,{urls:[$]}),{succeeded:le,failed:pe,total:ie}=te.summary;Te({title:"Bing submission requested",detail:pe===0?`${le} URL submitted to Bing.`:`${le}/${ie} submitted successfully, ${pe} failed.`,tone:pe===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${$}`,dedupeMode:"replace"})}catch(te){const le=te instanceof Error?te.message:"Submission failed";F(le),Te({title:"Bing submission failed",detail:le,tone:"negative",dedupeKey:`bing:indexing:${t}:${$}`,dedupeMode:"replace"})}finally{E(!1)}}async function oe(){E(!0),F(null),Te({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const $=await Pi(t,{allUnindexed:!0}),{succeeded:te,failed:le,total:pe}=$.summary;Te({title:"Bing submissions requested",detail:le===0?`${te}/${pe} URL${pe!==1?"s":""} submitted to Bing.`:`${te}/${pe} submitted successfully, ${le} failed.`,tone:le===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch($){const te=$ instanceof Error?$.message:"Batch submission failed";F(te),Te({title:"Bing submissions failed",detail:te,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{E(!1)}}if(y)return e.jsx(fe,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return ae()?e.jsxs(fe,{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(de,{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(fe,{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(de,{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:N,onChange:$=>S($.target.value),onKeyDown:$=>{$.key==="Enter"&&G()}}),e.jsx(We,{size:"sm",disabled:!N.trim(),onClick:He(G),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"})]})]}),D&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:D})]});if(!a.siteUrl)return e.jsxs(fe,{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(de,{tone:"positive",children:"Connected"}),!ae()&&e.jsx(We,{size:"sm",variant:"ghost",onClick:He(L),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?Qt(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:$=>R($.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),o.map($=>e.jsxs("option",{value:$.url,children:[$.url,$.verified?" (verified)":""]},$.url))]}),!ae()&&e.jsx(We,{size:"sm",disabled:!q,onClick:He(ee),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."})]})]}),D&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:D})]});const k=[{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"}],I=k.find($=>$.key===V)??k[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(fe,{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(de,{tone:"positive",children:"Connected"}),!ae()&&e.jsx(We,{size:"sm",variant:"ghost",onClick:He(L),children:"Disconnect"})]})]}),D&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:D}),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?Qt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(fe,{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:I.eyebrow}),e.jsx("h3",{children:I.title})]}),e.jsx("p",{className:"text-xs text-muted",children:c?.lastInspectedAt?`Last inspected ${Qt(c.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:k.map($=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${V===$.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>B($.key),children:$.label},$.key))}),V==="coverage"&&c&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(va,{label:"Indexed",value:c.summary.indexed,tone:"positive"}),e.jsx(va,{label:"Not in index",value:c.summary.notIndexed+(c.summary.unknown??0),tone:"negative"}),e.jsx(va,{label:"Status unknown",value:c.summary.unknown??0,tone:"neutral"}),e.jsx(va,{label:"Coverage",value:`${c.summary.percentage}%`,tone:"neutral"})]}),c.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",c.notIndexed.length,")"]}),!ae()&&e.jsx(We,{size:"sm",variant:"ghost",disabled:A,onClick:He(oe),children:A?"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"}),!ae()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:c.notIndexed.map($=>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:$.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:$.httpCode??"—"}),!ae()&&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:A,onClick:()=>{X($.url)},children:"Submit"})})]},$.id))})]})})]}),(c.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(c.unknown??[]).length,")"]}),!ae()&&e.jsx(We,{size:"sm",variant:"ghost",disabled:A,onClick:He(oe),children:A?"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"}),!ae()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(c.unknown??[]).map($=>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:$.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:$.lastCrawledDate?Qt($.lastCrawledDate):"—"}),!ae()&&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:A,onClick:()=>{X($.url)},children:"Submit"})})]},$.id))})]})})]}),c.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",c.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:c.indexed.map($=>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:$.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:$.lastCrawledDate?Qt($.lastCrawledDate):"—"})]},$.id))})]})})]})]}),V==="coverage"&&!c&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),V==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!ae()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:g,onChange:$=>f($.target.value),onKeyDown:$=>{$.key==="Enter"&&O()}}),e.jsx(We,{size:"sm",disabled:!g.trim(),onClick:He(O),children:"Inspect"})]}),p&&e.jsxs("div",{className:"rounded border border-base bg-bg-elevated/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-strong",children:p.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:p.inIndex?"text-positive-400":"text-negative-400",children:p.inIndex?"Yes":"No"})," · ","HTTP: ",p.httpCode??"—"," · ","Crawled: ",p.lastCrawledDate??"—"]})]}),u.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:u.map($=>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:$.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(de,{tone:$.inIndex?"positive":"negative",children:$.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:$.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Qt($.inspectedAt)})]},$.id))})]})})]}),V==="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:ba[hn.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:ba[hn.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:ba[hn.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:ba[hn.Position]})]})}),e.jsx("tbody",{children:m.map(($,te)=>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:$.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:$.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:$.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite($.ctr)?$.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:$.averagePosition.toFixed(1)})]},te))})]})})})]})]})}function My({projectName:t}){const s=ms(),[n,a]=l.useState("google"),[r,o]=l.useState(!0),[i,c]=l.useState("idle"),[d,u]=l.useState(null),h=l.useRef(null),[m,b]=l.useState(null),[p,x]=l.useState(null),[g,f]=l.useState(0);async function N(q=!1){q||o(!0),u(null);try{const[R,y]=await Promise.all([s.fetchQuery({...ti({client:W,path:{name:t}}),staleTime:_t}).catch(()=>[]),s.fetchQuery({...cl({client:W,path:{name:t}}),staleTime:_t}).catch(()=>null)]),j=R.find(A=>A.connectionType==="gsc")??null;b(j),x(y)}catch(R){u(R instanceof Error?R.message:"Failed to load search engine connections")}finally{o(!1)}}async function S(){if(i!=="idle")return;h.current?.abort();const q=new AbortController;h.current=q;const R=q.signal;c("syncing"),u(null),Te({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const y=[],j=[];try{async function A(){if(!m)return;const F=await mm(t);if(!F?.id)return;const V=Date.now()+Bo;for(;Date.now()<V;){if(R.aborted||(await new Promise(w=>setTimeout(w,Uo)),R.aborted))return;const B=await Er(F.id).catch(()=>null);if(!B)break;if(["completed","failed","cancelled"].includes(B.status)){B.status!=="completed"&&y.push(`Google sync ${B.status}`);return}}j.push("Google sync is still running — search data will appear shortly")}async function E(){if(!p?.connected)return;const F=await hm(t).catch(()=>null);if(!F?.id){y.push("Bing sweep could not be started");return}const V=Date.now()+Bo;for(;Date.now()<V;){if(R.aborted||(await new Promise(w=>setTimeout(w,Uo)),R.aborted))return;const B=await Er(F.id).catch(()=>null);if(!B)break;if(["completed","failed","cancelled","partial"].includes(B.status)){B.status==="failed"?y.push("Bing sweep failed"):B.status==="partial"&&j.push("Bing sweep finished with some pages unverified");return}}j.push("Bing sweep is still running — coverage will update shortly")}const D=await Promise.allSettled([A(),E()]);for(const F of D)F.status==="rejected"&&y.push(F.reason instanceof Error?F.reason.message:"Sync failed");if(await Promise.all([Ct(s,"gsc"),Ct(s,"bing")]),R.aborted)return;if(c("reloading"),await N(!0),f(F=>F+1),y.length>0){const F=`Partial refresh: ${[...y,...j].join("; ")}`;u(F),Te({title:"Search coverage partially refreshed",detail:F,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else j.length>0?Te({title:"Search coverage refresh incomplete",detail:j.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):Te({title:"Search coverage refreshed",detail:"Google and Bing workspaces are reloaded with the latest stored coverage.",tone:"positive",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}catch(A){if(!R.aborted){const E=A instanceof Error?A.message:"Refresh failed";u(E),Te({title:"Search coverage refresh failed",detail:E,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{R.aborted||c("idle")}}return l.useEffect(()=>(N(),()=>{h.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,R])=>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:R},q))}),!ae()&&e.jsxs(We,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{S()},children:[e.jsx(Zn,{className:`h-3.5 w-3.5 ${i!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":i==="syncing"?"Refreshing search data…":i==="reloading"?"Reloading workspaces…":"Refresh search data"]})]}),d&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:d}),n==="google"&&e.jsx(ax,{projectName:t,refreshNonce:g}),n==="bing"&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(Ty,{projectName:t,refreshNonce:g})]})]})}function Qa({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(_e,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${Vo[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 Ly({model:t,sweepRunning:s,hasVisibilityBaseline:n}){const a=t.citationMovement,r=t.mentionMovement,o=t.movementComparison,i=t.recentRuns.find(p=>p.kind===Ys["answer-visibility"]&&(p.status===Fa.completed||p.status===Fa.partial)),c=p=>p.tone==="positive"?"improved":p.tone==="negative"?"declined":p.gained>0||p.lost>0?"mixed":"steady",d=c(r),u=c(a),h=(()=>{if(s)return"A fresh sweep is running now";if(!n)return"No AI Visibility baseline yet";if(!o.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(o.querySetChanged)return"Tracking scope changed since the previous sweep";if(d===u)return d==="steady"?"Answer mentions and citation coverage held steady":d==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${d}`;const p=d==="mixed"?"Answer mention movement was mixed":d==="steady"?"Answer mentions held steady":`Answer mentions ${d}`,x=u==="mixed"?"citation movement was mixed":u==="steady"?"citation coverage held steady":`citation coverage ${u}`;return`${p}; ${x}`})(),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(_e,{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:h})]}),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(Qa,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(Qa,{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:Ut()?Js:"Run another sweep to measure mention and citation movement."})]})]})]}):e.jsx("div",{className:"overview-brief-grid",children:e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage signals"}),e.jsxs("dl",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm font-medium text-heading",children:"Mentioned"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:"Your brand or domain appears in the answer text."})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm font-medium text-heading",children:"Cited"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:"Your domain appears in the engine's source list."})]})]}),e.jsx("p",{className:"mt-4 border-t border-subtle pt-4 text-sm font-medium text-strong",children:s?"Your first sweep is running. Results will appear when it completes.":Ut()?Js:"Complete your first AI Visibility sweep to measure both signals."})]})})]})}function qr({id:t,eyebrow:s,title:n,meta:a,defaultOpen:r=!1,children:o}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:r||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"eyebrow eyebrow-soft",children:s}),e.jsx("span",{className:"overview-disclosure-title",children:n})]}),e.jsxs("span",{className:"overview-disclosure-meta",children:[a&&e.jsx("span",{children:a}),e.jsx(gn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:o})]})}function qy({insights:t,suggestedQueries:s,onManageQueries:n}){const{openEvidence:a}=Qo(),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(de,{tone:b.tone,children:b.actionLabel})]}),b.affectedPhrases.length>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:["Evidence · ",b.affectedPhrases.length," affected ",b.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:b.affectedPhrases.map((p,x)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(Or,{state:p.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:p.query}),p.provider?e.jsx($n,{provider:p.provider}):null,!ae()&&p.evidenceId?e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(p.evidenceId)},children:"View evidence"}):null]},p.evidenceId||`${b.id}-${x}`))})]}):null]},b.id),i=b=>e.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:b.query}),e.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:b.reason})]}),n?e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},b.query),c=t.slice(0,1),d=r.slice(0,1),u=t.slice(1),h=r.slice(1),m=u.length+h.length;return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[c.map(o),d.map(i)]}),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:[u.map(o),h.map(i)]})]}):null]})}function Xy(t){const{projectName:s}=ac({from:"/projects/$projectName"}),a=al()?.dashboard.projects.find(j=>j.project.name===s||j.project.id===s)?.project.name??null,r=$e({...Du({client:W}),enabled:!a}),o=a??r.data?.find(j=>j.name===s||j.id===s)?.name??null,i=rl(),c=il(t.tab,i?ol(i.projectTabs):void 0),[d,u]=l.useState(null),h=o!==null&&d===o,m=l.useCallback(()=>{o&&u(o)},[o]),{commandCenter:b,isLoading:p,overviewLoading:x,overviewError:g,isError:f,latestVisibilityRevision:N,competitorHistoryRevision:S,refetch:q}=ll(o,{overview:c==="overview"&&h}),R=!a&&r.isLoading||p;return!o&&!a&&r.isSuccess&&!p?e.jsx("div",{className:"page-container",children:e.jsxs(fe,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(P,{asChild:!0,children:e.jsx(ks,{to:"/",children:"Return to overview"})})]})}):!b&&(f||r.isError)?e.jsxs("div",{className:"page-container",role:"alert",children:[e.jsx("p",{children:"Could not load this project."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{Promise.all([r.refetch(),q()])},children:"Retry"})]}):!b||R?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(Oy,{model:b,refetch:q,latestVisibilityRevision:N,competitorHistoryRevision:S,overviewLoading:x,overviewError:g,overviewRequested:h,onRequestOverview:m,...t})}function Ey({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(null);l.useLayoutEffect(()=>{const h=r.current,m=o.current;if(!h||!m)return;const b=()=>{const x=h.getBoundingClientRect().width;if(!x)return;const g=Number.parseFloat(getComputedStyle(h).columnGap)||0,f=new Map([...m.querySelectorAll("[data-project-tab]")].map(j=>[j.dataset.projectTab,j.getBoundingClientRect().width])),N=j=>f.get(j)??0,S=j=>j.reduce((A,E)=>A+N(E),0)+Math.max(0,j.length-1)*g,q=[...t.map(j=>j.key),...s.length?["more"]:[],...n?[n.key]:[]];let R=t.map(j=>j.key),y=!1;if(S(q)>x){const j=t.find(D=>D.key===a),A=j?[j.key]:[];y=!!(n&&S([...A,"more",n.key])>x);const E=["more",...n&&!y?[n.key]:[]];for(const D of t)if(D.key!==j?.key){if(S([...A,D.key,...E])>x)break;A.push(D.key)}R=t.filter(D=>A.includes(D.key)).map(D=>D.key)}c(j=>j?.settingsInMore===y&&j.visibleKeys.join()===R.join()?j:{visibleKeys:R,settingsInMore:y})};if(b(),typeof ResizeObserver>"u")return window.addEventListener("resize",b),()=>window.removeEventListener("resize",b);const p=new ResizeObserver(b);return p.observe(h),p.observe(m),()=>p.disconnect()},[t,s,n,a]);const d=i?t.filter(h=>i.visibleKeys.includes(h.key)):t,u=[...t.filter(h=>!d.includes(h)),...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(h=>e.jsx("span",{className:"project-subnav-link","data-project-tab":h.key,children:h.label},h.key)),e.jsxs("span",{className:"project-subnav-link project-subnav-more-trigger","data-project-tab":"more",children:["More",e.jsx(gn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),d.map(h=>e.jsx(ks,{to:h.href,search:m=>({...m,onboarding:void 0}),className:`project-subnav-link ${h.key===a?"project-subnav-link-active project-subnav-current":""}`,"aria-current":h.key===a?"page":void 0,children:e.jsx("span",{className:"project-subnav-label",children:h.label})},h.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(Dy,{items:u,activeTab:a}),n&&!i?.settingsInMore&&e.jsx(ks,{to:n.href,search:h=>({...h,onboarding:void 0}),className:`project-subnav-link ${a==="settings"?"project-subnav-link-active":""}`,"aria-current":a==="settings"?"page":void 0,children:n.label})]})]})}function Dy({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null),o=l.useRef(null),i=l.useRef("first"),c=l.useId(),d=t.map(h=>h.key).join();if(l.useEffect(()=>{a(!1)},[d]),l.useEffect(()=>{if(!n)return;const h=r.current?.querySelectorAll('[role="menuitem"]');(i.current==="last"?h?.[h.length-1]:h?.[0])?.focus()},[n]),l.useEffect(()=>{if(!n)return;const h=b=>{r.current&&!r.current.contains(b.target)&&a(!1)},m=b=>{b.key==="Escape"&&(a(!1),o.current?.focus())};return document.addEventListener("pointerdown",h),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",h),document.removeEventListener("keydown",m)}},[n]),t.length===0)return null;const u=t.some(h=>h.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 ${u?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?c:void 0,onClick:()=>{i.current="first",a(h=>!h)},onKeyDown:h=>{h.key!=="ArrowDown"&&h.key!=="ArrowUp"||(h.preventDefault(),i.current=h.key==="ArrowUp"?"last":"first",a(!0))},children:["More",e.jsx(gn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:c,"aria-label":"More project sections",onKeyDown:h=>{const m=[...h.currentTarget.querySelectorAll('[role="menuitem"]')],b=m.indexOf(document.activeElement),p=h.key==="Home"?0:h.key==="End"?m.length-1:h.key==="ArrowDown"?(b+1)%m.length:h.key==="ArrowUp"?(b-1+m.length)%m.length:null;p!==null&&(h.preventDefault(),m[p]?.focus())},onBlur:h=>{r.current?.contains(h.relatedTarget)||a(!1)},children:t.map(h=>e.jsx(ks,{to:h.href,search:m=>({...m,onboarding:void 0}),role:"menuitem",tabIndex:-1,className:`project-subnav-menu-item ${h.key===s?"project-subnav-menu-item-active":""}`,"aria-current":h.key===s?"page":void 0,onClick:()=>a(!1),children:h.label},h.key))}):null]})}function Oy({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r,overviewLoading:o,overviewError:i,overviewRequested:c,onRequestOverview:d}){const u=rc(),h=ms(),{canWrite:m}=Ln(),[b,p]=l.useState(null),x=l.useRef(null),g=al(),f=s.project.name,N=g?.dashboard.projects.some(M=>M.project.name===f)??!1,S=$e({...Uu({client:W,path:{name:f}}),enabled:!ae()&&!!f&&(m||t==="portfolio"||t==="overview"||t==="settings"),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),q=g?g.dashboard.settings.providerStatuses.filter(M=>M.state==="ready").map(M=>ki(M.name)):void 0,R=S.data?.answerVisibilityProviderReady,y=q,j=s.project.providers.map(ki),A=y?.some(M=>j.length===0||j.includes(M))===!0,E=j.length===0||j.includes(Bu),D=$e({...Vu({client:W}),enabled:!ae()&&m&&R===void 0&&E&&!A,staleTime:6e4,retry:!1}),F=E?D.isSuccess?typeof D.data.browserVersion=="string":D.isError?!1:void 0:!1,V=R??zu({projectProviders:j,configuredApiProviders:y,cdpConfigured:F}),B=l.useMemo(()=>{const M=rl();return M?ol(M.projectTabs):void 0},[]),w=il(t,B),G=l.useMemo(()=>s.competitors.map(M=>M.domain),[s.competitors]),[L,ee]=l.useState(!1),[O,X]=l.useState(!1),oe=Qu(),k=ic({strict:!1}),I=ch(k),$=l.useCallback(M=>{u({to:".",search:ge=>dh(ge,M)})},[u]),te=k.manageQueries===!0,le=l.useCallback(()=>{u({to:".",replace:!0,search:M=>({...M,siteHealthRunId:void 0})})},[u]),[pe,ie]=l.useState(te),[Ne,Y]=l.useState(""),[z,ne]=l.useState(!1),[Z,be]=l.useState(null),[ce,De]=l.useState("30d"),[we,Se]=l.useState(void 0),[Je,Ue]=l.useState(!1),[Be,ze]=l.useState(null),[Oe,_]=l.useState(!1),U=Nl(k),[H,Ie]=l.useState(void 0),[Ge,se]=l.useState(void 0),Xe=l.useCallback(M=>{Ie(M.search),M.sort&&se(M.sort),u({to:".",search:ge=>({...ge,...oh(M)}),replace:!1})},[u]),[ut,mt]=l.useState(!1),Ve=s?.project.displayName||s?.project.name||f,Fe=Hu(),ht=$e({...Ai({client:W,path:{name:f}}),enabled:w==="portfolio"&&!!f,staleTime:0,refetchOnMount:"always"}),Ze=$e({...Wu({client:W,path:{name:f}}),enabled:!ae()&&!!f&&(m||w==="portfolio"||w==="overview"||w==="settings"),staleTime:0,refetchOnMount:"always"}),Ae=Ze.data?.active??null,at=Ze.data!==void 0,kt=new Set(Ae&&Number(Ae.plan.schemaVersion)===2?Ae.plan.groups?.map(M=>M.stableKey)??[]:[]),Ee={...U.scope==="group"&&!!U.groupKey&&at&&!kt.has(U.groupKey)?{scope:"all",queryClass:U.queryClass}:U,...H?{search:H}:{}},C=Ae===null?null:Number(Ae.plan.schemaVersion),Ce=Ae?.revision??0,ve=at?`${f}:${Ce}`:null,Ye=l.useRef(null);l.useEffect(()=>{const M=Ye.current;ve!==null&&(Ye.current=ve),ih(M,ve)&&(Xe({scope:"all",queryClass:"all"}),mt(!1))},[ve,Xe]);const yt={client:W,path:{name:f},query:{scope:Ee.scope,...Ee.groupKey?{groupKey:Ee.groupKey}:{},queryClass:Ee.queryClass,...Ee.search?{search:Ee.search}:{},...Ge?{sort:Ge}:{},limit:50}},tt=oc({...Yu(yt),enabled:!1,initialPageParam:yt,getNextPageParam:(M,ge)=>{if(!M.properties.nextCursor)return;const Le=ge[0]?.measurement.displayedRunId;return{path:yt.path,query:{...yt.query,cursor:M.properties.nextCursor,...Le?{runId:Le}:{}}}},placeholderData:ei,staleTime:0,refetchOnMount:"always"}),Lt=tt.data?.pages[0]?.measurement.displayedRunId,Qe=$e({...Ju({client:W,path:{name:f},query:{revision:Ce,...Lt?{runId:Lt}:{}}}),enabled:w==="overview"&&!!f&&Ae!==null&&C===1,staleTime:0,refetchOnMount:"always"}),J=Ze.data!==void 0,qe=ht.data!==void 0,Pe=Ze.isPending&&!J,Re=Ze.isError&&!J,Ht=ht.isPending&&!qe,jt=ht.isError&&!qe,Rt=Qe.data!==void 0,qt=Qf({activePlanSchemaVersion:S.data?.activeSchemaVersion??C,hasDraft:S.data?.draft!==null&&S.data?.draft!==void 0}),xt=qt.surface==="simple-overview",Et=S.data===void 0&&Ze.data===void 0&&(Ze.isLoading||S.isLoading);l.useEffect(()=>{w==="overview"&&xt&&!Et&&d()},[Et,xt,d,w]);const ts=w==="overview"&&xt&&!Et,rt=ll(f,{evidence:ts}),Vt=rt.commandCenter?.visibilityEvidence??s.visibilityEvidence,Nt=m&&!ae()&&!Ut()&&w!=="overview",ss=$e({...Ai({client:W,path:{name:f}}),enabled:Nt,staleTime:si,refetchOnWindowFocus:"always"}),it=C===2&&I.measurementScope==="group"?I.measurementScopeKey:void 0,Dt=C===2&&I.measurementScope==="project",Wt=l.useMemo(()=>{if(!(Ae?.plan.schemaVersion!==2||!it))return Ae.plan.groups.find(M=>M.stableKey===it)},[Ae,it]),It={client:W,path:{name:f},query:{window:ce,queryClass:C===2&&I.queryClass!=="unknown"?I.queryClass:"non-brand",...it?{groupKey:it}:{},...Dt?{scope:"all-markets"}:{}}},hs=w==="overview"&&!!f&&(xt||at)&&!Et&&(xt||(I.measurementScope==="project"||C===2&&I.measurementScope==="group")&&I.queryClass!=="unknown"&&(C===2||I.queryClass!=="branded")),[Yt,wt]=l.useState(null);l.useEffect(()=>{hs||wt(null)},[hs]),l.useEffect(()=>{wt(null)},[f]);const As=Yt===f,gt=hs&&As,Ot=$e({...Xu(It),enabled:gt,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});Zu(f,JSON.stringify([r,s.competitors.map(M=>M.domain).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,Ce,S.data?.draft?.etag??null]),gt);const ys=Ot.isError?Ot.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,xs=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]),zt=l.useMemo(()=>{if(Ae?.plan.schemaVersion!==2)return xs;const M=it?Wt?.competitors??[]:Ae.plan.groups.flatMap(Le=>Le.competitors),ge=new Map;for(const Le of M){const Zt=Le.domain.trim().toLowerCase();!Zt||ge.has(Zt)||ge.set(Zt,{domain:Le.domain,label:Le.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const Le of xs){const Zt=Le.domain.trim().toLowerCase();!Zt||ge.has(Zt)||ge.set(Zt,Le)}return[...ge.values()]},[Ae,it,xs,Wt]),K=C===2?zt:xs,re=Pt({...em({client:W}),meta:{skipGlobalErrorToast:!0}}),je=S.data!==void 0?"success":S.isError?"error":"pending",ue=l.useMemo(()=>{const M=tt.data?.pages;return M?!Bm(M):!1},[tt.data]),me=l.useMemo(()=>{const M=tt.data?.pages,ge=M?.[0],Le=M?.at(-1);if(!(!ge||!Le||ue))return{...ge,properties:{...ge.properties,items:M.flatMap(Zt=>Zt.properties.items),nextCursor:Le.properties.nextCursor}}},[ue,tt.data]),Ke=l.useMemo(()=>{if(Ae)return Ae.plan.schemaVersion===1?Qe.data?ty(Ae,Qe.data):void 0:me?Vm({overview:me,activePlan:Ae,sort:Ge,report:Qe.data,reportState:me.measurement.displayedRunId===void 0?"ready":Qe.isFetching&&Qe.data===void 0?"loading":Qe.isError&&Qe.data===void 0?"error":Qe.data?"ready":"loading"}):void 0},[Ae,Qe.data,Qe.isError,Qe.isFetching,me]),ns=C===2?ue?"error":tt.isPending?"loading":tt.isError&&Ke===void 0?"error":"ready":Qe.isPending&&!Rt?"loading":Qe.isError&&!Rt?"error":"ready",ot=(s?.recentRuns??[]).some(M=>M.kind===Ys["answer-visibility"]&&(M.status===Fa.running||M.status===Fa.queued)),bs=s.queryCounts.total>0,T=l.useMemo(()=>(s?.project.locations??[]).map(M=>M.label),[s?.project.locations]),xe=l.useMemo(()=>new Set(Vt.map(M=>M.location??"")),[Vt]),dt=xe.has(""),Me=l.useMemo(()=>[...new Set(Vt.map(M=>M.query))].sort((M,ge)=>M.localeCompare(ge)),[Vt]),Ft=Me.length>0||s.queryCounts.total>0||(ss.data?.length??0)>0||Ae!==null,Jt=m&&!Ft&&(Ze.data===void 0&&Ze.isPending||ss.isLoading||ts&&rt.evidenceLoading),bn=m&&(S.isError&&!S.isFetching||Nt&&ss.isError&&!ss.isFetching),St=m&&!bn&&(Jt||V===void 0||S.isFetching),ps=!St&&!bn&&Ft&&V===!0,vn=m&&!St&&!ps,qn=$e({...nl({client:W,path:{name:f}}),enabled:!ae()&&!Ut()&&!!f,retry:!1}).data?.find(M=>M.kind===Ys["answer-visibility"]),ia=qn?.enabled&&qn.nextRunAt?`Next AI sweep ${new Date(qn.nextRunAt).toLocaleString()}`:null,En=l.useMemo(()=>{const M=[...xe].filter(Boolean);return M.length>1?M:T},[xe,T]);l.useEffect(()=>{if(!ts||we===void 0||we===""||!f){ze(null),_(!1);return}_(!0),tm(f,we,20).then(M=>{ze(M),_(!1)}).catch(()=>{ze(null),_(!1)})},[we,f,ts]);const Os=l.useMemo(()=>{if(!Be)return null;const M=new Map;for(const ge of Be){for(const[Le,Zt]of Object.entries(ge.providerRuns??{}))M.set(`${ge.query}::${Le}`,Zt.map(gs=>({runId:gs.runId,citationState:gs.citationState,createdAt:gs.createdAt,answerMentioned:gs.answerMentioned,visibilityState:gs.visibilityState,visibilityTransition:gs.visibilityTransition,mentionState:gs.mentionState,mentionTransition:gs.mentionTransition})));(!ge.providerRuns||Object.keys(ge.providerRuns).length===0)&&M.set(`${ge.query}::`,ge.runs.map(Le=>({runId:Le.runId,citationState:Le.citationState,createdAt:Le.createdAt,answerMentioned:Le.answerMentioned,visibilityState:Le.visibilityState,visibilityTransition:Le.visibilityTransition,mentionState:Le.mentionState,mentionTransition:Le.mentionTransition})))}return M},[Be]),oa=l.useMemo(()=>{const M=we!==void 0?Vt.filter(ge=>we===""?!ge.location:ge.location===we):Vt;return Os?M.map(ge=>{const Le=Os.get(`${ge.query}::${ge.provider}`)??Os.get(`${ge.query}::`);return Le?{...ge,runHistory:Le}:ge}):M},[Vt,we,Os]);async function nn(){if(!(b!==f||!m||ae()||Ut()||Fe.isPending||ot||!ps))try{await Fe.mutateAsync({projectName:f,projectLabel:Ve,sourceAction:"project-run"}),p(null),n()}catch{}}function Dn(){u({to:"/setup",search:{experience:"legacy",setupProject:f}})}async function jn(){X(!0);try{await um(f),Te({title:"Project deleted",detail:`${Ve} was removed.`,tone:"positive",dedupeKey:`project:delete:${f}`,dedupeMode:"drop"}),u({to:"/"}),n()}catch(M){console.error("Failed to delete project:",M)}finally{X(!1)}}async function la(){const M=Ne.split(`
7
- `).map(ge=>ge.trim()).filter(Boolean);if(M.length!==0){ne(!0);try{await am(f,M),n(),Y("")}finally{ne(!1)}}}async function ca(M){be(M);try{await nm(f,[M]),n()}catch(ge){Te({title:"Could not remove query",detail:ge instanceof Error?ge.message:`Failed to remove "${M}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{be(null)}}async function da(M){const ge=M.trim();if(!ge)return!1;try{return await rm(f,[ge]),n(),!0}catch(Le){return Te({title:"Could not add competitor",detail:Le instanceof Error?Le.message:`Failed to add ${ge}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function On(M){const ge=s.competitors.find(Le=>Le.domain===M);if(!ge)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 im(f,ge.id),n(),!0}catch(Le){return Te({title:"Could not remove competitor",detail:Le instanceof Error?Le.message:`Failed to remove ${ge.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function ua(M){const ge=M.trim();if(!ge||!it||C!==2||!m||ae()||re.isPending)return!1;try{const Le=await re.mutateAsync({client:W,path:{name:f},headers:{"Idempotency-Key":Iy()},body:{expectedActiveRevision:Ce,groupKey:it,domain:ge}});return Promise.allSettled([S.refetch()]),Te({title:Le.draftCreated?"Competitor added to a market draft":"Market competitor updated",detail:`Publish the Advanced Measurement draft before ${ge} is used in future market runs.`,tone:"positive",dedupeKey:`competitor:market-pin:${it}:${ge}`,dedupeMode:"replace"}),!0}catch(Le){return Te({title:"Could not add market competitor",detail:Le instanceof Error?Le.message:`Failed to add ${ge} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function Ps(M,ge){const Le=await om(M,ge);return await h.invalidateQueries({queryKey:lm({client:W})}),h.setQueryData(cm({client:W,path:{name:M}}),Le),$y(h,Le),ge.providers!==void 0&&await h.invalidateQueries({queryKey:dm({client:W,path:{name:M}}),exact:!0}),Le}const Xt=`/projects/${encodeURIComponent(s.project.name)}`,ma=[{key:"overview",label:"AI Visibility",href:Xt},{key:"search-console",label:"Search Engines",href:`${Xt}/search-console`},{key:"activity",label:"Activity",href:`${Xt}/activity`},{key:"technical-aeo",label:"Site Health",href:`${Xt}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${Xt}/conversions`},{key:"local",label:"Local Presence",href:`${Xt}/local`},{key:"queries",label:"Queries",href:`${Xt}/queries`},{key:"backlinks",label:"Backlinks",href:`${Xt}/backlinks`}],ha=[{key:"report",label:"Report",href:`${Xt}/report`},{key:"history",label:"Change History",href:`${Xt}/history`}],xa=ma.filter(M=>sr(M.key,B)),pa=ha.filter(M=>sr(M.key,B)),Fn=sr("settings",B)?{key:"settings",label:"Settings",href:`${Xt}/settings`}:null;function ga(M){return xt?M:e.jsx(op,{projectName:f,selection:I,showUnmeasuredFallback:!Ae&&!bs&&I.measurementScope==="project"&&I.queryClass==="all"&&!I.provider&&!I.model&&!I.location&&!I.from&&!I.to&&!I.revision&&!I.measurementRunId&&!I.queryKey,onSelectionChange:$,onManageQueries:ae()?void 0:()=>{u({to:"/projects/$projectName/queries",params:{projectName:f},search:ge=>({...ge,queryWorkspace:"tracked",trackingQueryId:void 0})})},fallback:M},`${f}:${JSON.stringify({...I,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]}),!ae()&&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:Ut()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:[w==="overview"&&(xt||I.from||I.to)?e.jsx("p",{className:"text-sm text-muted",children:xt?s.dateRangeLabel:`${I.from?.slice(0,10)??"First measurement"} to ${I.to?.slice(0,10)??"Latest measurement"}`}):null,!ae()&&(Ut()?e.jsx(sm,{projectName:f,running:ot,portfolio:!xt}):e.jsxs("div",{className:"flex items-center gap-3",children:[ia?e.jsx("p",{className:"text-sm text-secondary",children:ia}):null,e.jsx(We,{type:"button",variant:"outline",disabled:Fe.isPending||ot||St,onClick:bn?()=>{Promise.all([S.refetch(),...Nt?[ss.refetch()]:[]])}:vn?Dn:M=>{x.current=M.currentTarget,p(f)},children:Fe.isPending?"Starting…":ot?"AI sweep running…":St?"Checking AI readiness…":bn?"Retry AI readiness":vn?"Set up AI Visibility":"Run AI sweep"})]}))]})]}),!ae()&&!Ut()&&e.jsx(Ry,{open:b===f,projectLabel:Ve,onOpenChange:M=>p(M?f:null),onConfirm:He(nn),onClosed:()=>x.current?.focus(),disabled:Fe.isPending||ot||!ps}),e.jsx(Ey,{items:xa,overflowItems:pa,settingsItem:Fn,activeTab:w}),w==="portfolio"&&!ae()?e.jsx(Pf,{projectName:f,canEdit:m,queries:ht.data??[],isQueryLoading:Ht,isQueryError:jt,onRetryQueries:()=>{ht.refetch()},publishedPlan:Ae,onCreateQueries:async M=>(await oe.mutateAsync({projectName:f,queries:[...M]}),(await ht.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{u({to:"/projects/$projectName",params:{projectName:f},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([S.refetch(),Ze.refetch()]).finally(()=>{u({to:"/projects/$projectName",params:{projectName:f}})})}},f):w==="overview"?Et||xt&&!N&&(!c||o)?e.jsxs("div",{role:"status","aria-live":"polite",children:[e.jsx("span",{className:"sr-only",children:"Loading project overview"}),e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-hidden":"true"})]}):xt&&i?e.jsxs("div",{role:"alert",className:"page-section-divider",children:[e.jsx("p",{children:"Could not load AI visibility."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[Re?e.jsxs("div",{role:"alert",className:"mb-5 flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("span",{children:"Could not check the advanced measurement setup. Existing project-wide results remain available."}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{Ze.refetch()},children:"Retry setup check"})]}):null,ga(e.jsx(Hf,{mode:qt,canEdit:m&&!ae()&&!Pe&&!Re,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(vp,{projectName:s.project.name,competitorDomains:G,analyticsRevision:a})}),e.jsx(Ly,{model:s,sweepRunning:ot,hasVisibilityBaseline:bs}),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"}),e.jsx("p",{className:"supporting-copy",children:"Latest measured results against pinned competitors."})]})}),bs?e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsx(ph,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:G},s.project.name),e.jsx("div",{className:"competitive-gaps",children:e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Qa,{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(Qa,{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(qr,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[!ae()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(We,{type:"button",variant:"outline",size:"sm",onClick:()=>ie(!pe),children:pe?"Done":"Manage queries"})}),!ae()&&pe&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[Me.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:Me.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:Z!==null,onClick:()=>{ca(M)},children:Z===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:Ne,onChange:M=>Y(M.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[Ne.split(`
8
- `).filter(M=>M.trim()).length," to add"]}),e.jsx(We,{type:"button",size:"sm",disabled:!Ne.trim()||z,onClick:He(la),children:z?"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),Ue(!1)},children:M.label},M.label)),dt&&e.jsx("button",{className:`filter-chip ${we===""?"filter-chip-active":""}`,type:"button","aria-pressed":we==="",onClick:()=>{Se(""),Ue(!1)},children:"No location"}),En.length>1&&we===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${Je?"filter-chip-active":""}`,type:"button","aria-pressed":Je,onClick:()=>Ue(M=>!M),title:"Side-by-side location comparison",children:"Compare"})]}),rt.evidenceLoading?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading query evidence…"}):rt.evidenceError?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load query evidence."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{rt.refetch()},children:"Retry"})]}):e.jsx(Ph,{evidence:oa,compareLocations:Je})]}),e.jsxs(qr,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:ae(),children:[e.jsx($x,{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(_e,{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($n,{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"}`))})]})})]})]}),!ae()&&e.jsx(qr,{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(Mm,{run:M},M.id))})})]}),report:Ke,reportState:ns,onOpenSetup:ae()?void 0:()=>{u({to:"/projects/$projectName/portfolio",params:{projectName:f}})},onRetryReport:()=>{C===2?Promise.all([tt.refetch(),Qe.refetch()]):Qe.refetch()},onViewChange:M=>{Xe({scope:M.scope,...M.groupKey?{groupKey:M.groupKey}:{},queryClass:M.queryClass,...M.search?.trim()?{search:M.search.trim()}:{}})},onLoadMore:M=>{M===me?.properties.nextCursor&&tt.fetchNextPage()},onPropertyExpand:()=>{ut&&Qe.isError&&Qe.refetch(),mt(!0)},onRetryEvidence:()=>{Qe.refetch()},renderPropertyLink:C===2&&!ae()?({id:M,name:ge})=>e.jsx(ks,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:f,targetKey:M},className:"text-link hover:underline",children:ge}):void 0,isViewLoading:tt.isPlaceholderData,isLoadingMore:tt.isFetchingNextPage,isLoadMoreError:tt.isFetchNextPageError,viewSearch:Ee.search??""},`${f}:${Ce}`)),!xt&&I.measurementScope==="project"?e.jsxs("details",{className:"page-section-divider",onToggle:M=>{M.currentTarget.open&&d()},children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm font-medium text-heading",children:"Project signals"}),!c||o?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading project signals…"}):i?e.jsxs("div",{role:"alert",className:"text-sm text-secondary",children:[e.jsx("p",{children:"Could not load project signals."}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>{n()},children:"Retry"})]}):e.jsx(qy,{insights:s.insights,suggestedQueries:s.suggestedQueries,onManageQueries:ae()?void 0:()=>{u({to:"/projects/$projectName/queries",params:{projectName:f},search:M=>({...M,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]},f):null,hs?e.jsxs("details",{className:"page-section-divider",open:As,onToggle:M=>wt(M.currentTarget.open?f:null),children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm font-medium text-heading",children:"Competitor history"}),e.jsx("p",{className:"pb-3 text-sm text-secondary",children:"History for this scope uses the time window below."}),e.jsx(jh,{window:ce,landscape:Ot.data,pinnedFallback:K,canWrite:m,isEmbed:ae(),onWindowChange:De,onPin:it&&m&&!ae()?ua:!Dt&&m&&!ae()?da:void 0,onUnpin:it||Dt||!m||ae()?void 0:On,onAddCompetitor:it&&m&&!ae()?ua:!Dt&&m&&!ae()?da:void 0,error:ys,onRetry:gt?()=>{Ot.refetch()}:void 0,isLoading:gt&&Ot.isPending&&Ot.data===void 0,scopeLabel:it?`${Wt?.label??it} group`:Dt?"All markets":"Project-wide"})]}):null]}):w==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(Ny,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(M,ge)=>{await Ps(M,ge)},onRefresh:()=>{n()}}),e.jsx(Sy,{project:s.project,onSave:async M=>{await Ps(s.project.name,M)}}),m&&!ae()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Advanced measurement"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Measure individual properties, locations, or site sections with separate query sets."}),je==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):je==="error"?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:"Could not load advanced measurement setup."}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{S.refetch()},children:"Retry"})]}):e.jsx(P,{type:"button",variant:"outline",onClick:()=>{u({to:"/projects/$projectName/portfolio",params:{projectName:f}})},children:sc(qt.setupAction)})]}):null,e.jsx(ky,{projectName:s.project.name}),e.jsx(Py,{projectName:s.project.name}),m&&!ae()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-negative-400",children:"Delete project"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Permanently deletes this project and all its queries, competitors, runs, and snapshots."}),L?e.jsxs(fe,{className:"surface-card p-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(P,{type:"button",variant:"destructive",disabled:O,onClick:He(jn),children:O?"Deleting...":"Yes, delete project"}),e.jsx(P,{type:"button",variant:"outline",disabled:O,onClick:()=>ee(!1),children:"Cancel"})]})]}):e.jsxs(We,{type:"button",variant:"outline",onClick:()=>ee(!0),children:[e.jsx(ml,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):w==="report"?e.jsx(ry,{projectName:s.project.name}):w==="queries"||w==="discovery"?e.jsx($p,{projectName:f,queryWorkspace:k.queryWorkspace==="research"||w==="discovery"&&k.queryWorkspace===void 0?"research":"tracked",onQueryWorkspaceChange:M=>$({queryWorkspace:M,trackingQueryId:void 0}),researchMode:k.researchMode==="test"?"test":"find",onResearchModeChange:M=>$({researchMode:M}),selection:I,onSelectionChange:$,trackingQueryId:typeof k.trackingQueryId=="string"?k.trackingQueryId:void 0,onTrackingQueryIdChange:M=>$({trackingQueryId:M})}):w==="technical-aeo"?e.jsx(Lm,{projectName:s.project.name,projectId:s.project.id,initialRunId:k.siteHealthRunId,onReleaseInitialRun:le}):w==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(Ug,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(Rg,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):w==="history"?e.jsx(rg,{projectName:s.project.name}):w==="activity"?e.jsx(Bh,{projectName:s.project.name}):w==="backlinks"?e.jsx(Ix,{projectName:s.project.name}):w==="local"?e.jsx(ix,{projectName:s.project.name,projectId:s.project.id}):w==="search-console"?e.jsx(My,{projectName:s.project.name}):null]})}export{Xy as ProjectPage,Ey as ProjectSubnav,Ry as ProjectSweepConfirmation,$y as patchProjectDashboardCache};