@ainyc/canonry 4.183.1 → 4.185.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/assets/{AuditHistoryPanel-DM-2GC2i.js → AuditHistoryPanel-N0RYtAB2.js} +1 -1
- package/assets/assets/{BacklinksPage-YJU9B2RQ.js → BacklinksPage-Bou9tizz.js} +1 -1
- package/assets/assets/{HistoryPage-DcFzvVRB.js → HistoryPage-CXhga4Ph.js} +1 -1
- package/assets/assets/MeasurementPropertyPage-XvZ5N7OJ.js +1 -0
- package/assets/assets/ProjectPage-HRI4qMI7.js +9 -0
- package/assets/assets/{RunRow-6SFvSqhK.js → RunRow-C3D8VQYJ.js} +1 -1
- package/assets/assets/RunsPage-CpgzRa0M.js +1 -0
- package/assets/assets/{SettingsPage-DSS1eunM.js → SettingsPage-Bmx9pUOn.js} +1 -1
- package/assets/assets/{SiteHealthSection-CewNWjGo.js → SiteHealthSection-NLM9j7Eg.js} +3 -3
- package/assets/assets/{TrafficPage-DRZ1aqnG.js → TrafficPage-BYZhOBmP.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-vaBD4zHK.js → TrafficSourceDetailPage-D9H8w5_Y.js} +1 -1
- package/assets/assets/{extract-error-message-DD4JJz8j.js → extract-error-message-CH5Z1tok.js} +1 -1
- package/assets/assets/index-D2ciQ6Rc.js +86 -0
- package/assets/assets/{index-DwdK2e4e.css → index-D5UC9w71.css} +1 -1
- package/assets/assets/{react-sigma_core.esm.min-B8Wmi5Ko.js → react-sigma_core.esm.min-D6BeZvg8.js} +1 -1
- package/assets/index.html +2 -2
- package/dist/{chunk-AZJOCWZ4.js → chunk-4EMNAQR6.js} +11 -4
- package/dist/{chunk-VXPM6O4R.js → chunk-OVJJDBZY.js} +2 -2
- package/dist/{chunk-3SFCUICM.js → chunk-SCNSP2GV.js} +677 -391
- package/dist/{chunk-DU5Q5ZOX.js → chunk-U7XFRKLH.js} +5009 -4411
- package/dist/{chunk-7ATZMDG2.js → chunk-UXZCO5WK.js} +5377 -2339
- package/dist/cli.js +7687 -7787
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-BQIIWWQJ.js → intelligence-service-WTRLQG5V.js} +2 -2
- package/dist/mcp.js +3 -3
- package/package.json +8 -8
- package/assets/assets/MeasurementPropertyPage-OQ3X0KHU.js +0 -1
- package/assets/assets/ProjectPage-CMZO1xb2.js +0 -9
- package/assets/assets/RunsPage-Chk_-IOW.js +0 -1
- package/assets/assets/index-BdR4Vlu6.js +0 -86
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{r as l,j as e,u as Re,L as bs,h as As,o as Et,B as Qi,C as al,k as rl,l as il,D as ol}from"./vendor-tanstack-CYBjbqVr.js";import{M as Hi,I as ze,B as A,T as de,t as ll,a as cl,u as dl,C as ul,P as Mn,h as ml,b as hl,c as Ys,g as Wi,d as Yi,e as xe,f as V,i as ee,j as yt,k as De,l as xl,m as pl,n as gl,o as Ji,p as fl,q as bl,S as Xs,r as yl,s as vl,v as Hs,w as Vt,x as jl,y as $r,z as Xi,G as qt,A as dr,D as Nl,E as wl,F as Sl,H as Cl,J as Mr,K as ke,L as kl,N as Al,O as Na,Q as Pl,R as Rl,U as Il,V as Tl,W as $l,X as Ml,Y as Ll,Z as Dl,_ as El,$ as ql,a0 as Ol,a1 as Gl,a2 as Fl,a3 as _l,a4 as Ul,a5 as Zi,a6 as Fs,a7 as Bl,a8 as eo,a9 as ra,aa as Vl,ab as We,ac as Kl,ad as zl,ae as Ql,af as ia,ag as Hl,ah as Wl,ai as Yl,aj as sn,ak as Jl,al as Xl,am as Zl,an as to,ao as Ja,ap as ec,aq as so,ar as tc,as as ur,at as _s,au as cs,av as sc,aw as nc,ax as ac,ay as rc,az as ic,aA as oc,aB as lc,aC as Tn,aD as Zs,aE as cc,aF as dc,aG as uc,aH as mc,aI as no,aJ as hc,aK as xc,aL as pc,aM as gc,aN as fc,aO as ao,aP as bc,aQ as yc,aR as vc,aS as jc,aT as Nc,aU as wc,aV as Sc,aW as Cc,aX as kc,aY as Ac,aZ as Pc,a_ as Rc,a$ as Ic,b0 as Tc,b1 as $c,b2 as Mc,b3 as Lc,b4 as Dc,b5 as Ec,b6 as qc,b7 as gs,b8 as Oc,b9 as ot,ba as Gc,bb as Fc,bc as _c,bd as Uc,be as Bc,bf as Vc,bg as Kc,bh as zc,bi as Qc,bj as Hc,bk as Wc,bl as Yc,bm as Jc,bn as Xc,bo as Zc,bp as ed,bq as td,br as sd,bs as nd,bt as ad,bu as rd,bv as id,bw as od,bx as ld,by as cd,bz as dd,bA as ud,bB as md,bC as hd,bD as xd,bE as pd,bF as gd,bG as fd,bH as bd,bI as yd,bJ as vd,bK as jd,bL as Nd,bM as ro,bN as wa,bO as wd,bP as Lr,bQ as Sd,bR as Cd,bS as kd,bT as Ad,bU as Pd,bV as Rd,bW as Id,bX as io,bY as Td,bZ as $d,b_ as Md,b$ as Dr,c0 as Ld,c1 as Dd,c2 as Ed,c3 as qd,c4 as Od,c5 as Gd,c6 as Fd,c7 as _d,c8 as Ud,c9 as Bd,ca as Vd,cb as Kd,cc as zd,cd as Qd,ce as Hd,cf as oa,cg as Wd,ch as Sa,ci as Yd,cj as Jd,ck as Xd,cl as Zd,cm as eu,cn as tu,co as su,cp as nu,cq as au,cr as oo,cs as ru,ct as iu,cu as ou,cv as lu,cw as cu,cx as du,cy as Bn,cz as uu,cA as mu,cB as hu,cC as Er,cD as xu}from"./index-D2ciQ6Rc.js";import{C as Ln,e as pu,q as la,U as gu,r as fu,L as bu,s as lo,i as yu,P as ca,D as co,t as vu,u as ju,E as Nu,v as wu}from"./vendor-lucide-XjCNFK0x.js";import{R as Su}from"./RunRow-C3D8VQYJ.js";import{u as Dn,D as fn,a as en,b as uo,M as na,c as Ns,S as Cu}from"./SiteHealthSection-NLM9j7Eg.js";import{C as da,f as nn,a as ls,b as Kt,c as Ot,d as ss,e as nt,g as as,h as tn,M as mo,i as ho,o as ks,j as Os,p as ku}from"./ChartPrimitives-DLEICrrL.js";import{u as Au,a as Pu,b as Ru,t as Iu,e as Tu,c as mt}from"./extract-error-message-CH5Z1tok.js";import{R as an,C as rn,a as ua,X as on,Y as ln,T as cn,b as Xa,L as ma,A as Ds,d as Js,e as $u}from"./vendor-recharts-FA0uySU7.js";import{A as Mu}from"./AuditHistoryPanel-N0RYtAB2.js";import{a as Lu,b as Du}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-BpmvLvpp.js";import"./vendor-markdown-9tTeP8v7.js";import"./vendor-yaml-GWJz5H2G.js";function Gs(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 Eu(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=qu(r,1));return a}function qu(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 Ou(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 Gu(t,s){const n=Ou(t,s);return n===null?null:Math.round(n*100)}function Ca(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Gs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Gs(t.prior)} ${s})`:`Flat ${n} (${Gs(t.prior)} ${s})`}const xo=30;function qr(t){return Math.round(t*10)/10}function Fu(t){return t.prior>=xo&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${qr(t.deltaAbs)} vs ${qr(t.prior)}`}function _u(t,s,n){return t.prior>=xo&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Gs(Math.round(t.deltaAbs))} ${s} ${n}`}const Uu=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function po(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function go(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 fo(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(po).map(go).filter(Boolean)):new Set}function bo(t,s){const n=po(t).map(go).filter(Boolean).filter(a=>!Uu.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Bu(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Vu(t,s){const n=fo(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=bo(Bu(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function Ku(t){const s=fo(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=bo(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const zu=1e6;function Qu(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/zu)}const yo={queryClass:"all"},Hu=["all","non-brand","branded"];function Wu(t){return typeof t=="string"&&Hu.includes(t)}function Yu(t){const s=Wu(t.class)?t.class:yo.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 Ju(t,s){return s===null||t===null?!1:t!==s}function Xu(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===yo.queryClass?void 0:t.queryClass}}const Us=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Or={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Zu={"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."},em="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function tm(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 sm({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,u)=>u.mentions-i.mentions||(i.label<u.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(ze,{text:em})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:o.map(i=>{const u=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:`${u>0?Math.max(u,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:i.mentions}),e.jsxs("td",{className:"mention-share-share",children:[u.toFixed(1),"%"]})]},i.label)})})]})}function nm({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=l.useState("non-brand"),o=l.useId(),i=t.scope==="pooled",u=!i&&t.branded.snapshotsTotal>0,m=u?a:"non-brand",d=i?"pooled":m,p=m==="branded"?t.branded:t.breakdown,h=m==="branded"?t.breakdown:t.branded,j=tm(p,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:h.snapshotsTotal>0}),b=d==="non-brand"?Hi[t.tone]:"text-secondary";function g(f){const y=Us.findIndex(Q=>Q.value===m);let C=null;f.key==="ArrowRight"||f.key==="ArrowDown"?C=(y+1)%Us.length:f.key==="ArrowLeft"||f.key==="ArrowUp"?C=(y-1+Us.length)%Us.length:f.key==="Home"?C=0:f.key==="End"&&(C=Us.length-1),C!==null&&(f.preventDefault(),r(Us[C].value),f.currentTarget.querySelectorAll('[role="radio"]')[C]?.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(ze,{text:Zu[d]})]}),u?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:g,children:Us.map(f=>{const y=f.value===m;return e.jsx("button",{type:"button",role:"radio","aria-checked":y,tabIndex:y?0:-1,onClick:()=>r(f.value),className:`segmented-option min-h-11 ${y?"segmented-option-active":""}`,children:f.label},f.value)})}):e.jsx("span",{className:"mention-share-class",children:Or[d]})]}),j.numeric?e.jsxs("p",{className:`mention-share-value ${b}`,children:[j.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:j.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:Or[d]}),` · ${j.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),j.showRows&&e.jsx(sm,{breakdown:p,projectLabel:s,competitorDomains:n})]})}const Bs=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Gr=5;function am(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 rm(t){return t===null?"Not measured":`${t.toFixed(1)}%`}function vo(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 im({value:t,onChange:s}){function n(a){const r=Bs.findIndex(u=>u.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%Bs.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+Bs.length)%Bs.length:a.key==="Home"?o=0:a.key==="End"&&(o=Bs.length-1),o===null)return;a.preventDefault();const i=Bs[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:Bs.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 Za({row:t,isProject:s=!1,metricsAvailable:n=!0,canManage:a,onPin:r,onUnpin:o}){const i=!s&&a&&!t.pinned&&!!r,u=!s&&a&&t.pinned&&!!o,m=n&&t.sampleUrls.length>0,[d,p]=l.useState(!1),[h,j]=l.useState(null);async function b(g,f){if(!(!f||d)){p(!0),j(null);try{await f(t.domain)===!1&&j(`Could not ${g} competitor. Try again.`)}catch{j(`Could not ${g} competitor. Try again.`)}finally{p(!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":vo(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:n?rm(t.shareOfVoice):"Unavailable"}),e.jsx("td",{className:"tabular-nums text-secondary",children:n?t.mentionCount:"Unavailable"}),e.jsx("td",{className:"tabular-nums text-secondary",children:n?t.citationCount:"Unavailable"}),e.jsx("td",{className:"text-right",children:i||u||m?e.jsxs("div",{className:"flex min-w-max items-start justify-end gap-2",children:[m?e.jsxs("details",{className:"inline-disclosure text-left text-xs text-secondary",children:[e.jsx("summary",{children:"Source URLs"}),e.jsx("ul",{className:"mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal",children:t.sampleUrls.map(g=>e.jsx("li",{className:"break-all",children:g},g))})]}):null,u&&o?e.jsxs(A,{type:"button",size:"sm",variant:"outline",disabled:d,onClick:()=>{b("unpin",o)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,i&&r?e.jsxs(A,{type:"button",size:"sm",variant:"outline",disabled:d,onClick:()=>{b("pin",r)},children:["Pin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,h?e.jsx("span",{role:"alert",className:"sr-only",children:h}):null]}):e.jsx("span",{className:"text-faint",children:"—"})})]})}function er({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function om({rows:t,canManage:s,onPin:n}){const[a,r]=l.useState(!1),o=a?t:t.slice(0,Gr);return e.jsxs("tbody",{children:[e.jsx(er,{children:"Observed in this window"}),o.map(i=>e.jsx(Za,{row:{...i,pinned:!1},canManage:s,onPin:n},i.domain)),t.length>Gr?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 ",o.length," of ",t.length," observed competitors."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11 text-sm","aria-expanded":a,"aria-label":a?"Show fewer observed competitors":`Show all ${t.length} observed competitors`,onClick:()=>r(i=>!i),children:a?"Show fewer":`Show all ${t.length}`})]})})}):null]})}function lm({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,u]=l.useState(null);async function m(){const d=n.trim();if(!(!d||r)){o(!0),u(null);try{if(await t(d)===!1){u("Could not add competitor. Try again.");return}a("")}catch{u("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:d=>{d.preventDefault(),m()},"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:d=>a(d.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(A,{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 Fr({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:u,onAddCompetitor:m,error:d,onRetry:p,isLoading:h=!1,scopeLabel:j}){const b=a&&!r,g=s?.pinned??n,f=s?.observed??[],y=s?.otherSources??[],C=s?.evidence,Q=s?.marketState?.draft?.pendingCompetitorDomains.length??0;return e.jsxs("section",{"aria-labelledby":"competitor-landscape-title","aria-busy":h,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"}),j?e.jsx("p",{className:"supporting-copy mt-1",children:j}):null,s?e.jsx("p",{className:"supporting-copy mt-1",children:am(s.filters?.queryClass)}):null]}),e.jsx(im,{value:t,onChange:o})]}),d?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:d}),p?e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:p,children:"Retry competitor history"}):null]}):null,h&&!s&&g.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(er,{children:"You"}),e.jsx(Za,{row:s.project,isProject:!0,canManage:!1})]}):null,e.jsx(er,{children:"Pinned"}),g.length>0?g.map(M=>e.jsx(Za,{row:{...M,pinned:!0},metricsAvailable:!!s,canManage:b,onUnpin:u},M.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s&&f.length>0?e.jsx(om,{rows:f,canManage:b,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),C?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:[C.answeredResults," ",C.answeredResults===1?"answer":"answers"]}),C.missingAnswerTextResults>0?e.jsx("span",{className:"text-caution",children:"Answer data incomplete"}):null,C.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(Ln,{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:[f.length===0?e.jsx("p",{children:"No additional competitors were identified in this period."}):null,e.jsxs("p",{children:[C.sourceResults," ",C.sourceResults===1?"result includes":"results include"," source URLs."]}),C.missingAnswerTextResults>0?e.jsxs("p",{children:[C.missingAnswerTextResults," ",C.missingAnswerTextResults===1?"result has":"results have"," no answer text and ",C.missingAnswerTextResults===1?"is":"are"," excluded from mention share."]}):null,C.incompleteSourceResults>0?e.jsxs("p",{children:[C.incompleteSourceResults," ",C.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,C.excludedProbeResults+C.excludedNonCompletedResults>0?e.jsxs("p",{children:[C.excludedProbeResults+C.excludedNonCompletedResults," test or unfinished ",C.excludedProbeResults+C.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,y.length>0?e.jsxs("details",{className:"inline-disclosure",children:[e.jsxs("summary",{children:["Other observed sources (",y.length,")"]}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:y.map(M=>e.jsxs("li",{children:[e.jsxs("span",{children:[M.label," · ",vo(M.surfaceClass)," · ",M.citationCount," citations"]}),M.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:M.sampleUrls.map(R=>e.jsx("li",{className:"break-all",children:R},R))}):null]},M.domain))})]}):null]}),b&&m?e.jsx(lm,{onAddCompetitor:m}):null]})}function _r({state:t,label:s}){return e.jsx(de,{tone:cl(t),children:s??ll(t)})}function Ur({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"}),u=new Date(n[o].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),m=n.map((d,p)=>{const h=new Date(d.createdAt).toLocaleDateString();return`${p===o?"Latest run, ":""}${h}: ${d.citationState}${d.model?`, model ${d.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${m}`,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((d,p)=>{const h=!!(d.model&&p>0&&n[p-1]?.model&&n[p-1].model!==d.model),j=p===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[d.citationState]??"rounded-sm"} ${a[d.citationState]??"bg-mono-700"} ${h?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${j?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[d.citationState,new Date(d.createdAt).toLocaleDateString(),d.model?`model ${d.model}`:null,h?"model changed":null,j?"latest run":null].filter(Boolean).join(" · ")},`${d.runId}:${d.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function tr(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 cm=320;function dm(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function um(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function Br(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 Vr(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 Kr(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 u=t.length-1;u>=0&&t[u].citationState===r;u--)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 mm(t,s){return t.map(n=>jo(n,s))}function jo(t,s){return s==="citations"?t:{...t,citationState:Br(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Br(n,s)}))}}function zr(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",u=o==="cited"||o==="emerging";return r==="lost"||o!==null&&u&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||o!==null&&!u&&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 hm(t){const s=tr(mm(t,"mentions")),n=tr(t);return[zr(s,"mentions"),zr(n,"citations")]}function xm({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 Qr({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:hm(t).map(s=>e.jsx(xm,{signal:s},s.key))})}function pm({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=dl(),[r,o]=l.useState(new Set),[i,u]=l.useState("mentions"),[m,d]=l.useState(n),[p,h]=l.useState("all"),j=l.useMemo(()=>{const c=new Map;for(const v of t){const N=v.query,$=v.queryClass??null,D=s?v.location??null:null,w=JSON.stringify([N,$,D]),U=c.get(w)??{key:w,phrase:N,queryClass:$,location:D,items:[],rawItems:[]};U.items.push(jo(v,i)),U.rawItems.push(v),c.set(w,U)}return[...c.values()]},[t,i,s]),b=l.useMemo(()=>j.filter(c=>p==="all"||(p==="unclassified"?c.queryClass===null:c.queryClass===p)),[j,p]),g=Dn({rows:b,getSearchText:um}),f=g.rows.map(c=>c.key),y=f.length>0&&f.every(c=>r.has(c)),C=c=>{o(v=>{const N=new Set(v);return N.has(c)?N.delete(c):N.add(c),N})},Q=i==="mentions"?"mentioned":"cited",M=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:()=>u("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:()=>u("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(c=>{const v=new Set(c);for(const N of f)y?v.delete(N):v.add(N);return v})},children:y?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":m==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>d("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":m==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>d("detailed"),children:"Detailed"})]})]})]})]}),j.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(fn,{value:g.query,onChange:g.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:p,onChange:c=>{h(c.target.value),g.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:M}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:g.rows.map(({key:c,phrase:v,queryClass:N,location:$,items:D,rawItems:w})=>{const U=r.has(c),z=D.map(F=>F.citationState),B=z.includes("cited")?"cited":z.includes("emerging")?"emerging":z.includes("lost")?"lost":z.every(F=>F==="pending")?"pending":"not-cited",K=tr(D),pe=D.filter(F=>F.citationState===ul.cited||F.citationState==="emerging").length,we=Kr(K,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:()=>C(c),onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),C(c))},tabIndex:0,role:"button","aria-expanded":U,children:[e.jsx("td",{children:e.jsx(pu,{size:14,className:`transition-transform duration-150 text-muted ${U?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:v}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:$??"No location"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.jsx(de,{tone:"neutral",className:"whitespace-nowrap",children:dm(N)}),D.map(F=>e.jsx(Mn,{provider:F.provider},F.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{state:B,label:Vr(B,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${pe} of ${D.length} engines ${R}`,children:[pe,"/",D.length]})]})}),e.jsx("td",{children:e.jsx(Ur,{history:K})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:we}),e.jsx(Qr,{items:w})]}),e.jsx("td",{})]}),U&&D.map((F,te)=>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(Mn,{provider:F.provider})}),e.jsx("td",{children:e.jsx(_r,{state:F.citationState,label:Vr(F.citationState,i)})}),e.jsx("td",{children:e.jsx(Ur,{history:F.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:Kr(F.runHistory,i)}),e.jsx(Qr,{items:[w[te]??F]})]}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",size:"sm",type:"button",onClick:ie=>{ie.stopPropagation(),a(F.id)},children:"View"})})]}),m==="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(bm,{item:F,onViewFull:()=>a(F.id)})})]})]},F.id))]},c)})})]})}),g.totalRows===0&&(g.hasQuery||p!=="all")?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(en,{page:g.page,pageSize:g.pageSize,visibleRows:g.rows.length,totalRows:g.totalRows,onPageChange:g.setPage,itemLabel:g.hasQuery||p!=="all"?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",Q==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function gm(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=hl(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 Hr(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function fm(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 bm({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}=fm(t.answerSnippet,cm),o=gm(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:ml(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] ${Hr(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,Hr(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 Vn({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 fa({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 ka=nt[0],Aa=nt[1],Wr=nt[2],Yr=nt[3],ym=["both","server","ga4"],Jr={fontSize:11,paddingTop:6},Xr=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Zr=t=>typeof t=="number"?Gs(Math.round(t)):String(t),Xt=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function Pa(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 Ra({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(ze,{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 vm(t,s){return n=>{const{cx:a,cy:r,index:o,key:i}=n,u=o??-1;return!(t[u]!=null&&t[u-1]==null&&t[u+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 jm({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,u]=l.useState("both"),m=Au(t,{sinceMinutes:s,granularity:"day",limit:1}),d=Pu(t),h=Re({...Wi({client:V,path:{name:t}}),enabled:!!t,staleTime:Ys}).data?.connected===!0,j=Re({...Yi({client:V,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&h,staleTime:Ys}),b=l.useMemo(()=>m.data?.series?.points??[],[m.data]),g=l.useMemo(()=>{const $=j.data;return new Map(($?.days??[]).map(D=>[D.date,D.sessions]))},[j.data]),f=l.useMemo(()=>{const $=w=>w.measured!==!1;if(b.length===0||$(b[0]))return null;const D=b.findIndex($)-1;return D<0?{from:b[0].bucket,to:b[b.length-1].bucket}:{from:b[0].bucket,to:b[D].bucket}},[b]),y=m.data?.series?.coverageStart??null,C=m.data?.series?.trends,Q=l.useMemo(()=>{const $=Pa(C?.crawlerContentHits,b.length),D=Pa(C?.aiUserFetchHits,b.length),w=Pa(C?.aiReferralLandedHits,b.length);return b.map((U,z)=>({...U,crawlerContentHits:U.measured!==!1?Xt(U.crawlerContentHits):null,aiUserFetchHits:U.measured!==!1?Xt(U.aiUserFetchHits):null,aiReferralLandedHits:U.measured!==!1?Xt(U.aiReferralLandedHits):null,ga4Visits:g.get(U.bucket)??null,crawlTrend:$[z],fetchTrend:D[z],visitTrend:w[z]}))},[b,g,C]),M=m.data?.totals,R=M&&{crawlers:Xt(M.crawlerContentHits),fetches:Xt(M.aiUserFetchHits),visits:Xt(M.aiReferralLandedHits)},c=l.useMemo(()=>b.reduce(($,D)=>({crawlers:$.crawlers+Xt(D.crawlerContentHits),fetches:$.fetches+Xt(D.aiUserFetchHits),visits:$.visits+Xt(D.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[b]),v=R??c,N=v.crawlers>0||v.fetches>0||v.visits>0;if(m.isLoading)return e.jsx(xe,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(m.isError)return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!N){const $=d.data?.sources,D=$!==void 0&&$.length===0,w=!D&&y===null;return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:D?"No server-side traffic source connected yet.":w?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:D?"Connect a traffic source to see how AI engines read this site over time.":w?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Ra,{label:"AI crawlers",value:Gs(v.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(Ra,{label:"AI page fetches",value:Gs(v.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(Ra,{label:"AI visitors",value:Gs(v.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),b.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:Xt(b[b.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:Xt(b[b.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:Xt(b[b.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:g.get(b[b.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(ze,{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:$=>a($.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:$=>o($.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(an,{width:"100%",height:206,children:e.jsxs(rn,{data:Q,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(ua,{stroke:da,vertical:!1}),e.jsx(on,{dataKey:"bucket",tick:Kt,stroke:ls,tickFormatter:nn,minTickGap:28}),e.jsx(ln,{tick:Kt,stroke:ls,width:48,allowDecimals:!1}),e.jsx(cn,{contentStyle:ss.contentStyle,labelStyle:ss.labelStyle,itemStyle:ss.itemStyle,labelFormatter:Ot,formatter:Zr}),f&&e.jsx(Xa,{x1:f.from,x2:f.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(ma,{wrapperStyle:Jr,iconType:"plainline",iconSize:14,formatter:$=>Xr.has($)?"":$}),e.jsx(Ds,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:ka,fill:ka,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Ds,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Aa,fill:Aa,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Js,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:ka,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Js,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Aa,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(ze,{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(fa,{windows:ym,value:i,onChange:u,label:"Visit measurement source",formatOption:$=>$==="ga4"?"GA4":$==="both"?"Both":"Server"})]}),e.jsx(an,{width:"100%",height:176,children:e.jsxs(rn,{data:Q,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(ua,{stroke:da,vertical:!1}),e.jsx(on,{dataKey:"bucket",tick:Kt,stroke:ls,tickFormatter:nn,minTickGap:28}),e.jsx(ln,{tick:Kt,stroke:ls,width:48,allowDecimals:!1}),e.jsx(cn,{contentStyle:ss.contentStyle,labelStyle:ss.labelStyle,itemStyle:ss.itemStyle,labelFormatter:Ot,formatter:Zr}),f&&e.jsx(Xa,{x1:f.from,x2:f.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(ma,{wrapperStyle:Jr,iconType:"plainline",iconSize:14,formatter:$=>Xr.has($)?"":$}),i!=="ga4"&&e.jsx(Js,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Wr,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Js,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Yr,strokeWidth:1.8,strokeDasharray:"5 3",dot:vm(Q.map($=>$.ga4Visits),Yr)}),r&&i!=="ga4"&&e.jsx(Js,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Wr,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const Nm=6,vn="__other__",bn="_socialTotal";function wm(t,s=Nm){const n=new Map;for(const p of t)n.set(p.source,(n.get(p.source)??0)+p.sessions);const a=[...n.entries()].sort((p,h)=>h[1]!==p[1]?h[1]-p[1]:p[0].localeCompare(h[0])),r=a.slice(0,s),o=new Set(r.map(([p])=>p)),i=Math.max(0,a.length-s),u=new Map;for(const p of t){let h=u.get(p.date);h||(h={date:p.date,[bn]:0},u.set(p.date,h));const j=o.has(p.source)?p.source:vn;h[j]=(h[j]??0)+p.sessions,h[bn]=(h[bn]??0)+p.sessions}const m=[...u.values()].sort((p,h)=>String(p.date).localeCompare(String(h.date))),d=r.map(([p])=>p);return i>0&&d.push(vn),{data:m,sources:d,otherCount:i}}function yn(t){return t.replace(/\+/g," ")}function No(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const ei="_totalSessions",ti="_organicSessions";function Sm(t,s){const n=new Map;for(const i of s)n.set(i.date,{[ei]:i.sessions,[ti]:i.organicSessions});for(const i of t.days){let u=n.get(i.date);u||(u={[ei]:0,[ti]:0},n.set(i.date,u));for(const m of i.bySource)u[m.source]=(u[m.source]??0)+m.sessions}const a=[...n.entries()].sort(([i],[u])=>i.localeCompare(u)).map(([i,u])=>({date:i,...u})),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 Cm=["7d","30d","90d"],km={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Ls=nt,sr=as.textDim,wo=as.textFaint,Sn=25;function Am(t){return uo(t.landingPage)}const Pm=25,Rm=10,Ia={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Kn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function So(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 Im({projectName:t}){const{data:s,isLoading:n,isError:a}=Ru(t);if(n)return e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(xe,{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."," ",!ee()&&e.jsx(bs,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(xe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ee()&&e.jsxs(e.Fragment,{children:[e.jsx(bs,{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(xe,{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:Iu(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?So(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ee()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(bs,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function Tm({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Im,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(fa,{windows:Cm,value:s,onChange:n,label:"Traffic time period"})}),e.jsx($m,{projectName:t,window:s}),e.jsx(jm,{projectName:t,sinceMinutes:km[s]})]})}function $m({projectName:t,window:s}){const n=As(),a=s??"30d",[r,o]=l.useState(null),[i,u]=l.useState(null),[m,d]=l.useState(!0),[p,h]=l.useState(!1),[j,b]=l.useState(!1),[g,f]=l.useState(null),[y,C]=l.useState(null),[Q,M]=l.useState("sessions"),[R,c]=l.useState("desc"),[v,N]=l.useState("sessions"),[$,D]=l.useState("desc"),[w,U]=l.useState("sessions"),[z,B]=l.useState("desc"),[K,pe]=l.useState("sessions"),[we,F]=l.useState("desc"),[te,ie]=l.useState(Ia),[Y,H]=l.useState([]),[P,ae]=l.useState([]),[le,O]=l.useState(!1);async function W(q){d(!0),f(null);try{const Ce=await n.fetchQuery({...Wi({client:V,path:{name:t}}),staleTime:Ys});if(q.current)return;if(o(Ce),!Ce.connected){u(null),ie(Ia),H([]),ae([]),d(!1);return}const ye=a==="all"?void 0:a,je=await n.fetchQuery({...xl({client:V,path:{name:t},query:ye?{window:ye}:void 0}),staleTime:Ys}).then(rs=>rs),ft=je.windowStart||je.windowEnd?{...je.windowStart?{startDate:je.windowStart}:{},...je.windowEnd?{endDate:je.windowEnd}:{}}:void 0,[Je,At,Nt]=await Promise.all([n.fetchQuery({...Yi({client:V,path:{name:t},query:ye?{window:ye}:void 0}),staleTime:Ys}).catch(()=>Ia),n.fetchQuery({...pl({client:V,path:{name:t},query:ye?{window:ye}:void 0}),staleTime:Ys}).catch(()=>[]),n.fetchQuery({...gl({client:V,path:{name:t},query:ft}),staleTime:Ys}).catch(()=>[])]);if(q.current)return;u(je),ie(Je),H(At),ae(Nt),d(!1)}catch(Ce){if(q.current)return;f(Ce instanceof Error?Ce.message:"Failed to load GA4 data"),d(!1)}}l.useEffect(()=>{const q={current:!1};return W(q),()=>{q.current=!0}},[t,a,n]);async function ue(){h(!0),f(null),C(null);try{const q=await Ji(t);C(`Synced ${q.rowCount.toLocaleString()} page rows, ${q.aiReferralCount.toLocaleString()} AI and ${q.socialReferralCount.toLocaleString()} social referral rows (${q.days} days)`),await yt(n,"ga"),await W({current:!1})}catch(q){f(q instanceof Error?q.message:"Sync failed")}finally{h(!1)}}async function _(){b(!0),f(null),C(null);try{await fl(t),await yt(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),u(null),C("GA4 disconnected")}catch(q){f(q instanceof Error?q.message:"Disconnect failed")}finally{b(!1)}}function Z(q){Ae.setPage(1),Q===q?c(Ce=>Ce==="desc"?"asc":"desc"):(M(q),c("desc"))}function fe(q){v===q?D(Ce=>Ce==="desc"?"asc":"desc"):(N(q),D("desc"))}function Fe(q){w===q?B(Ce=>Ce==="desc"?"asc":"desc"):(U(q),B("desc"))}const Le=l.useMemo(()=>i?.topPages?[...i.topPages].sort((q,Ce)=>{const ye=q[Q],je=Ce[Q];return typeof ye=="string"&&typeof je=="string"?R==="asc"?ye.localeCompare(je):je.localeCompare(ye):R==="asc"?ye-je:je-ye}):[],[i?.topPages,Q,R]),Ae=Dn({rows:Le,getSearchText:q=>uo(q.landingPage),pageSize:Rm}),Xe=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((q,Ce)=>{const ye=q[v],je=Ce[v];return typeof ye=="string"&&typeof je=="string"?$==="asc"?ye.localeCompare(je):je.localeCompare(ye):$==="asc"?ye-je:je-ye}):[],[i?.aiReferrals,v,$]),lt=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((q,Ce)=>{const ye=q[K],je=Ce[K];return typeof ye=="string"&&typeof je=="string"?we==="asc"?ye.localeCompare(je):je.localeCompare(ye):we==="asc"?ye-je:je-ye}):[],[i?.aiReferralLandingPages,K,we]),Se=Dn({rows:lt,getSearchText:Am,pageSize:Pm}),et=Se.totalRows>0?`${Se.totalRows.toLocaleString()} ${Se.hasQuery?Se.totalRows===1?"match":"matches":Se.totalRows===1?"row":"rows"}`:Se.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Ve(q){Se.setPage(1),K===q?F(Ce=>Ce==="desc"?"asc":"desc"):(pe(q),F("desc"))}const _e=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((q,Ce)=>{const ye=q[w],je=Ce[w];return typeof ye=="string"&&typeof je=="string"?z==="asc"?ye.localeCompare(je):je.localeCompare(ye):z==="asc"?ye-je:je-ye}):[],[i?.socialReferrals,w,z]),{socialChartData:Ue,socialChartSources:Ie,socialOtherCount:G}=l.useMemo(()=>{const q=wm(P);return{socialChartData:q.data,socialChartSources:q.sources,socialOtherCount:q.otherCount}},[P]),{chartData:T,chartSources:E,dateRange:he}=l.useMemo(()=>{const q=Sm(te,Y);return{chartData:q.data,chartSources:q.sources,dateRange:q.dateRange}},[te,Y]);if(m&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return ee()?e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Mm,{projectName:t,onConnected:()=>{(async()=>(await yt(n,"ga"),await W({current:!1})))()}});const be=i?.organicSharePctDisplay??"0%",J=i?.channelBreakdown?.organic.sharePctDisplay??be,Ze=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,zt=i?.aiSessionsDeduped??0,Ye=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,Te=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",$e=i?.paidAiSessionsBySession??0,pt=i?.paidAiSharePctBySessionDisplay??"0%",ct=i?new Set(i.aiReferrals.map(q=>q.source.toLowerCase())).size:0,Oe=Xe[0]??null,Qe=i?.totalDirectSessions??0,vt=i?.directSharePctDisplay??"0%",Ke=i?.channelBreakdown?.direct.sessions??Qe,Ee=i?.channelBreakdown?.direct.sharePctDisplay??vt,qe=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,jt=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ge=i?.socialSessions??0,It=i?.socialSharePctDisplay??"0%",Gt=i?.channelBreakdown?.social.sessions??Ge,gt=i?.channelBreakdown?.social.sharePctDisplay??It,kt=i?new Set(i.socialReferrals.map(q=>q.source.toLowerCase())).size:0,ht=_e[0]??null;return e.jsxs(e.Fragment,{children:[g&&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:g}),y&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:y}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!ee()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:p,onClick:De(ue),children:[e.jsx(la,{className:`w-3.5 h-3.5 mr-1.5 ${p?"animate-spin":""}`}),p?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:j,onClick:De(_),children:[e.jsx(gu,{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(ze,{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(Ta,{value:Kn(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ta,{value:Kn(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${be} of total`,tone:"positive"}),e.jsx(Ta,{value:i.totalUsers===null?"—":Kn(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."}),!ee()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:p,onClick:De(ue),children:[e.jsx(la,{className:`w-3.5 h-3.5 mr-1.5 ${p?"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(ze,{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."})]})]}),he&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(he.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(he.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),T.length>0&&e.jsxs(xe,{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:E.length>0?"AI vs. total sessions":"All sessions (baseline)"}),E.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),E.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(an,{width:"100%",height:"100%",children:e.jsxs(rn,{data:T,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(on,{dataKey:"date",tick:Kt,tickLine:!1,axisLine:{stroke:ls},tickFormatter:nn}),e.jsx(ln,{tick:Kt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(cn,{...ss,labelFormatter:Ot,formatter:(q,Ce)=>{const ye=typeof q=="number"?q.toLocaleString():String(q??0),je=String(Ce??"");return je==="_totalSessions"?[ye,"Total Sessions"]:je==="_organicSessions"?[ye,"Organic Sessions"]:[ye,je]}}),e.jsx(ma,{wrapperStyle:{fontSize:11,color:as.text},formatter:q=>q==="_totalSessions"?"Total Sessions":q==="_organicSessions"?"Organic Sessions":q}),e.jsx(Ds,{type:"monotone",dataKey:"_totalSessions",stroke:as.textFaint,fill:as.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),E.map((q,Ce)=>e.jsx(Ds,{type:"monotone",dataKey:q,stackId:"ai",stroke:Ls[Ce%Ls.length],fill:Ls[Ce%Ls.length],fillOpacity:.4,strokeWidth:1.5},q))]})})})]}),e.jsxs(xe,{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(os,{label:"Organic",value:J,hint:`${Ze.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(os,{label:"Social",value:gt,hint:`${Gt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(os,{label:"Direct",value:Ee,hint:`${Ke.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(os,{label:"Visitors from AI (at least)",value:Te,hint:$e>0?`${Ye.toLocaleString()} sessions · ${$e.toLocaleString()} paid`:`${Ye.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(os,{label:"Other channels",value:jt,hint:`${qe.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."})]}),Oe&&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:Oe.source})," via ",Oe.medium,", accounting for ",Oe.sessions.toLocaleString()," sessions.",$e>0&&e.jsxs("span",{children:[" Paid AI: ",$e.toLocaleString()," sessions (",pt,")."]})]})]}),e.jsxs(xe,{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?`${ct} 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(Zt,{label:"Source",sortKey:"source",current:v,dir:$,onSort:fe,align:"left"}),e.jsx(Zt,{label:"Medium",sortKey:"medium",current:v,dir:$,onSort:fe,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(Zt,{label:"Sessions",sortKey:"sessions",current:v,dir:$,onSort:fe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Xe.map(q=>e.jsx(Dm,{referral:q,totalSessions:zt},`${q.source}:${q.medium}:${q.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(xe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:et})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(fn,{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(Zt,{label:"Landing Page",sortKey:"landingPage",current:K,dir:we,onSort:Ve,align:"left"}),e.jsx(Zt,{label:"Source",sortKey:"source",current:K,dir:we,onSort:Ve,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Zt,{label:"Sessions",sortKey:"sessions",current:K,dir:we,onSort:Ve,align:"right"})]})}),e.jsx("tbody",{children:Se.rows.map(q=>e.jsx(Em,{row:q},`${q.landingPage}:${q.source}:${q.medium}:${q.sourceDimension}`))})]})}),e.jsx(en,{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(ze,{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(xe,{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(os,{label:"Social Sessions",value:Kn(Ge),hint:`${Ge.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(os,{label:"Share of Traffic",value:It,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(os,{label:"Platforms",value:String(kt),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."})]}),ht&&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:`${ht.source} via ${ht.medium}`,children:No(yn(ht.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:ht.medium,children:["via ",yn(ht.medium)," · ",ht.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(os,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(os,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(os,{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."})]})]})]}),Ue.length>0&&e.jsxs(xe,{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"})]}),G>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ie.length-1," sources · ",G," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(an,{width:"100%",height:"100%",children:e.jsxs(rn,{data:Ue,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(on,{dataKey:"date",tick:Kt,tickLine:!1,axisLine:{stroke:ls},tickFormatter:nn}),e.jsx(ln,{tick:Kt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(cn,{...ss,labelFormatter:Ot,formatter:(q,Ce)=>{const ye=typeof q=="number"?q.toLocaleString():String(q??0),je=String(Ce??"");if(je===bn)return[ye,"Total Social"];if(je===vn){const ft=`Other (${G} source${G===1?"":"s"})`;return[ye,ft]}return[ye,yn(je)]}}),e.jsx(Ds,{type:"monotone",dataKey:bn,stroke:wo,fill:as.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ie.map((q,Ce)=>{const je=q===vn?sr:Ls[Ce%Ls.length];return e.jsx(Ds,{type:"monotone",dataKey:q,stackId:"social",stroke:je,fill:je,fillOpacity:.4,strokeWidth:1.5},q)})]})})}),e.jsx(Om,{sources:Ie,otherCount:G})]}),e.jsxs(xe,{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?_e.length>Sn&&!le?`Top ${Sn} of ${_e.length}`:`${_e.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(Zt,{label:"Source",sortKey:"source",current:w,dir:z,onSort:Fe,align:"left"}),e.jsx(Zt,{label:"Medium",sortKey:"medium",current:w,dir:z,onSort:Fe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Zt,{label:"Sessions",sortKey:"sessions",current:w,dir:z,onSort:Fe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(le?_e:_e.slice(0,Sn)).map(q=>e.jsx(qm,{referral:q,totalSessions:Ge},`${q.source}:${q.medium}:${q.channelGroup}`))})]})}),_e.length>Sn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>O(q=>!q),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 ${Sn}`:`Show all ${_e.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(ze,{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(fn,{value:Ae.query,onChange:Ae.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(Zt,{label:"Landing Page",sortKey:"landingPage",current:Q,dir:R,onSort:Z,align:"left"}),e.jsx(Zt,{label:"Sessions",sortKey:"sessions",current:Q,dir:R,onSort:Z,align:"right"}),e.jsx(Zt,{label:"Organic",sortKey:"organicSessions",current:Q,dir:R,onSort:Z,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Ae.rows.map(q=>e.jsx(Lm,{page:q},q.landingPage))})]})}),Ae.totalRows===0&&Ae.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(en,{page:Ae.page,pageSize:Ae.pageSize,visibleRows:Ae.rows.length,totalRows:Ae.totalRows,onPageChange:Ae.setPage,itemLabel:Ae.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 ${So(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Mm({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,u]=l.useState(null),[m,d]=l.useState(!1),[p,h]=l.useState(null),j=l.useRef(null),b=l.useCallback(f=>{const y=f.target.files?.[0];if(!y)return;h(null),o(y.name);const C=new FileReader;C.onload=()=>{const Q=C.result;try{const M=JSON.parse(Q);if(!M.client_email||!M.private_key){h("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),u(null);return}u(Q)}catch{h("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},C.onerror=()=>{h("Failed to read file."),u(null)},C.readAsText(y)},[]);async function g(){if(h(null),!n.trim()){h("Property ID is required.");return}if(!i){h("Please upload a service account key file.");return}d(!0);try{await bl(t,{propertyId:n.trim(),keyJson:i});try{await Ji(t)}catch{}s()}catch(f){h(f instanceof Error?f.message:"Failed to connect GA4")}finally{d(!1)}}return e.jsxs(xe,{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."}),p&&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:p}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:f=>a(f.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:j,type:"file",accept:".json,application/json",onChange:b,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>j.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(fu,{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(A,{variant:"default",size:"sm",disabled:m||!n.trim()||!i,onClick:De(g),children:m?"Connecting & syncing…":"Connect GA4"})]})}function Zt({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 Co={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Ta({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 ${Co[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function os({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(ze,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Co[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Lm({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 ko={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Ao={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 Dm({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=ko[t.sourceDimension]??t.sourceDimension,r=Ao[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 Em({row:t}){const s=ko[t.sourceDimension]??t.sourceDimension,n=Ao[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(na,{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 qm({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=yn(t.source),o=yn(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 Om({sources:t,otherCount:s}){const n=[{key:bn,color:wo,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===vn)n.push({key:vn,color:sr,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=yn(r);n.push({key:r,color:Ls[a%Ls.length]??sr,label:No(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 Gm(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 Fm=["7d","30d","90d","all"],zn=500,si=[{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:tn.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:nt[2],inverted:!0,format:t=>t.toFixed(1)}],Ts=25,_m="canonry:google-oauth-complete",Um=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function Bm(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 m=t.prior[s],d=t.trailing[s];return m!==null&&d!==null&&m<=0&&d>0?`new in the last ${a}d`:m===null||m<=0?`no prior ${a}d to compare`:d===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%":`${Um.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function Vm(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}`,u=`${r.startDate} to ${r.endDate}`,m=`Tile percentages compare these ${s} ${o} (${u}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?m:`${m} 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 ni(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function ai(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 ri(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Km({projectName:t,refreshNonce:s}){const n=As(),[a,r]=l.useState(!1),[o,i]=l.useState([]),[u,m]=l.useState([]),[d,p]=l.useState([]),[h,j]=l.useState(null),[b,g]=l.useState([]),[f,y]=l.useState([]),[C,Q]=l.useState(null),[M,R]=l.useState(""),[c,v]=l.useState(""),[N,$]=l.useState("30"),[D,w]=l.useState(!1),[U,z]=l.useState("30d"),[B,K]=l.useState(["clicks","impressions"]),[pe,we]=l.useState(!0),[F,te]=l.useState(null),[ie,Y]=l.useState(0),[H,P]=l.useState({startDate:"",endDate:"",query:"",page:""}),[ae,le]=l.useState(0),[O,W]=l.useState(!1),[ue,_]=l.useState(0),[Z,fe]=l.useState(!1),[Fe,Le]=l.useState(""),[Ae,Xe]=l.useState(!0),[lt,Se]=l.useState(!1),[et,Ve]=l.useState(!1),[_e,Ue]=l.useState(!1),[Ie,G]=l.useState(!1),[T,E]=l.useState(!1),[he,be]=l.useState(!1),[J,Ze]=l.useState(null),[zt,Ye]=l.useState(!1),[Te,$e]=l.useState(!1),[pt,ct]=l.useState(null),[Oe,Qe]=l.useState(null),[vt,Ke]=l.useState([]),[Ee,qe]=l.useState(new Set),[jt,Ge]=l.useState({}),[It,Gt]=l.useState(new Set),[gt,kt]=l.useState(""),[ht,q]=l.useState(null),[Ce,ye]=l.useState(""),[je,ft]=l.useState(!1),[Je,At]=l.useState(!1),[Nt,rs]=l.useState(!1),[is,ds]=l.useState(!1),[rt,us]=l.useState("indexed"),[dt,ys]=l.useState(null),Wt=!!(H.query.trim()||H.page.trim()||dt),Ft=dt!==null,Yt=l.useMemo(()=>{if(!dt)return d;const{key:x,dir:L}=dt;return[...d].sort((ne,me)=>{const Be=x===Xs.CTR?Number.isFinite(ne.ctr)?ne.ctr:0:ne[x],He=x===Xs.CTR?Number.isFinite(me.ctr)?me.ctr:0:me[x];return L==="asc"?Be-He:He-Be})},[d,dt]),wt=Dn({rows:Yt,pageSize:Ns}),ms=Z?wt.rows:Yt,Qt=Dn({rows:(pt??[]).filter(x=>x.path.toLowerCase().includes(gt.trim().toLowerCase())),pageSize:Ns}),[bt,vs]=l.useState([]),[Pt,hs]=l.useState(null),[xs,ps]=l.useState(1),St=l.useMemo(()=>{if(bt.length<2)return null;const x=bt[bt.length-1],L=bt[bt.length-2];return{indexed:x.indexed-L.indexed,notIndexed:x.notIndexed-L.notIndexed}},[bt]);l.useEffect(()=>{ps(1)},[J,rt,Pt]);const I=l.useMemo(()=>Pt?(J?.reasonGroups??[]).find(x=>x.reason===Pt):void 0,[J,Pt]),X=l.useMemo(()=>J?rt==="indexed"?J.indexed:rt==="deindexed"?J.deindexed:rt==="notIndexed"?Pt?I?.urls??[]:(J.reasonGroups??[]).length===0?J.notIndexed:[]:[]:[],[J,rt,Pt,I]),ge=Math.max(1,Math.ceil(X.length/Ts)),se=Math.min(Math.max(1,xs),ge),re=(se-1)*Ts,Me=l.useMemo(()=>J?.indexed.slice(re,re+Ts)??[],[J,re]),Tt=l.useMemo(()=>J?.notIndexed.slice(re,re+Ts)??[],[J,re]),ut=l.useMemo(()=>J?.deindexed.slice(re,re+Ts)??[],[J,re]),Ps=l.useMemo(()=>(I?.urls??[]).slice(re,re+Ts),[I,re]),[S,oe]=l.useState(!1),[at,Pe]=l.useState(null),[it,Jt]=l.useState(null),[$t,_t]=l.useState(null);function Ht(x,L){const ne=Tu(x),me=Gm(ne);me?(Jt(me),Pe(null)):(Jt(null),Pe(ne.message||L))}const Mt=o.find(x=>x.connectionType==="gsc"),js=(Mt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),Nn=vt.length>0?vt:(pt??[]).map(x=>x.path),Fn=Nn.filter(x=>pt?.some(L=>L.path===x&&L.isSitemapsIndex)).length,dn=Fn===1?"Resubmit sitemap index":Fn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",k=d.length>0||b.length>0||f.length>0,ce=yl(),Ne=vl();async function Ut(x,L=!1){if(!x){m([]),R("");return}Ve(!0);try{const{sites:ne}=await n.fetchQuery({...Ll({client:V,path:{name:t}}),staleTime:L?0:qt});m(ne),R(x.propertyId??ne[0]?.siteUrl??""),Jt(null)}catch(ne){m([]),Ht(ne,"Failed to load Search Console properties")}finally{Ve(!1)}}async function Bt(x){G(!0);const L=x??ae;try{const ne=Wt?zn:Ns,me=Wt?0:L,Be={limit:String(ne)};H.startDate&&(Be.startDate=H.startDate),H.endDate&&(Be.endDate=H.endDate),H.query&&(Be.query=H.query),H.page&&(Be.page=H.page),me>0&&(Be.offset=String(me)),U&&U!=="all"&&!H.startDate&&(Be.window=U);const He=await n.fetchQuery({...wl({client:V,path:{name:t},query:Be}),staleTime:qt}),tt=He.rows;Wt?(W(!1),p(tt),_(tt.length),fe(!0)):(W(me+tt.length<He.totalMatching),p(tt),_(0),fe(!1))}catch(ne){p([]),W(!1),_(0),Pe(ne instanceof Error?ne.message:"Failed to load GSC performance data")}finally{G(!1)}}async function ya(){try{const x={};H.startDate&&(x.startDate=H.startDate),H.endDate&&(x.endDate=H.endDate),U&&U!=="all"&&!H.startDate&&(x.window=U);const L=await n.fetchQuery({...Nl({client:V,path:{name:t},query:x}),staleTime:qt});j(L)}catch{j(null)}}async function _n(x=!1){E(!0);try{const L=Fe.trim()||void 0,ne={limit:"20"};L&&(ne.url=L);const[me,Be]=await Promise.all([n.fetchQuery({...$l({client:V,path:{name:t},query:ne}),staleTime:x?0:qt}),n.fetchQuery({...Ml({client:V,path:{name:t}}),staleTime:x?0:qt})]);g(me),y(Be)}catch(L){g([]),y([]),Pe(L instanceof Error?L.message:"Failed to load GSC inspection history")}finally{E(!1)}}async function wr(x=!1){Ye(!0);try{const[L,ne]=await Promise.all([n.fetchQuery({...kl({client:V,path:{name:t}}),staleTime:x?0:qt}),n.fetchQuery({...Al({client:V,path:{name:t}}),staleTime:x?0:qt}).catch(()=>[])]);Ze(L),vs(ne)}catch(L){Ze(null),vs([]),Pe(L instanceof Error?L.message:"Failed to load coverage data")}finally{Ye(!1)}}async function Sr(x){oe(!0),Pe(null);try{const L=await Mr(t,{urls:x}),{succeeded:ne,failed:me,total:Be}=L.summary;ke({title:"Indexing requested",detail:me===0?`${ne} URL${ne!==1?"s":""} submitted for indexing.`:`${ne}/${Be} submitted successfully, ${me} failed.`,tone:me===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(L){Pe(L instanceof Error?L.message:"Failed to request indexing")}finally{oe(!1)}}async function Jo(){oe(!0),Pe(null);try{const x=await Mr(t,{urls:[],allUnindexed:!0}),{succeeded:L,failed:ne,total:me}=x.summary;ke({title:"Indexing requested",detail:ne===0?`${L} unindexed URL${L!==1?"s":""} submitted for indexing.`:`${L}/${me} submitted successfully, ${ne} failed.`,tone:ne===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(x){Pe(x instanceof Error?x.message:"Failed to request indexing")}finally{oe(!1)}}async function va(){$e(!0),Pe(null);try{const x=await Na(t);n.setQueryData(Pl({client:V,path:{name:t}}),x),ct(x.sitemaps),Qe(x.summary),Ke(x.preferredSubmissionUrls),qe(new Set),Ge({}),x.sitemaps.length===0&&_t("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(x){Pe(x instanceof Error?x.message:"Failed to list sitemaps")}finally{$e(!1)}}async function Xo(x){const L=Ee.has(x);if(qe(ne=>{const me=new Set(ne);return L?me.delete(x):me.add(x),me}),!(L||jt[x])){Gt(ne=>new Set(ne).add(x));try{const ne=await Na(t,x);Ge(me=>({...me,[x]:ne.sitemaps}))}catch(ne){Pe(ne instanceof Error?ne.message:"Failed to load sitemap files")}finally{Gt(ne=>{const me=new Set(ne);return me.delete(x),me})}}}async function un(x){if(!js||x.length===0)return;const L=[...new Set(x)];At(!0),Pe(null),q({completed:0,total:L.length});let ne=0,me=0,Be=0,He=null;try{for(let Ct=0;Ct<L.length;Ct+=50){const st=L.slice(Ct,Ct+50);try{const ve=await Rl(t,st);ne+=ve.summary.accepted,me+=ve.summary.failed,Be+=st.length,q({completed:Be,total:L.length})}catch(ve){Be+=st.length;const Rs=st.length,wn=L.length-Be,Un=ve instanceof Error?ve.message:"The batch request failed",Is=`${ne} accepted, ${me} failed, ${Rs} unconfirmed, ${wn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;He=`Sitemap submission stopped after a batch request failed. ${Is} ${Un}`,Pe(He),ke({title:"Sitemap resubmission partially completed",detail:Is,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const tt=L.length;ke({title:me===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:me===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ne}/${tt} sitemap submissions; ${me} failed. Indexing is not guaranteed.`,tone:me===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),ye("")}catch(tt){Pe(tt instanceof Error?tt.message:"Failed to submit sitemap to Google")}finally{At(!1),q(null),await va(),He&&Pe(He)}}async function Zo(){At(!0);const x=pt??[];try{const L=x.filter(me=>me.isSitemapsIndex),ne=[];for(let me=0;me<L.length;me+=4)(await Promise.all(L.slice(me,me+4).map(async He=>{const tt=jt[He.path];if(tt)return tt;const Ct=await Na(t,He.path);return Ge(st=>({...st,[He.path]:Ct.sitemaps})),Ct.sitemaps}))).forEach((He,tt)=>{ne.push(...He.length>0?He.map(Ct=>Ct.path):[L[me+tt].path])});await un([...x.filter(me=>!me.isSitemapsIndex).map(me=>me.path),...ne])}catch(L){Pe(L instanceof Error?L.message:"Failed to load sitemap files"),At(!1)}}async function Cr(x){ft(!0),Pe(null);try{await Il(t,"gsc",x),await yt(n,"google"),i(L=>L.map(ne=>ne.connectionType==="gsc"?{...ne,sitemapUrl:x}:ne)),ke({title:"Default sitemap updated",detail:x,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(L){Pe(L instanceof Error?L.message:"Failed to set the default sitemap")}finally{ft(!1)}}async function kr(x){try{await Ne.mutateAsync({projectName:t,projectLabel:t,opts:x?{sitemapUrl:x}:void 0})}catch{}}async function Ar(){Xe(!0),Pe(null);try{const[x,L]=await Promise.all([Xi().catch(()=>null),n.fetchQuery({...dr({client:V,path:{name:t}}),staleTime:qt}).catch(()=>[])]);r(!!x?.google?.configured),i(L);const ne=L.find(me=>me.connectionType==="gsc");await Promise.all([Ut(ne),Bt(),ya(),_n(),wr(),ne?.propertyId?va():Promise.resolve()])}finally{Xe(!1)}}l.useEffect(()=>{Ar()},[t,s]),l.useEffect(()=>{le(0),te(null),P(x=>x.startDate||x.endDate?{...x,startDate:"",endDate:""}:x),Y(x=>x+1),ya()},[U]);const Pr=l.useRef(!1);l.useEffect(()=>{if(!Pr.current){Pr.current=!0;return}le(0),wt.setPage(1),Bt(0)},[ie]);function ja(x){const L=F===x?null:x;te(L),P(ne=>({...ne,startDate:L??"",endDate:L??""})),Y(ne=>ne+1)}const Rr=l.useRef(!1);l.useEffect(()=>{if(!Rr.current){Rr.current=!0;return}le(0),Bt(0)},[Ft]);async function Ir(){if(!a){Pe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Se(!0),Pe(null),_t(null);try{let x=function(ve){if(ve.source!==me||ve.origin!==Be||!ve.data||typeof ve.data!="object")return;const Rs=ve.data;Rs.type!==_m||Rs.connectionType!=="gsc"||st(!0)};const{authUrl:L,redirectUri:ne}=await Cl(t,"gsc");if(!L.startsWith("https://accounts.google.com/")){Pe("Unexpected OAuth redirect URL. Please try again.");return}const me=window.open(L,"_blank","width=600,height=700");if(!me){window.location.assign(L);return}const Be=ne?new URL(ne).origin:window.location.origin;let He=!1,tt=null;const Ct=()=>{tt!==null&&window.clearInterval(tt),window.removeEventListener("message",x)},st=async ve=>{if(!He){He=!0,Ct(),_t(ve?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await yt(n,"google"),await Ar()}finally{_t(null)}}};window.addEventListener("message",x),_t("Finish the Google consent flow in the popup. This page will refresh automatically."),tt=window.setInterval(()=>{me.closed&&st(!1)},1e3)}catch(x){Pe(x instanceof Error?x.message:"Failed to start OAuth flow")}finally{Se(!1)}}async function el(){Pe(null),_t(null);try{await Sl(t,"gsc"),await yt(n,"google"),i(x=>x.filter(L=>L.connectionType!=="gsc")),m([]),R("")}catch(x){Pe(x instanceof Error?x.message:"Failed to disconnect")}}async function tl(){if(M){Ue(!0),Pe(null);try{await Dl(t,"gsc",M),await yt(n,"google"),i(x=>x.map(L=>L.connectionType==="gsc"?{...L,propertyId:M}:L)),ke({title:"GSC property updated",detail:`${t} is now linked to ${M}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(x){Pe(x instanceof Error?x.message:"Failed to save GSC property")}finally{Ue(!1)}}}async function sl(){Pe(null),_t(null);try{await ce.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(N,10)||void 0,full:D||void 0}}),await yt(n,"gsc")}catch{}}async function Tr(){if(c.trim()){be(!0),Pe(null),_t(null);try{const x=await Tl(t,c.trim());await yt(n,"gsc"),Q(x),v(""),await _n()}catch(x){Pe(x instanceof Error?x.message:"Failed to inspect URL")}finally{be(!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"})]})}),it&&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:it.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:it.message}),(Hs(it.enableUrl)||Hs(it.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Hs(it.enableUrl)&&e.jsx("a",{href:Hs(it.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 ↗"}),Hs(it.indexingApiUrl)&&e.jsx("a",{href:Hs(it.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:()=>Jt(null),children:"×"})]})}),at&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[at,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Pe(null),children:"×"})]}),$t&&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:[$t,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>_t(null),children:"×"})]}),Ae?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Mt?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:Mt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",J?.lastInspectedAt?Vt(J.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:De(el),children:"Disconnect"})]}):e.jsxs(xe,{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(A,{type:"button",variant:"outline",size:"sm",disabled:lt,onClick:De(Ir),children:lt?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(bs,{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."})]})]})]}),(Mt||k)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(xe,{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(ze,{text:`${Vm(h?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${zn.toLocaleString()} matching rows while the table shows ${Ns} per page.`})]}),h?.window?.startDate&&h.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[h.window.startDate," to ",h.window.endDate,(h.window.daysSinceLatestData??0)>0&&` · latest data ${h.window.daysSinceLatestData} day${h.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{windows:Fm,value:U,onChange:x=>{z(x),le(0),wt.setPage(1)},label:"Search Console time period",formatOption:x=>x==="all"?"All":x}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Ie,onClick:()=>{le(0),wt.setPage(1),Bt(0),ya()},children:Ie?"Loading…":"Apply filters"})]})]}),h&&h.daily.length>0&&(()=>{const{totals:x,daily:L,trends:ne,periodComparison:me}=h,He=si.filter(ve=>B.includes(ve.key)).map(ve=>({dataKey:ve.key,label:ve.label,color:ve.color,axisId:ve.key,inverted:ve.inverted,formatValue:ve.format,trend:pe?ne?.[ve.key]??null:null})),tt=ve=>x[ve]??null,Ct=new Map(L.map(ve=>[ve.date,ve])),st=L.length===0?[]:Eu(L[0].date,L[L.length-1].date).map(ve=>Ct.get(ve)??{date:ve});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:si.map(ve=>{const Rs=B.includes(ve.key),wn=tt(ve.key),Un=wn===null;return e.jsxs("button",{type:"button","aria-pressed":Rs,disabled:Un,className:`rounded-md border px-3 py-2 text-left transition-colors ${Rs?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Un?"cursor-not-allowed opacity-50":""}`,onClick:()=>{K(Is=>Is.includes(ve.key)?Is.length===1?Is:Is.filter(nl=>nl!==ve.key):[...Is,ve.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:Rs?ve.color:"transparent",border:`1px solid ${ve.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ve.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:wn===null?"—":ve.format(wn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Bm(me,ve.key,ve.inverted)})]},ve.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:pe,onChange:ve=>we(ve.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(mo,{data:st,xKey:"date",series:He,xTickFormatter:nn,labelFormatter:Ot,onSelectX:ja,selectedX:F})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:L.map(ve=>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":F===ve.date,onClick:()=>ja(ve.date),children:[Ot(ve.date),": ",ve.clicks," clicks, ",ve.impressions," impressions"]},ve.date))}),F&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Ot(F)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>ja(F),children:["Show all ",x.days," days"]})]}),x.position!==null&&(x.positionDays??x.days)<x.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",x.positionDays," of ",x.days," days. The rest have no property-level position recorded."]}),(x.position===null||x.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:H.startDate,onChange:x=>P(L=>({...L,startDate:x.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:H.endDate,onChange:x=>P(L=>({...L,endDate:x.target.value}))}),e.jsx(fn,{value:H.query,onChange:x=>P(L=>({...L,query:x})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(fn,{value:H.page,onChange:x=>P(L=>({...L,page:x})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),d.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(Xs).map(x=>e.jsx("th",{className:"text-right","aria-sort":dt?.key===x?dt.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:()=>{wt.setPage(1),ys(L=>L?.key===x?L.dir==="desc"?{key:x,dir:"asc"}:null:{key:x,dir:"desc"})},children:[jl[x],dt?.key===x?dt.dir==="desc"?" ↓":" ↑":""]})},x))]})}),e.jsx("tbody",{children:ms.map((x,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:x.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(na,{value:x.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:x.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(x.ctr)?x.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.position.toFixed(1)})]},`${x.date}:${x.query}:${x.page}:${L}`))})]})}),e.jsx(en,{page:Z?wt.page:Math.floor(ae/Ns)+1,pageSize:Ns,visibleRows:ms.length,totalRows:Z?ue:void 0,hasNextPage:Z?void 0:O,disabled:Ie,itemLabel:Z?"matches":"rows",onPageChange:x=>{if(Z){wt.setPage(x);return}const L=(x-1)*Ns;le(L),Bt(L)}}),Z&&ue>=zn?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",zn.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(xe,{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(ze,{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:[J&&J.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:S,onClick:()=>{Jo()},children:S?"Requesting…":`Request indexing (${J.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:zt,onClick:()=>{wr(!0)},children:zt?"Loading…":"Reload saved coverage"})]})]}),J&&J.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const x=J.summary.indexed+J.summary.notIndexed,L=x>0?J.summary.indexed/x:0,ne=x>0?J.summary.notIndexed/x:0,me=54,Be=2*Math.PI*me,He=Be*(1-L),tt=Be*ne,Ct=Be*L;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:me,fill:"none",stroke:as.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:me,fill:"none",stroke:tn.positiveDeep,strokeWidth:"14",strokeDasharray:Be,strokeDashoffset:He,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),J.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:me,fill:"none",stroke:as.textFaint,strokeWidth:"14",strokeDasharray:`${tt} ${Be-tt}`,strokeDashoffset:-Ct,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:[(L*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:J.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:J.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(J.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(J.reasonGroups??[]).length," ",(J.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),J.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:J.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(x=>{const L=x==="indexed"?J.indexed.length:x==="notIndexed"?J.notIndexed.length:J.deindexed.length,ne=x==="indexed"?"Indexed":x==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":rt===x,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${rt===x?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{us(x),hs(null)},children:[ne," (",L,")"]},x)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[rt==="indexed"&&J.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:Me.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.crawlTime?x.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:x.isMobileFriendly===!0?"Yes":x.isMobileFriendly===!1?"No":"—"})]},x.id))})]}),rt==="notIndexed"&&!Pt&&(J.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:(J.reasonGroups??[]).map(x=>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:()=>hs(x.reason),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),hs(x.reason))},tabIndex:0,role:"button","aria-label":`View ${x.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:x.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.count})]},x.reason))})]}),rt==="notIndexed"&&!Pt&&(J.reasonGroups??[]).length===0&&J.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:Tt.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.coverageState??"Unknown"})]},x.id))})]}),rt==="notIndexed"&&Pt&&(()=>{const x=(J.reasonGroups??[]).find(L=>L.reason===Pt);return x?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:()=>hs(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:x.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[x.count," affected page",x.count!==1?"s":""]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:S,onClick:()=>{Sr(x.urls.map(L=>L.url))},children:S?"Requesting…":`Request indexing (${x.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:Ps.map(L=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:L.url}),e.jsx("td",{className:"text-secondary",children:L.crawlTime?L.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:S,onClick:()=>{Sr([L.url])},title:"Request indexing",children:"Index"})})]},L.id))})]})]}):null})(),rt==="deindexed"&&J.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:ut.map((x,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.previousState}),e.jsx("td",{className:"text-secondary",children:x.currentState}),e.jsx("td",{className:"text-secondary",children:x.transitionDate.split("T")[0]})]},`${x.url}-${L}`))})]}),(rt==="indexed"&&J.indexed.length===0||rt==="notIndexed"&&!Pt&&J.notIndexed.length===0||rt==="deindexed"&&J.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(en,{page:se,pageSize:Ts,visibleRows:Math.min(Ts,X.length-re),totalRows:X.length,onPageChange:ps,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":is,onClick:()=>ds(x=>!x),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:is?"Hide snapshots":bt.length>0?`View ${bt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",J.summary.indexed.toLocaleString()," indexed, ",J.summary.notIndexed.toLocaleString()," not indexed.",St&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",St.indexed>=0?"+":"",St.indexed.toLocaleString()," indexed, ",St.notIndexed>=0?"+":"",St.notIndexed.toLocaleString()," not indexed."]})]}),is&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:bt.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:bt.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:x.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.notIndexed.toLocaleString()})]},x.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:zt?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(xe,{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(ze,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Te||!Mt?.propertyId,onClick:()=>{va()},children:Te?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:Ce,onChange:x=>ye(x.target.value),onKeyDown:x=>x.key==="Enter"&&void un([Ce.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!js||Je||!Ce.trim(),onClick:()=>{un([Ce.trim()])},children:Je?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!js||Je||Nn.length===0,onClick:()=>{un(Nn)},children:Je?"Resubmitting…":dn}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!js||Je||!pt?.length,onClick:()=>{Zo()},children:"Resubmit all files"}),Oe&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Oe.indexes," index",Oe.indexes===1?"":"es",", ",Oe.files," file",Oe.files===1?"":"s"]}),ht&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",ht.completed,"/",ht.total]})]}),!js&&Mt&&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:De(Ir),children:"Reconnect"})]}),pt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:pt.length>0?e.jsxs(e.Fragment,{children:[e.jsx(fn,{value:gt,onChange:x=>{kt(x),Qt.setPage(1)},label:"Filter sitemaps",placeholder:"Filter sitemaps…"}),e.jsxs("table",{className:"data-table mt-3 w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Sitemap"}),e.jsx("th",{className:"text-left",children:"Type"}),e.jsx("th",{className:"text-left",children:"Google status"}),e.jsx("th",{className:"text-left",children:"Last submitted"}),e.jsx("th",{className:"text-left",children:"Last read"}),e.jsx("th",{className:"text-right",children:"Discovered URLs"}),e.jsx("th",{className:"text-left",children:"Issues"}),e.jsx("th",{className:"text-left",children:"Actions"})]})}),e.jsx("tbody",{children:Qt.rows.flatMap(x=>{const L=ni(x),ne=ai(x),me=ri(x),Be=jt[x.path]??[],He=Ee.has(x.path),tt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(na,{value:x.path})}),e.jsx("td",{className:"text-secondary",children:x.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":He,"aria-label":`${He?"Collapse":"Expand"} files in ${x.path}`,onClick:()=>{Xo(x.path)},children:It.has(x.path)?"Loading…":`${He?"▾":"▸"} Index${jt[x.path]?` (${Be.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:me}),e.jsx("td",{className:"text-secondary",children:x.lastSubmitted?x.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:x.lastDownloaded?x.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:L.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ne||"—"}),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:!js||Je,onClick:()=>{un([x.path])},children:x.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Mt?.sitemapUrl===x.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:je,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Cr(x.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Ne.isPending,onClick:()=>{kr(x.path)},children:"Inspect URLs"})]})})]},x.path),Ct=x.isSitemapsIndex&&He?Be.map(st=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(na,{value:st.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:ri(st)}),e.jsx("td",{className:"text-secondary",children:st.lastSubmitted?st.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:st.lastDownloaded?st.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:ni(st).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:ai(st)||"—"}),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:!js||Je,onClick:()=>{un([st.path])},children:"Resubmit"}),Mt?.sitemapUrl===st.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:je,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Cr(st.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Ne.isPending,onClick:()=>{kr(st.path)},children:"Inspect URLs"})]})})]},`${x.path}:${st.path}`)):[];return[tt,...Ct]})})]}),e.jsx(en,{page:Qt.page,pageSize:Ns,visibleRows:Qt.rows.length,totalRows:Qt.totalRows,onPageChange:Qt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:c,onChange:x=>v(x.target.value),onKeyDown:x=>x.key==="Enter"&&void Tr()}),e.jsx(A,{type:"button",size:"sm",disabled:he||!Mt?.propertyId||!c.trim(),onClick:De(Tr),children:he?"Inspecting…":"Inspect URL"})]}),C&&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:C.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:C.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:$r(C.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:Vt(C.crawlTime)})]})]})]}),e.jsxs(xe,{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(A,{type:"button",variant:"outline",size:"sm",disabled:T,onClick:()=>{_n(!0)},children:T?"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:Fe,onChange:x=>Le(x.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:T,onClick:()=>{_n(!0)},children:"Apply filter"})]}),b.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:b.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-neutral",children:x.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:$r(x.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Vt(x.inspectedAt)})]},x.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),f.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:f.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:x.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Vt(x.transitionDate)})]},`${x.url}:${x.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Mt&&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:()=>rs(x=>!x),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 ${Nt?"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"})]})}),Nt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(xe,{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(ze,{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:M,disabled:et||u.length===0,onChange:x=>R(x.target.value),children:u.length===0?e.jsx("option",{value:"",children:et?"Loading properties…":"No properties available"}):u.map(x=>e.jsxs("option",{value:x.siteUrl,children:[x.siteUrl," · ",x.permissionLevel]},x.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:et,onClick:()=>{Ut(Mt,!0)},children:et?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!M||_e,onClick:De(tl),children:_e?"Saving…":"Save property"})]})]})]}),e.jsxs(xe,{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:N,onChange:x=>$(x.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:x=>w(x.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:ce.isPending||!Mt.propertyId,onClick:De(sl),children:ce.isPending?"Queueing…":"Queue sync"}),!Mt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const zm=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Qm({projectName:t,projectId:s}){const n=As(),[a,r]=l.useState(null),[o,i]=l.useState(null),[u,m]=l.useState(!1),d=Re(dr({client:V,path:{name:t}})),p=d.data?.find(_=>_.connectionType==="gbp"),h=!!p,j=a?{locationName:a}:void 0,b=Re({...El({client:V,path:{name:t}}),enabled:h}),g=Re({...ql({client:V,path:{name:t},query:j}),enabled:h}),f=Re({...Ol({client:V,path:{name:t},query:j}),enabled:h}),y=Re({...Gl({client:V,path:{name:t},query:j}),enabled:h}),C=Re({...Fl({client:V,path:{name:t},query:j}),enabled:h}),Q=Re({..._l({client:V,path:{name:t},query:j}),enabled:h}),M=Re({queryKey:["gbp-section-insights",t],queryFn:()=>Ul(t),enabled:h});function R(){yt(n,"gbp")}const c=Et({...Bl(),onSuccess:_=>{Zi({id:_.runId,projectId:s,kind:Fs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),ke({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=l.useSyncExternalStore(eo,ra,ra),N=Object.values(v.runs).some(_=>_.kind===Fs["gbp-sync"]&&_.projectId===s),$=c.isPending||N,D=Et({...Vl(),onSuccess:()=>R()});if(l.useEffect(()=>{if(!a||!b.data)return;const _=b.data.locations.filter(Z=>Z.selected);(_.length<=1||!_.some(Z=>Z.locationName===a))&&r(null)},[a,b.data]),l.useEffect(()=>{if(!o||!b.data)return;(a?[a]:b.data.locations.filter(Z=>Z.selected).map(Z=>Z.locationName)).includes(o)||i(null)},[o,b.data,a]),d.isLoading)return null;if(!p){const _=[{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(xe,{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:_.map((Z,fe)=>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:fe+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 w=g.data,U=b.data?.locations??[],z=U.filter(_=>_.selected),B=f.data?.keywords??[],K=y.data?.lodging??[],pe=C.data?.placeActions??[],we=Q.data?.places??[],F=U.length>0?U[0].accountName:p.domain,te=a?U.find(_=>_.locationName===a)?.displayName??null:null,ie=a?U.filter(_=>_.locationName===a):z,Y=new Set(ie.map(_=>_.locationName)),H=K.filter(_=>Y.has(_.locationName)),P=pe.filter(_=>Y.has(_.locationName)),ae=we.filter(_=>Y.has(_.locationName)),le=new Set(z.map(_=>_.locationName)),O=a?B:B.filter(_=>le.has(_.locationName)),W=!a&&z.length>1,ue=(M.data??[]).filter(_=>!_.dismissed&&zm.has(_.type)&&(!te||_.query===te||_.query===a||_.title.startsWith(te)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(xe,{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(ze,{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"}),!ee()&&e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:$,onClick:()=>c.mutate({client:V,path:{name:t},body:{}}),children:$?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[F?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:F})," · "]}):null,b.data?`${b.data.totalSelected} of ${b.data.totalDiscovered} locations tracked`:"Loading locations…"]}),z.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:_=>r(_.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"}),z.map(_=>e.jsx("option",{value:_.locationName,children:_.displayName},_.id))]})]}),z.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:[ue.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),ue.map(_=>e.jsx("div",{className:["insight-card",ih(_.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:[_.title,_.recommendation?.reason&&e.jsx(ze,{text:_.recommendation.reason})]})},_.id))]}),w&&e.jsx(dh,{performance:w.performance,freshness:w.freshness,timeseries:w.timeseries}),w?.profileCompleteness&&e.jsx(Hm,{summary:w.profileCompleteness}),ie.length>0&&e.jsx(Wm,{locations:ie,lodging:H,places:ae,placeActions:P,expandedLocation:o,onToggleExpanded:_=>{i(Z=>Z===_?null:_)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),f.data&&f.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[f.data.thresholdedPct,"% privacy-thresholded"]})]}),O.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"}),W&&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:O.slice(0,25).map(_=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:_.keyword}),W&&e.jsx("td",{className:"text-muted",children:U.find(Z=>Z.locationName===_.locationName)?.displayName??_.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:_.valueCount!==null?_.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",_.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[_.periodStart,"–",_.periodEnd]})]},`${_.locationName}:${_.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:()=>m(_=>!_),"aria-expanded":u,children:[e.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"})," Manage locations (",U.length,")"]}),u&&e.jsx("div",{className:"mt-3",children:U.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"}),!ee()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:U.map(_=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:_.displayName}),e.jsx("td",{className:"text-muted",children:_.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(de,{tone:_.selected?"positive":"neutral",children:_.selected?"Tracked":"Not tracked"})}),!ee()&&e.jsx("td",{className:"text-right",children:e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:D.isPending,onClick:()=>D.mutate({client:V,path:{name:t,locationName:_.locationName},body:{selected:!_.selected}}),children:_.selected?"Untrack":"Track"})})]},_.id))})]})})]})]})})}function Hm({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Cn(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Cn(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Cn(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Cn(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Cn(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(ze,{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 ${rh(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Wm({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:o}){const i=new Map(s.map(d=>[d.locationName,d])),u=new Map(n.map(d=>[d.locationName,d])),m=new Map;for(const d of a){const p=m.get(d.locationName)??[];p.push(d),m.set(d.locationName,p)}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(ze,{text:ee()?"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(d=>{const p=i.get(d.locationName)??null,h=u.get(d.locationName)??null,j=m.get(d.locationName)??[],b=r===d.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:d.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:d.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(de,{tone:d.selected?"positive":"neutral",children:d.selected?"Tracked":"Not tracked"}),d.openStatus&&d.openStatus!=="OPEN"&&e.jsx(de,{tone:d.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Po(d.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Jm,{location:d})}),e.jsx("td",{children:e.jsx(Xm,{lodging:p})}),e.jsx("td",{children:e.jsx(eh,{place:h,mapsUri:d.mapsUri})}),e.jsx("td",{children:e.jsx(sh,{actions:j})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>o(d.locationName),children:b?"Hide":"Details"})})]}),b&&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(ah,{location:d,lodging:p,place:h,placeActions:j})})})]},d.id)})})]})})]})}function Ym(t){return[{label:"Description",tone:Ws(t.description)?"positive":"neutral",value:Ws(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Ws(t.primaryPhone)?"positive":"neutral",value:Ws(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Ws(t.websiteUri)?"positive":"neutral",value:Ws(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 Jm({location:t}){const s=Ym(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 Xm({lodging:t}){return e.jsx(mr,{...Zm(t)})}function Zm(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 eh({place:t,mapsUri:s}){return e.jsx(mr,{...th(t,s)})}function th(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 sh({actions:t}){return e.jsx(mr,{...nh(t)})}function nh(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 mr({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 ah({location:t,lodging:s,place:n,placeActions:a}){const r=s?lh(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs($a,{title:"Owner profile · Business Information",children:[e.jsx(Lt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Lt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Lt,{label:"Description",value:Ws(t.description)?t.description:"Not returned"}),e.jsx(Lt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Lt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Lt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Lt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Lt,{label:"Open status",value:Po(t.openStatus)}),e.jsx(Lt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx($a,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{label:"Last checked",value:ii(s.syncedAt)}),e.jsx(Lt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Lt,{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($a,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{label:"Places tier",value:n.tier}),e.jsx(Lt,{label:"Last checked",value:ii(n.syncedAt)}),e.jsx(Lt,{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:[ha(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[ha(o.providerType),o.uri?` · ${oh(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function $a({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 Lt({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 Cn(t,s,n){return t===s?"positive":t===0?n:"caution"}function rh(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function ih(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Ws(t){return typeof t=="string"&&t.trim().length>0}function Po(t){return t?ha(t):"Not returned"}function ha(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function oh(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function ii(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function lh(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&ch(n)).map(([s])=>ha(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function ch(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function dh({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Kl.filter(g=>(a[g]??0)>0),o=zl.filter(g=>(a[g]??0)>0),i=Object.keys(a).filter(g=>(a[g]??0)>0&&Ql(g)==="other").sort((g,f)=>(a[f]??0)-(a[g]??0)),u=Object.keys(a).filter(g=>(a[g]??0)===0).sort(),m=n.map(g=>{const f={date:g.date};for(const[y,C]of Object.entries(g.metrics))f[y]=C;return f}),d=n.find(g=>g.pending)?.date,p=n.length>0?n[n.length-1].date:void 0,h=m.length>0,j=s.dataThroughDate?`Data through ${Ot(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,b=[...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"}),j&&e.jsx("span",{className:"text-[11px] text-muted",children:j})]}),!h||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(oi,{data:m,metrics:r,kind:"line",firstPending:d,lastDate:p}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:b.map(g=>e.jsxs("span",{className:"text-sm text-secondary",children:[ia(g)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[g]??0).toLocaleString()})]},g))})]})]}),h&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(oi,{data:m,metrics:o,kind:"area",firstPending:d,lastDate:p})]}),u.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",u.map(g=>ia(g)).join(", ")]})]})}function oi({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(an,{width:"100%",height:"100%",children:e.jsxs(rn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ua,{stroke:da,vertical:!1}),e.jsx(on,{dataKey:"date",tick:Kt,tickLine:!1,axisLine:{stroke:ls},tickFormatter:nn,minTickGap:24}),e.jsx(ln,{tick:Kt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(cn,{...ss,labelFormatter:Ot,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),ia(String(i??""))]}),e.jsx(ma,{wrapperStyle:{fontSize:11,color:as.text},formatter:o=>ia(o)}),a&&r&&e.jsx(Xa,{x1:a,x2:r,fill:as.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:as.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(Js,{type:"monotone",dataKey:o,stroke:nt[i%nt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Ds,{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 uh(t){return ho(ks(String(t)))}function mh(t){return Os(ks(String(t)))}function Ma({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(vu,{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 Qn=Ns;function mn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function La(t){return t.toLocaleString()}function hh(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function xh(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 ph(t){const s=t.filter(n=>n.kind===Fs["backlink-extract"]&&!to(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function gh(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 fh({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[o,i]=l.useState([]),[u,m]=l.useState(null),[d,p]=l.useState(null),[h,j]=l.useState(null),[b,g]=l.useState(Date.now()),[f,y]=l.useState(0),[C,Q]=l.useState(!0),[M,R]=l.useState(!1),[c,v]=l.useState(null),N=l.useCallback(async()=>{Q(!0),v(null);try{const[F,te,ie,Y,H]=await Promise.all([Hl().catch(()=>null),Wl(t,{excludeCrawlers:!0}).catch(()=>null),Yl(t,{limit:Qn,offset:f,excludeCrawlers:!0}).catch(ae=>{if(ae instanceof sn&&ae.code==="NOT_FOUND")return null;throw ae}),Jl(t).catch(()=>[]),Xl(t).catch(()=>[])]);m(F),n(te),r(ie),i(Y);const P=ph(H);p(P)}catch(F){v(F instanceof Error?F.message:"Failed to load backlinks")}finally{Q(!1)}},[t,f]);l.useEffect(()=>{N()},[N]),l.useEffect(()=>{if(!d)return;const F=d.id;let te=!1;const ie=async()=>{try{const H=await Ja(F);if(te)return;to(H.status)?(p(null),j(H),await N()):p(P=>P?.id===H.id?{...P,...H}:P)}catch{}},Y=window.setInterval(()=>{ie()},3e3);return()=>{te=!0,window.clearInterval(Y)}},[d,N]),l.useEffect(()=>{if(!d)return;const F=window.setInterval(()=>g(Date.now()),1e3);return()=>window.clearInterval(F)},[d]),l.useEffect(()=>{if(!h||h.status==="failed")return;const F=window.setTimeout(()=>j(null),1e4);return()=>window.clearTimeout(F)},[h]);async function $(){R(!0),v(null);try{const F=await ec(t);p(F)}catch(F){F instanceof sn&&F.code==="MISSING_DEPENDENCY"?v("DuckDB is not installed. Visit the Backlinks admin page to install it."):v(F instanceof Error?F.message:"Failed to trigger extract")}finally{R(!1)}}const D=l.useMemo(()=>o.slice().sort((F,te)=>F.queriedAt.localeCompare(te.queriedAt)).map(F=>({date:F.queriedAt,linkingDomains:F.totalLinkingDomains})),[o]),w=a?.rows??[],U=a?.total??0,z=s?.excludedLinkingDomains??0,B=Math.floor(f/Qn)+1;return l.useEffect(()=>{f>0&&f>=U&&y(0)},[f,U]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),c&&e.jsx(xe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:c})}),d&&e.jsx(xe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(bu,{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:d.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[gh(d.startedAt??null,d.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",b]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),h&&!d&&e.jsx(xe,{className:`surface-card p-4 mb-4 ${h.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[h.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(lo,{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 ${h.status==="failed"?"text-negative":"text-positive"}`,children:h.status==="failed"?"Extract failed":"Extract complete"}),h.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Zl(h.error)}):h.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),K()]});function K(){return C?e.jsx(xe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):pe()}function pe(){const F=s!==null&&s.totalLinkingDomains>0,te=h?.status==="failed",ie=s!==null&&s.totalLinkingDomains===0&&!te,Y=u?.status==="ready",H=u?.status==="failed",P=u&&(u.status==="downloading"||u.status==="querying"||u.status==="queued");return F?we(e.jsxs(e.Fragment,{children:[!ee()&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:M||d!==null,onClick:De($),children:[e.jsx(co,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),d?"Extract running…":M?"Queuing…":"Re-run extract"]}),e.jsx(Ma,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ee()&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:mn("/backlinks"),children:"Open admin"})})]})):e.jsx(xe,{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(yu,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!u&&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."}),!ee()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:mn("/backlinks"),children:"Set up backlinks"})})})]}),P&&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 (",u.status,u.phaseDetail?` — ${u.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!ee()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:mn("/backlinks"),children:"View sync status"})})})]}),H&&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:u.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!ee()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:mn("/backlinks"),children:"Go to Backlinks admin"})})})]}),Y&&!P&&!ie&&!te&&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:u.release})," is ready. Run an extract for this project."]}),!ee()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:M||d!==null,onClick:De($),children:[e.jsx(ca,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),d?"Extract running…":M?"Queuing…":"Run extract"]}),e.jsx(Ma,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),te&&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."}),!ee()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:mn("/backlinks"),children:"Go to Backlinks admin"})})})]}),ie&&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."]}),!ee()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:mn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:M||d!==null,onClick:De($),children:[e.jsx(ca,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),d?"Extract running…":M?"Queuing…":"Re-run extract"]}),e.jsxs(Ma,{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 we(F){if(!s)return null;const te="Linking hosts",ie="linking hosts",Y="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:La(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 ",ie]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:La(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",ie," 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:hh(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",ie," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",Y," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",xh(s.queriedAt),z>0&&e.jsxs(e.Fragment,{children:[" · ",z," excluded domain",z===1?"":"s"]})]}),D.length>=2&&e.jsxs(xe,{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(an,{width:"100%",height:"100%",children:e.jsxs(rn,{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(on,{dataKey:"date",tick:Kt,stroke:ls,tickFormatter:uh}),e.jsx(ln,{tick:Kt,stroke:ls,allowDecimals:!1}),e.jsx(cn,{contentStyle:ss.contentStyle,labelStyle:ss.labelStyle,itemStyle:ss.itemStyle,labelFormatter:mh}),e.jsx(Ds,{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(xe,{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:te})]})}),e.jsxs("tbody",{children:[w.map(H=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:H.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:La(H.numHosts)})]},H.linkingDomain)),w.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:z>0&&U===0?`Every referring domain in this ${Y} was a crawler/proxy host (${z} hidden).`:`No referring domains in this ${Y}.`})})]})]})}),e.jsx(en,{page:B,pageSize:Qn,visibleRows:w.length,totalRows:U,onPageChange:H=>y((H-1)*Qn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:F})]})}}function bh({projectName:t}){const s=Re({...tc({client:V,path:{name:t}}),staleTime:so}),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:ur(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:cs()?"text-sm text-secondary":"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":cs()?_s:"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(ze,{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(ze,{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(yh,{data:n}),e.jsx(vh,{data:n}),n.competitorGaps.length>0&&e.jsx(Sh,{data:n})]})}function yh({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(Hn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Hn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Hn,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(Hn,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function Hn({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 vh({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(jh,{}),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(Mn,{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(ju,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Nh,{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 jh(){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(gn,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gn,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gn,{active:!1,tone:"cited"}),e.jsx(gn,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Nh({provider:t}){const s=wh(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(gn,{active:t.cited,tone:"cited"}),e.jsx(gn,{active:t.mentioned,tone:"mentioned"})]})}function wh(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 gn({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 Sh({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(ze,{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(Mn,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const On="__cited__",Gn="__mentioned__",ns="__mentionShare__";function Ro(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:ks(n),end:ks(a),sweepCount:s.sweepCount??1}}function xa(t){const s=Ro(t);if(!s)return"Sweep date unavailable";const n=Os(s.start),a=Os(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Ch(t){const s=Ro(t);return s?ho(s.start):""}function jn(t){return t.trim().toLowerCase()}function nr(t){return Math.round(t*1e3)/10}function ar(t){return t.byProvider??{}}function kh(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const m=s==="cited"?On:Gn,d=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(h=>({date:h.startDate,[m]:nr(h[d])})),series:[m],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(m=>Object.keys(ar(m))))].sort();return{rows:t.buckets.map(m=>{const d={date:m.startDate},p=ar(m);for(const h of i){const j=p[h];d[h]=j?nr(j[o]):null}return d}),series:i,hasData:a,singleBucket:r}}function Io(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Ah(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Ph(t){return t.servedModelAttribution??{}}function Rh(t){return t.modelServiceMismatch??{}}function Ih(t){return t.modelPointerChanges??{}}function Th(t){return t.length>0?t.join(", "):null}function li(t,s){const n=jn(s);return Object.entries(t).find(([a])=>jn(a)===n)?.[1]}function ws(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 $h(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!li(ar(a),s))continue;const r=Io(a);return r?li(r,s)??null:null}return null}function Mh(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 Lh(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:Mh(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Dh(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 Eh(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 qh(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[ns]:r?.rate==null?null:nr(r.rate)}}),n=s.map(a=>a[ns]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[ns],hasData:n.length>0,singleBucket:n.length===1}}function Oh(t,s,n){return s==="mentionShare"?qh(t):kh(t,s,n)}function ci(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 di(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function ui(t){return t>0?`+${t}`:`${t}`}function Gh(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${ui(n.delta)} on ${di(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${ui(s.delta)} on ${di(s.date)})`}const Fh=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],_h=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Uh=[{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."}],hr=nt[2],Bh="var(--chart-tooltip-bg)",Vh={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Cs(t){const s=jn(t);return Vh[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Es(t){return Math.round(t*10)/10}function Kh(t){return t===On||t===Gn||t===ns}function To(t){return t===On?"Cited":t===Gn?"Mentioned":t===ns?"Mention share":Cs(t)}function Pn(t,s){return t===On?tn.positive:t===Gn?nt[1]:t===ns?hr:ku(jn(t),s)}function zh(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Qh(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
|
+
`)}function ba(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function aa(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${ba(s)}`:"Mention share":"Mentioned"}function En(t){return t==="cited"?"citationRate":"mentionRate"}function $o(t,s){return s==="cited"?t.cited:t.mentionedCount}function Mo(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 Lo(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function rr(t){const s=Io(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>jn(a).localeCompare(jn(r))).map(([a,r])=>`${Cs(a)}: ${ws(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function Hh(t){return t.some(({event:s})=>s.to.status==="mixed")?tn.caution:t.some(({event:s})=>s.to.status==="unknown")?tn.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?nt[4]:tn.positive}function Wh(t,s,n){const a=Lo(t,s);return a?xa(a):Os(ks(n))}function Yh({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:o,mismatch:i,buckets:u}){const m=l.useId(),d=Object.entries(o).sort(([h],[j])=>h.localeCompare(j)),p=t.buckets.length>0||t.beforeWindow.length>0;return!s||!p?null:e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":m,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:m,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:h,events:j})=>j.map(({provider:b,event:g})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Wh(u,h,g.observedAt)}),e.jsxs("span",{children:[Cs(b),": ",ws(g.from)," → ",ws(g.to)]})]},`${b}-${g.observedAt}-${g.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:h,event:j})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Os(ks(j.observedAt))]}),e.jsxs("span",{children:[Cs(h),": ",ws(j.from)," → ",ws(j.to),j.anchorObservedAt?` (last seen ${ws(j.from)} on ${Os(ks(j.anchorObservedAt))})`:""]})]},`before-${h}-${j.observedAt}`))})]}),a.map(h=>e.jsxs("p",{className:"trend-model-evidence-note",children:[Cs(h.provider),": showing the most recent ",h.shown," of ",h.total," changes."]},`truncated-${h.provider}`)),r.map(h=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",Cs(h)," change."]},`incomplete-${h}`)),d.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:d.map(([h,j])=>{const b=Th(j.latestServedModelIds),g=i[h];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Os(ks(j.latestObservation.observedAt))}),e.jsxs("span",{children:[Cs(h),": ",b??ws(j.latestObservation.state),g?` — not the ${ws(g.configured)} you selected`:""]})]},`served-${h}`)})})]})]})}function mi(t){return t===null?"no data":`${t}%`}function Da(t){return t==null?"undefined":`${Es(t*100)}%`}function Jh({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=Lo(o,s);if(!i)return null;if(a==="mentionShare"){const m=i.mentionShare.projectMentionSnapshots,d=i.mentionShare.competitorMentionSnapshots,p=m+d,h=i.mentionShare.rate==null?null:Es(i.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:xa(i)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:hr},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",ba(i.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:mi(h)})]}),p>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",m," / ",p," brand mentions. Competitors ",d,"."]}):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:rr(i)})]})}const u=r==="byProvider"?(n??[]).filter(m=>m.dataKey!==void 0):[{dataKey:a==="cited"?On:Gn,value:Es(i[En(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:xa(i)}),u.map((m,d)=>{const p=String(m.dataKey??m.name??""),h=r==="byProvider"?Mo(i,p,a):null,j=h?.count??$o(i,a),b=h?.total??i.total,g=typeof m.value=="number"?m.value:Es(h?h.rate*100:i[En(a)]*100),f=m.color??Pn(p,d);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:f},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:To(p)}),e.jsx("span",{className:"trend-tooltip-value",children:mi(g)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[j," / ",b," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${p}-${d}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:rr(i)})]})}function Xh({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:[aa(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 u=o.mentionShare.projectMentionSnapshots,m=o.mentionShare.competitorMentionSnapshots,d=u+m,p=ba(o.mentionShare.scope);i=d>0?`${Da(o.mentionShare.rate)} mention share for ${p}, ${u} of ${d} brand mentions were you`:`mention share undefined for ${p}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(u=>{const m=Mo(o,u,s);return m?`${Cs(u)} ${Da(m.rate)} ${aa(s).toLowerCase()}, ${m.count} of ${m.total} snapshots`:`${Cs(u)} no data`}).join("; "):i=`${Da(o[En(s)])} ${aa(s).toLowerCase()}, ${$o(o,s)} of ${o.total} snapshots`;return i+=`; ${rr(o)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:xa(o)}),e.jsx("td",{children:i})]},o.startDate)})})]})}function Ea({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 u=s===i.value,m=i.description?`${o}-${i.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":u,"aria-describedby":m,className:`segmented-option ${u?"segmented-option-active":""}`,onClick:()=>n(i.value),children:i.label}),i.description&&e.jsx("span",{id:m,className:"sr-only",children:i.description})]},i.value)})})}function Zh({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[o,i]=l.useState("mentioned"),[u,m]=l.useState("byProvider"),d=l.useMemo(()=>Qh(s),[s]),p=Re({queryKey:["analytics-metrics",t,a,d,n],queryFn:()=>sc(t,a),staleTime:so}),h=p.data??null,j=p.error,b=o==="mentionShare"?"overall":u,g=l.useMemo(()=>h?Oh(h,o,b):null,[h,o,b]),f=h?Ah(h):null,y=l.useMemo(()=>Lh(f??{}),[f]),C=l.useMemo(()=>Dh(f??{}),[f]),Q=l.useMemo(()=>Eh(f??{}),[f]),M=l.useMemo(()=>Object.entries(f??{}).filter(([,H])=>H.anchorUnavailable).map(([H])=>H).sort(),[f]),R=l.useMemo(()=>h?Ph(h):{},[h]),c=l.useMemo(()=>h?Rh(h):{},[h]),v=l.useMemo(()=>h?nc(Ih(h)):null,[h]),N=o!=="mentionShare"&&b==="byProvider",$=h?.buckets??[],D=$[$.length-1]?.mentionShare.scope??h?.mentionShareScope??"pooled",w=aa(o,D),U=o==="cited"?tn.positive:o==="mentionShare"?hr:nt[1],z=N?as.textDim:U,B=l.useMemo(()=>{const H=new Map($.map(P=>[P.startDate,Ch(P)]));return P=>H.get(String(P))??""},[$]),K=o==="mentionShare"?g?ci(g.rows,ns):null:$.length>0?Es($[$.length-1][En(o)]*100):null,pe=o==="mentionShare"?g?zh(g.rows,ns):null:$.length>0?Es($[0][En(o)]*100):null,we=o==="mentionShare"?g?.rows.filter(H=>typeof H[ns]=="number").length??0:$.length,F=K!==null&&pe!==null&&we>1?Es(K-pe):null,te=s.length,ie=e.jsxs(e.Fragment,{children:[v?.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:v.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(ze,{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."})]})]}),K!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:z},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:w}),N&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[K,"%"]}),F!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${F>0?"text-positive-400":F<0?"text-negative-400":"text-muted"}`,children:[F>0?"+":"",F.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Ea,{options:Uh,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(Ea,{options:_h,value:u,onChange:m,ariaLabel:"Series"}),e.jsx(Ea,{options:Fh,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let Y;if(j)Y=e.jsx("p",{className:"text-sm text-negative-400",children:ur(j)});else if(p.isLoading&&!h)Y=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(o==="mentionShare"&&te===0)Y=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!h||!g)Y=null;else{const{rows:H,series:P,hasData:ae}=g,le=Gh(h.queryChanges);if(!ae)Y=e.jsx("p",{className:"text-sm text-secondary",children:o==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${ba(D)} in this window yet.`:cs()?_s:"Run a sweep to start tracking citations and mentions over time."});else if(N&&P.length===0)Y=e.jsxs("p",{className:"text-sm text-secondary",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-strong",children:"All engines"})," to see the trend."]});else{const O=`${w} rate across ${H.length} ${H.length===1?"sweep":"sweeps"}. Latest ${K}%${F!==null?`, ${F>=0?"up":"down"} ${Math.abs(F).toFixed(1)} points over the period`:""}.`;Y=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:O}),e.jsx(Xh,{buckets:$,metric:o,mode:b,series:P}),N&&P.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:P.map((W,ue)=>{const _=ci(H,W),Z=$h($,W),fe=f===null?"Attribution unavailable":Z?ws(Z):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:Pn(W,ue)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:To(W)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),fe]})]}),_!==null&&e.jsxs("span",{className:"trend-legend-value",children:[_,"%"]})]},W)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${w} trend chart over ${H.length} ${H.length===1?"bucket":"buckets"}`,children:e.jsx(an,{width:"100%",height:"100%",children:e.jsxs(rn,{data:H,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ua,{stroke:da,vertical:!1}),e.jsx(on,{dataKey:"date",tick:Kt,tickLine:!1,axisLine:{stroke:ls},tickFormatter:B,minTickGap:24}),e.jsx(ln,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:W=>`${W}%`,tick:Kt,tickLine:!1,axisLine:!1,width:40}),e.jsx(cn,{cursor:{stroke:ls,strokeWidth:1},content:e.jsx(Jh,{metric:o,mode:b,buckets:$})}),y.buckets.map(({bucketStartDate:W,events:ue})=>e.jsx($u,{x:W,stroke:Hh(ue),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${W}`)),P.map((W,ue)=>e.jsx(Js,{type:"monotone",dataKey:W,name:W,stroke:Pn(W,ue),strokeDasharray:W===ns?"5 4":void 0,strokeWidth:Kh(W)?2.5:2,dot:W===ns?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:Pn(W,ue),strokeWidth:1.5}:{r:2.5,fill:Pn(W,ue),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Bh},connectNulls:W!==ns,isAnimationActive:!1},W))]})})}),e.jsx(Yh,{partition:y,available:f!==null,counts:C,truncated:Q,incompleteHistory:M,served:R,mismatch:c,buckets:$}),le&&e.jsx("p",{className:"visibility-trend-note",children:le})]})}}return e.jsxs("section",{className:"visibility-trend",children:[ie,Y]})}const hi=new Set([Tn.queued,Tn.running]);function ex({projectName:t}){const s=As(),[n,a]=l.useState(""),[r,o]=l.useState(""),[i,u]=l.useState(""),[m,d]=l.useState("__default__"),[p,h]=l.useState(null),j=Re({...ac({client:V,path:{name:t}}),staleTime:6e4}),b=Re({...rc({client:V}),staleTime:6e4}),g=Re({...ic({client:V,path:{name:t},query:{limit:20}}),refetchInterval:w=>w.state.data?.runs.some(U=>hi.has(U.status))?3e3:!1}),f=g.data?.runs??[];l.useEffect(()=>{!p&&f[0]&&h(f[0].id)},[f,p]);const y=f.find(w=>w.id===p)??null,C=Re({...oc({client:V,path:{name:t,runId:p??""}}),enabled:!!p,refetchInterval:y&&hi.has(y.status)?3e3:!1}),Q=C.data??null,M=l.useMemo(()=>nx(n),[n]),R=j.data?.locations??[],c=l.useMemo(()=>{const w=new Map((b.data?.providerCatalog??[]).map(U=>[U.name,U]));return(b.data?.providers??[]).filter(U=>U.configured&&w.get(U.name)?.mode==="api").map(U=>({...U,catalog:w.get(U.name)}))},[b.data]),v=!b.isLoading&&c.length===0,N=c.find(w=>w.name===r)??null;l.useEffect(()=>{r&&!N&&(o(""),u(""))},[r,N]);const $=Et({...lc(),onSuccess:async w=>{h(w.id),a(""),u(""),await ox(s),ke({title:"Research batch saved",detail:`${w.totalQueries} quer${w.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${w.id}`,dedupeMode:"replace"})},onError:w=>{ke({title:"Could not start research",detail:w instanceof Error?w.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function D(){if(M.length===0||M.length>50||v||$.isPending||ee())return;const w=m==="__default__"?void 0:m==="__none__"?null:R.find(U=>U.label===m)??void 0;$.mutate({client:V,path:{name:t},body:{queries:M,...r?{provider:r}:{},...r&&i.trim()?{model:i.trim()}:{},...w!==void 0?{location:w}:{}}})}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.85fr)_minmax(360px,1.15fr)]",children:[e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"New batch"}),e.jsx("h3",{children:"Research queries"}),e.jsx("p",{className:"mt-1 max-w-xl text-sm leading-6 text-muted",children:"Run specific queries against one API model and keep the answers as a separate research record."})]})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"research-queries",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Queries"}),e.jsx("textarea",{id:"research-queries",className:"mt-1 min-h-36 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:`one query per line
|
|
3
|
+
e.g. What is the best way to choose an AEO platform?`,value:n,onChange:w=>a(w.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${M.length>50?"text-negative":"text-faint"}`,children:[M.length," ",M.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block",htmlFor:"research-provider",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"API provider"}),e.jsxs("select",{id:"research-provider",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:r,onChange:w=>{o(w.target.value),u("")},children:[e.jsx("option",{value:"",children:"Project default"}),c.map(w=>e.jsx("option",{value:w.name,children:w.displayName??w.name},w.name))]})]}),e.jsxs("label",{className:"block",htmlFor:"research-location",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"research-location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:m,onChange:w=>d(w.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),R.map(w=>e.jsx("option",{value:w.label,children:w.label},w.label))]})]})]}),e.jsxs("label",{className:"block",htmlFor:"research-model",children:[e.jsxs("span",{className:"text-xs font-medium text-secondary",children:["Exact model ",e.jsx("span",{className:"font-normal text-muted",children:"(optional)"})]}),e.jsx("input",{id:"research-model",list:"research-known-models",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 disabled:cursor-not-allowed disabled:opacity-50",placeholder:N?`Default: ${N.model??N.defaultModel??N.catalog.defaultModel}`:"Choose a provider to select an exact model",value:i,disabled:!N,onChange:w=>u(w.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(N?.catalog.knownModels??[]).map(w=>e.jsx("option",{value:w.id,children:w.displayName},w.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!ee()&&e.jsxs(We,{type:"button",size:"sm",disabled:M.length===0||M.length>50||v||$.isPending,onClick:D,children:[e.jsx(ca,{size:14}),$.isPending?"Starting research…":`Run ${M.length||""} research ${M.length===1?"query":"queries"}`]}),e.jsx("p",{className:"text-xs leading-5 text-muted",children:"Saved to research history. Nothing is added to tracked queries."})]}),v&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."})]})]}),e.jsxs(xe,{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:"Saved research batches"})]}),g.isFetching&&e.jsx(de,{tone:"neutral",children:"Loading"})]}),f.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:"No research batches yet. Add one or more queries to begin."}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:f.map(w=>e.jsxs("tr",{className:p===w.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:()=>h(w.id),children:ax(w.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:w.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:w.requestedModel??w.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:w.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[w.completedQueries+w.failedQueries,"/",w.totalQueries]}),e.jsx("td",{children:e.jsx(de,{tone:Do(w.status),children:w.status})})]},w.id))})]})})]})]}),e.jsx(tx,{detail:Q,isLoading:C.isFetching})]})}function tx({detail:t,isLoading:s}){const[n,a]=l.useState(null);l.useEffect(()=>{a(t?.queries[0]?.id??null)},[t?.id]);const r=t?.queries.find(o=>o.id===n)??t?.queries[0]??null;return e.jsxs(xe,{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:"Results"}),e.jsx("h3",{children:t?`Research run ${rx(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(de,{tone:Do(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(o=>e.jsxs("tr",{className:r?.id===o.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(o.id),children:o.query})}),e.jsx("td",{children:e.jsx(de,{tone:ix(o.status),children:o.status})}),e.jsx("td",{children:e.jsx(de,{tone:o.answerMentioned===!0?"positive":o.answerMentioned===!1?"neutral":o.status===Zs.failed?"negative":"caution",children:o.answerMentioned===null?o.status===Zs.failed?"Unavailable":"Pending":o.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(de,{tone:o.citationState==="cited"?"positive":o.citationState==="not-cited"?"neutral":o.status===Zs.failed?"negative":"caution",children:o.citationState===null?o.status===Zs.failed?"Unavailable":"Pending":o.citationState==="cited"?"Cited":"Not cited"})})]},o.id))})]})}),e.jsx(sx,{query:r,isLoading:s})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved batch to inspect each answer and its source links."})]})}function sx({query:t,isLoading:s}){return t?e.jsxs("div",{className:"space-y-4 border-t border-default pt-4 xl:border-t-0 xl:border-l xl:pl-4 xl:pt-0",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})]}),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("p",{className:"mt-1 whitespace-pre-wrap text-sm leading-6 text-secondary",children:t.answerText})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===Zs.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(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n},n))})]}),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(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n.replace(/^www\./,"")},n))})]}),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((n,a)=>{const r=Hs(n.uri),o=n.title||n.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[r?e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:o}):e.jsx("span",{className:"truncate text-secondary",children:o}),r&&e.jsx(Nu,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${n.uri}-${a}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function nx(t){const s=new Set;return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>{const a=n.toLocaleLowerCase();return!n||s.has(a)?!1:(s.add(a),!0)})}function ax(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 rx(t){return t.length>8?t.slice(0,8):t}function Do(t){return t===Tn.completed?"positive":t===Tn.partial?"caution":t===Tn.failed?"negative":"neutral"}function ix(t){return t===Zs.completed?"positive":t===Zs.failed?"negative":"neutral"}async function ox(t){await yt(t,"researchRuns")}const ir=new Set(["queued","seeding","probing"]);function lx({projectName:t}){const[s,n]=l.useState("find");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:"Query discovery"}),e.jsx("h2",{children:"Discover or research queries"})]})}),e.jsxs("div",{className:"inline-flex rounded-md border border-default bg-surface p-1",role:"tablist","aria-label":"Query discovery workflow",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":s==="find",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="find"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("find"),children:"Find queries"}),e.jsx("button",{type:"button",role:"tab","aria-selected":s==="research",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="research"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("research"),children:"Research queries"})]}),e.jsx("div",{className:"mt-4",children:s==="find"?e.jsx(cx,{projectName:t}):e.jsx(ex,{projectName:t})})]})}function cx({projectName:t}){const s=As(),[n,a]=l.useState(null),[r,o]=l.useState(""),[i,u]=l.useState("100"),m=Re({...cc({client:V,path:{name:t},query:{limit:"10"}}),refetchInterval:c=>c.state.data?.some(N=>ir.has(N.status))?3e3:!1}),d=m.data??[];l.useEffect(()=>{!n&&d[0]&&a(d[0].id)},[n,d]);const p=d.find(c=>c.id===n)??null,h=Re({...dc({client:V,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:p&&ir.has(p.status)?3e3:!1}),j=h.data??null,b=Re({...uc({client:V,path:{name:t,id:n??""}}),enabled:!!(n&&p?.status==="completed")}),g=Et({mutationFn:()=>{const c={},v=r.trim();v&&(c.icpDescription=v);const N=Number.parseInt(i,10);return Number.isFinite(N)&&N>0&&(c.maxProbes=N),mc(t,c)},onSuccess:async c=>{a(c.sessionId),o(""),await pi(s,t,c.sessionId),ke({title:"Discovery started",detail:`Run ${qa(c.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${c.sessionId}`,dedupeMode:"replace"})},onError:c=>{ke({title:"Discovery failed to start",detail:c instanceof Error?c.message:"Could not start discovery.",tone:"negative"})}}),f=Et({mutationFn:c=>{if(!n)throw new Error("Select a completed discovery session first.");return hc(t,n,c)},onSuccess:async c=>{await pi(s,t,c.sessionId),s.invalidateQueries({queryKey:no({client:V})}),s.invalidateQueries({predicate:v=>Array.isArray(v.queryKey)&&v.queryKey[0]==="projects"&&v.queryKey.length>1}),ke({title:"Queries added",detail:hx(c),tone:"positive",dedupeKey:`discovery:promote:${c.sessionId}`,dedupeMode:"replace"})},onError:c=>{ke({title:"Could not add queries",detail:c instanceof Error?c.message:"Could not add queries from this run.",tone:"negative"})}}),y=j??p,C=b.data??null,Q=(C?.queriesByBucket.cited.length??0)+(C?.queriesByBucket.aspirational.length??0),M=l.useMemo(()=>(j?.probes??[]).slice(0,30),[j?.probes]);async function R(){try{const c=await m.refetch();if(c.error)throw c.error;const v=c.data?.length??0;ke({title:"Discovery sessions refreshed",detail:`${v} recent session${v===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(c){ke({title:"Discovery refresh failed",detail:c instanceof Error?c.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:ee()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{R()},children:[e.jsx(la,{className:`size-3.5 ${m.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(xe,{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:r,onChange:c=>o(c.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:i,onChange:c=>u(c.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."})]}),!ee()&&e.jsxs(We,{type:"button",size:"sm",disabled:g.isPending,onClick:()=>g.mutate(),children:[e.jsx(ca,{size:14}),g.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),m.isFetching&&e.jsx(de,{tone:"neutral",children:"Loading"})]}),d.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:d.map(c=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===c.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(c.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:qa(c.id)}),e.jsx(de,{tone:xi(c.status),children:c.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",c.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",c.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",c.wastedCount??0]})]})]},c.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(xe,{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:y?qa(y.id):"No run selected"})]}),y&&e.jsx(de,{tone:xi(y.status),children:y.status})]}),y?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx($s,{label:"Questions tested",value:y.probeCount??0}),e.jsx($s,{label:"Cited queries",value:y.citedCount??0,tone:"positive"}),e.jsx($s,{label:"Worth tracking",value:y.aspirationalCount??0,tone:"caution"}),e.jsx($s,{label:"Skip",value:y.wastedCount??0,tone:"negative"})]}),y.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:y.error}),y.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:y.warning}),y.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:y.icpDescription})]}),y.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:y.competitorMap.slice(0,8).map(c=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[c.domain," ",e.jsx("span",{className:"text-muted",children:c.hits})]},c.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),y?.status==="completed"&&e.jsxs(xe,{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 2"}),e.jsx("h3",{children:"Choose queries to track"})]}),!ee()&&e.jsxs(We,{type:"button",size:"sm",disabled:f.isPending||Q===0,onClick:()=>f.mutate(void 0),children:[e.jsx(lo,{size:14}),f.isPending?"Adding…":"Add recommended queries"]})]}),b.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):C?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx($s,{label:"Queries to add",value:Q,tone:"positive"}),e.jsx($s,{label:"Cited queries",value:C.queriesByBucket.cited.length,tone:"positive"}),e.jsx($s,{label:"Worth tracking",value:C.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx($s,{label:"Skip",value:C.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Adds Cited queries and Worth tracking queries, plus recurring competitor sites. Skip items remain available for review only."}),C.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-secondary",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:C.suggestedCompetitors.map(c=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[c.domain," ",e.jsx("span",{className:"text-muted",children:c.hits})]},c.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(xe,{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"})]}),h.isFetching&&e.jsx(de,{tone:"neutral",children:"Loading"})]}),M.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("tbody",{children:M.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:c.query}),e.jsx("td",{children:e.jsx(de,{tone:dx(c.bucket),children:mx(c.bucket)})}),e.jsx("td",{className:"text-secondary",children:c.citedDomains.length>0?c.citedDomains.slice(0,3).join(", "):"-"})]},c.id))})]})})]})]})]})]})}function $s({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 xi(t){return t==="completed"?"positive":t==="failed"?"negative":ir.has(t)?"caution":"neutral"}function dx(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const ux={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function mx(t){return t?ux[t]:"Not classified"}function qa(t){return t.length>8?t.slice(0,8):t}function hx(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,a=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${a>0?`; ${a} already tracked`:""}.`}async function pi(t,s,n){await Promise.all([yt(t,"discovery"),t.invalidateQueries({queryKey:xc({client:V})})])}function gi(t){return`${(t*100).toFixed(1)}%`}function xx({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),u=Re({...pc({client:V,path:{name:t},query:{limit:30}}),enabled:s==="health"}),m=Re({...gc({client:V,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),d=(m.data??[]).filter(y=>(y.status==="completed"||y.status==="partial")&&y.trigger!=="probe").reverse(),p=o??d[0]?.id??"",h=a??d.find(y=>y.id!==p)?.id??"",j=!!(h&&p&&h!==p),b=Re({...fc({client:V,path:{name:t},query:{run1:h,run2:p}}),enabled:s==="compare"&&j}),g=u.data??[],f=b.data?.diff.filter(y=>y.changed||y.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([y,C])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===y,className:`filter-chip ${s===y?"filter-chip-active":""}`,onClick:()=>n(y),children:C},y))}),s==="changes"?e.jsx(Mu,{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."})]}),u.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!u.isLoading&&g.length===0?e.jsxs(xe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:cs()?_s:"Complete an answer visibility sweep to create the first snapshot."})]}):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:"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:g.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(y.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[y.mentionedPairs,"/",y.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:gi(y.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[y.citedPairs,"/",y.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:gi(y.overallCitedRate)})]},y.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:h,onChange:y=>r(y.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:d.map(y=>e.jsx("option",{value:y.id,children:new Date(y.createdAt).toLocaleString()},y.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:p,onChange:y=>i(y.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:d.map(y=>e.jsx("option",{value:y.id,children:new Date(y.createdAt).toLocaleString()},y.id))})]})]}),m.isLoading||b.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!m.isLoading&&d.length<2?e.jsxs(xe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:cs()?_s:"Run another answer visibility sweep before comparing historical evidence."})]}):null,b.data&&f.length===0?e.jsxs(xe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,f.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:f.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:y.query??"Archived query"}),e.jsx("td",{children:e.jsxs(de,{tone:y.changed?"caution":"neutral",children:[y.run1State??"none"," → ",y.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(de,{tone:y.visibilityChanged?"caution":"neutral",children:[y.run1MentionState??"none"," → ",y.run2MentionState??"none"]})})]},y.queryId??y.query??"unknown"))})]})}):null]}):null]})}const fi={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},px={contract:null,assessment:null,googleAds:fi,gtm:fi,snapshots:[]};function gx(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":vx(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function fx(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 bx(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 yx(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 Eo(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"&&jx(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 vx(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function jx(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function qo(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 Nx(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 wx(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 Vs(t){return t.length<=12?t:`…${t.slice(-10)}`}function Sx(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 Cx(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 Oa={"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 bi(t){return t.outcome==="pass"?{label:Oa[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Oa[t.code],tone:"negative",outcome:"Fail"}:{label:Oa[t.code],tone:"caution",outcome:"Unknown"}}function kx(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Ax(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 Px(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function yi({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=qo(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 ${Vt(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 Rx="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.",Ix="Available once Google Ads and Tag Manager are connected.",Tx="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 $x({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:o}){const i=t.googleAds.state==="connected",u=t.gtm.state==="connected",m=t.googleAds.state==="unavailable",d=t.gtm.state==="unavailable",p=m||d||t.gtm.state==="unavailable",h={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},j=!i&&!u,b=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:m?h:bx(t)},{title:"Tag Manager",state:t.gtm.state,ready:u,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:d?h:yx(t)}],g=i&&u&&!p?Eo(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(ze,{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."})]}),j?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:Tx}):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(ze,{text:Rx})]}),g&&s?e.jsx(We,{type:"button",disabled:r,onClick:()=>s(g.id),children:r?"Working…":g.label}):e.jsx("p",{className:"text-sm text-secondary",children:Ix})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:b.map(f=>{const y=f.ready?{label:"Ready",tone:"positive"}:qo(f.state),C=f.action;return e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-heading",children:f.title}),e.jsx(de,{tone:y.tone,children:y.label}),f.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:f.summary}):null,C&&s?C.id==="retry-connection-status"?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(C.id),children:r?"Working…":C.label}):e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(C.id),children:r?"Working…":C.label}):null,f.summary&&f.onChange?e.jsx(We,{type:"button",variant:"ghost",size:"sm","aria-label":f.changeLabel,disabled:r,onClick:f.onChange,children:"Change"}):null]},f.title)})}),o?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:o}):null]})]})}function Mx({workspace:t=px,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:o=null,onSelectContract:i,contractError:u=null,onRetryContracts:m,onRetryEvidence:d,onChangeGoogleAdsSelection:p,onChangeGtmSelection:h,onAddContract:j}){const b=gx(t),g=fx(b),f=Eo(t),y=t.assessment?.findings??[],C=y.filter(c=>c.outcome!=="pass"),Q=y.filter(c=>c.outcome==="pass"),M=C.some(c=>c.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&u===null?e.jsx($x,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:p,onChangeGtmSelection:h,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:g.tone,children:g.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Vt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:g.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(c=>e.jsxs("li",{className:"break-words",children:[Px(c)," ",c.kind,", captured ",Vt(c.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",c.id,")"]})]},c.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?f.id==="review-findings"||f.id==="review-runtime-verification"||f.id==="retry-connection-status"||f.id==="select-contract"||f.id==="retry-integrity"||f.id==="waiting-for-integrity"?e.jsx(A,{type:"button",disabled:n||f.id==="waiting-for-integrity",onClick:()=>s(f.id),children:n?"Working…":f.label}):e.jsx(We,{type:"button",disabled:n,onClick:()=>s(f.id),children:n?"Working…":f.label}):f.id==="review-findings"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):b==="runtime-unverified"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:f.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),r.length>0&&j?e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:j,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:c=>i?.(c.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(c=>e.jsx("option",{value:c.id,children:c.name},c.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:Sx(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:Cx(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:Vs(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:Vs(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:Vs(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:Vs(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."}),u?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:u}),m?e.jsx(A,{type:"button",variant:"outline",onClick:m,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),C.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:M,children:[C.length," ",C.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:C.map(c=>{const v=bi(c);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:v.label}),e.jsx(de,{tone:v.tone,children:v.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",c.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",c.code]}),c.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",c.evidenceIds.join(", ")]}):null]},`${c.code}:${c.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(ze,{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(c=>{const v=Nx(c.key,b);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${v==="positive"?"bg-positive-fill":v==="caution"?"bg-caution-fill":v==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:c.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:c.detail}),e.jsx(de,{tone:v,children:wx(c.key,b)})]},c.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:[yi({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:p}:{},actionPending:n}),yi({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:h}:{},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)&&d?e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:d,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(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:c.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:c.kind}),e.jsx("td",{className:"text-secondary",children:Vt(c.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:Vs(c.id)})]},c.id))})]})})]}):null,Q.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[Q.length," ",Q.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:Q.map(c=>{const v=bi(c);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:v.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",c.code]}),c.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",c.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(de,{tone:v.tone,children:v.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:c.subject})]},`${c.code}:${c.subject}`)})})]})})]}):null,b==="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 ",kx(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:Vs(t.contract.gtm.tagId)})," fires with ",Ax(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:Vs(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const Ks=3e4,vi={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Rt="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",ts="text-sm font-medium text-secondary";function ji(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:mt(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function Wn(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function Lx(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 Dx(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Ex(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:Dx(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 qx(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:Wn(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:Wn(t.triggerIds),variableIds:Wn(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:Wn(t.productionHosts)}}}function Ni(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 Yn(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 Jn(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Xn({id:t,label:s,value:n,onChange:a,children:r,disabled:o=!1}){return e.jsxs("label",{htmlFor:t,className:ts,children:[s,e.jsx("select",{id:t,className:Rt,value:n,onChange:i=>a(i.target.value),disabled:o,children:r})]})}function hn({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 wi({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[u,m]=l.useState(null),d=l.useRef(null),p=l.useRef(null),h=l.useRef(!1);l.useEffect(()=>{const f=h.current;h.current=a,a?p.current?.focus():f&&d.current?.querySelector("button")?.focus()},[a]);function j(){m(null),r(!0)}function b(){m(null),r(!1)}async function g(){i(!0),m(null);try{await n()}catch(f){m(mt(f)),i(!1)}}return e.jsx("div",{ref:d,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(A,{ref:p,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:o,onClick:b,children:"Keep connected"}),e.jsx(We,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||o,onClick:()=>{g()},children:o?"Disconnecting…":`Disconnect ${t}`})]}),u?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:u}):null]}):e.jsxs(We,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:j,children:["Disconnect ",t]})})}function Si({id:t,label:s,options:n,synced:a,loading:r,failed:o,onRetry:i,emptyHint:u,value:m,onChange:d}){const p=n.some(f=>f.id===m),[h,j]=l.useState(!1),b=h||m!==""&&!p&&n.length>0,g=e.jsx("label",{htmlFor:t,className:ts,children:s});return r?e.jsxs("div",{children:[g,e.jsx("select",{id:t,className:Rt,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):o?e.jsxs("div",{children:[g,e.jsx("input",{id:t,required:!0,className:Rt,value:m,onChange:f=>d(f.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:i,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[g,e.jsx("input",{id:t,required:!0,className:Rt,value:m,onChange:f=>d(f.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":u})]}):e.jsxs("div",{children:[g,b?e.jsx("input",{id:t,required:!0,className:Rt,value:m,onChange:f=>d(f.target.value)}):e.jsxs("select",{id:t,required:!0,className:Rt,value:m,onChange:f=>d(f.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(f=>e.jsxs("option",{value:f.id,children:[f.name,f.detail?` (${f.detail})`:"",f.active?"":" — inactive"]},f.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{j(!b),d("")},children:b?"Choose from synced list":"Enter an ID manually"})]})}function Ox({projectId:t,projectName:s}){const n=ao(),[a,r]=l.useState(null),[o,i]=l.useState(null),[u,m]=l.useState(!1),[d,p]=l.useState(""),[h,j]=l.useState(null),[b,g]=l.useState(!1),[f,y]=l.useState(!1),[C,Q]=l.useState(""),[M,R]=l.useState(""),[c,v]=l.useState(""),[N,$]=l.useState(""),[D,w]=l.useState(""),[U,z]=l.useState(!1),[B,K]=l.useState(vi),[pe,we]=l.useState(null),F=l.useRef(null),te=Re({...bc({client:V,path:{name:s}}),staleTime:Ks}),ie=Re({...yc({client:V,path:{name:s}}),staleTime:Ks}),Y=Re({...vc({client:V,path:{name:s}}),staleTime:Ks}),H=Re({...jc({client:V,path:{name:s}}),staleTime:Ks}),P=H.data,ae=Re({...Nc({client:V,path:{name:s},query:{limit:5}}),staleTime:Ks}),le=Re({...wc({client:V,path:{name:s},query:{limit:5}}),staleTime:Ks}),O=Y.data??[],ue=(pe?O.find(S=>S.id===pe)??null:null)??(O.length===1?O[0]??null:null),_=O.length>1&&!ue,Z=Re({...Sc({client:V,path:{name:s,contractId:ue?.id??""}}),enabled:!!ue,staleTime:Ks}),fe=Re({...Cc({client:V,path:{name:s}}),enabled:h==="google-ads"&&te.data?.connected===!0,staleTime:0}),Fe=Re({...kc({client:V,path:{name:s}}),enabled:h==="gtm"&&ie.data?.connected===!0,staleTime:0}),Le=Re({...Ac({client:V,path:{name:s,accountId:c}}),enabled:h==="gtm"&&!!c,staleTime:0}),Ae=Re({...Pc({client:V,path:{name:s,accountId:c,containerId:N}}),enabled:h==="gtm"&&!!c&&!!N,staleTime:0}),Xe=Et(Rc({client:V})),lt=Et(Ic({client:V})),Se=Et(Tc({client:V})),et=Et($c({client:V})),Ve=Et(Mc({client:V})),_e=Et(Lc({client:V})),Ue=Et(Dc({client:V})),Ie=Et(Ec({client:V})),G=Et(qc({client:V}));l.useEffect(()=>{if(h!=="google-ads"||b||!te.isSuccess)return;const S=te.data.connection?.selection;Q(S?.customerId??""),R(S?.loginCustomerId??""),g(!0)},[b,te.data,te.isSuccess,h]),l.useEffect(()=>{if(h!=="gtm"||f||!ie.isSuccess)return;const S=ie.data.selection;v(S?.accountId??""),$(S?.containerId??""),w(S?.workspaceId??""),y(!0)},[f,ie.data,ie.isSuccess,h]),l.useEffect(()=>{!pe||!Y.data||Y.data.some(S=>S.id===pe)||we(null)},[Y.data,pe]);const T=l.useMemo(()=>{const S=ae.data?.snapshots??[],oe=le.data?.snapshots??[],at=[...S.map($t=>({id:$t.id,provider:"google-ads",kind:$t.kind,capturedAt:$t.capturedAt})),...oe.map($t=>({id:$t.id,provider:"gtm",kind:$t.kind,capturedAt:$t.capturedAt}))].sort(($t,_t)=>_t.capturedAt.localeCompare($t.capturedAt)).slice(0,5),Pe=[],it=Z.data?.googleAdsSnapshot,Jt=Z.data?.gtmSnapshot;return it&&Pe.push({id:it.id,provider:"google-ads",kind:it.kind,capturedAt:it.capturedAt}),Jt&&Pe.push({id:Jt.id,provider:"gtm",kind:Jt.kind,capturedAt:Jt.capturedAt}),{contract:Z.data?.assessment.contract??ue,assessment:Z.data?.assessment??null,contractSelectionRequired:_,assessmentState:ue?Z.isError?"unavailable":Z.isLoading?"loading":void 0:void 0,assessmentError:Z.isError?mt(Z.error):null,googleAds:Lx(te.data,ji(ae.data?.total??0,ae.isLoading,ae.isError,ae.error),te.isError),gtm:Ex(ie.data,ji(le.data?.total??0,le.isLoading,le.isError,le.error),ie.isError),snapshots:at,assessmentEvidenceSnapshots:Pe}},[ue,_,ae.data,ae.error,ae.isError,ae.isLoading,te.data,te.isError,le.data,le.error,le.isError,le.isLoading,ie.data,ie.isError,Z.data,Z.error,Z.isError,Z.isLoading]),E=l.useSyncExternalStore(eo,ra,ra),he=Object.values(E.runs).some(S=>S.projectId===t&&(S.kind===Fs["google-ads-sync"]||S.kind===Fs["gtm-sync"])),be=Xe.isPending||lt.isPending||Se.isPending||et.isPending||Ve.isPending||_e.isPending||Ue.isPending||Ie.isPending||G.isPending||he;async function J(){await Promise.all([te.refetch(),ie.refetch(),Y.refetch(),ae.refetch(),le.refetch(),H.refetch(),ue?Z.refetch():Promise.resolve()])}async function Ze(S){await J();for(let oe=0;oe<10&&!S();oe+=1)await new Promise(at=>setTimeout(at,1500)),await J()}function zt(){const S=document.activeElement;F.current=S instanceof HTMLElement?S:null}function Ye(S){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(S);return}globalThis.setTimeout(S,0)}function Te(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function $e(S){if(!S)return;!S.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!S.hasAttribute("tabindex")&&(S.tabIndex=-1),S.focus({preventScroll:!0})}function pt(S,oe=S){const at=document.getElementById(S);at instanceof HTMLDetailsElement&&(at.open=!0);const Pe=at?.scrollIntoView;typeof Pe=="function"&&Pe.call(at,{behavior:Te()?"auto":"smooth",block:"start"}),$e(document.getElementById(oe)??at)}function ct(S,oe){zt(),Ye(()=>pt(S,oe))}function Oe(){const S=F.current;F.current=null,S&&Ye(()=>{S.isConnected&&S.focus({preventScroll:!0})})}function Qe(){r(null),m(!1),Oe()}function vt(){r(null),j(null),Oe()}function Ke(){r(null),z(!1),Oe()}function Ee(){r(null),j(null),m(!0),ct("google-ads-connect-panel","google-ads-connect-title")}function qe(){r(null),Q(""),R(""),g(!1),j("google-ads"),m(!1),ct("google-ads-selection-panel","google-ads-selection-title")}function jt(){r(null),v(""),$(""),w(""),y(!1),j("gtm"),m(!1),ct("gtm-selection-panel","gtm-selection-title")}function Ge(){r(null),z(!0),ct("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function It(S,oe){Zi({id:S.id,projectId:S.projectId,kind:S.kind,projectLabel:s,sourceAction:oe}),ke({title:oe==="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:${S.id}`,dedupeMode:"replace"})}async function Gt(){gs(n),r(null);try{const S=await Xe.mutateAsync({path:{name:s},body:{provider:"google-ads",...d.trim()?{developerToken:d.trim()}:{}}});p(""),m(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Ni(S.authorizationUrl,()=>{J(),i(null),Oe()})}catch(S){r(mt(S))}}async function gt(){gs(n),r(null);try{const S=await lt.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."),Ni(S.authorizationUrl,()=>{J(),i(null),Oe()})}catch(S){r(mt(S))}}async function kt(){if(gs(n),!C){r("Select a Google Ads customer before saving.");return}r(null);try{await Se.mutateAsync({path:{name:s},body:{customerId:C,...M.trim()?{loginCustomerId:M.trim()}:{}}}),j(null),Oe(),await Ze(()=>te.data?.selectedCustomer!=null)}catch(S){r(mt(S))}}async function ht(){if(gs(n),!c||!N){r("Select a Tag Manager account and container before saving.");return}r(null);try{await et.mutateAsync({path:{name:s},body:{accountId:c,containerId:N,...D?{workspaceId:D}:{}}}),j(null),Oe(),await Ze(()=>ie.data?.status==="connected")}catch(S){r(mt(S))}}async function q(){gs(n),r(null),await Ue.mutateAsync({path:{name:s}}),j(null),m(!1),Q(""),R(""),g(!1),i(null),await J(),ke({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),F.current=null,Ye(()=>$e(document.getElementById("conversion-integrity-title")))}async function Ce(){gs(n),r(null),await Ie.mutateAsync({path:{name:s}}),j(null),v(""),$(""),w(""),y(!1),i(null),await J(),ke({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),F.current=null,Ye(()=>$e(document.getElementById("conversion-integrity-title")))}async function ye(){gs(n),r(null);try{const S=await Ve.mutateAsync({path:{name:s}});It(S,"google-ads-sync")}catch(S){r(mt(S))}}async function je(){gs(n),r(null);try{const S=await _e.mutateAsync({path:{name:s}});It(S,"gtm-sync")}catch(S){r(mt(S))}}async function ft(){gs(n),r(null);try{const S=await Promise.allSettled([Ve.mutateAsync({path:{name:s}}),_e.mutateAsync({path:{name:s}})]),[oe,at]=S;oe.status==="fulfilled"&&It(oe.value,"google-ads-sync"),at.status==="fulfilled"&&It(at.value,"gtm-sync");const Pe=S.find(it=>it.status==="rejected");if(Pe?.status==="rejected")throw Pe.reason}catch(S){r(mt(S))}}async function Je(){gs(n);const S=te.data?.connection?.selection.customerId,oe=ie.data?.selection;if(!S||!oe?.accountId||!oe.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const at=await G.mutateAsync({path:{name:s},body:qx(B,S,{accountId:oe.accountId,containerId:oe.containerId})});K(vi),z(!1),Oe(),(await Y.refetch()).data?.some(it=>it.id===at.id)&&we(at.id)}catch(at){r(mt(at))}}function At(S){switch(S){case"connect-google-ads":Ee();return;case"connect-gtm":zt(),gt();return;case"select-google-ads":qe();return;case"select-gtm":jt();return;case"sync-google-ads":ye();return;case"sync-gtm":je();return;case"sync-static-evidence":ft();return;case"declare-contract":Ge();return;case"review-findings":ct("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":ct("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":J();return;case"select-contract":ct("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":Z.refetch();return;case"waiting-for-integrity":return}}const Nt=fe.data?.customers??[],rs=Fe.data?.accounts??[],is=Le.data?.containers??[],ds=Ae.data?.workspaces??[],rt=!!C&&!Nt.some(S=>S.customerId===C),us=!!c&&!rs.some(S=>S.id===c),dt=!!N&&!is.some(S=>S.id===N),ys=!!D&&!ds.some(S=>S.id===D),Wt=rt&&fe.isSuccess&&fe.data.truncated===!1,Ft=us&&Fe.isSuccess&&Fe.data.truncated===!1,Yt=dt&&Le.isSuccess&&Le.data.truncated===!1,wt=ys&&Ae.isSuccess&&Ae.data.truncated===!1,ms=Ft||Yt||wt,Qt=Ft?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Yt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":wt?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,bt=Jn(Wt,fe.data,fe.isError),vs=Jn(Ft,Fe.data,Fe.isError),Pt=Jn(Yt,Le.data,Le.isError),hs=Jn(wt,Ae.data,Ae.isError),xs=fe.isError?mt(fe.error):null,ps=Fe.isError?mt(Fe.error):Le.isError?mt(Le.error):Ae.isError?mt(Ae.error):null,St=h==="google-ads"?xs:h==="gtm"?ps:null,I=Yn("customer",fe.data,Nt.length),X=Yn("account",Fe.data,rs.length),ge=Yn("container",Le.data,is.length),se=Yn("draft workspace",Ae.data,ds.length),re=Fe.isError||Le.isError||Ae.isError&&!!D,Me=u||h!==null||U;function Tt(){fe.refetch()}function ut(){if(Fe.isError){Fe.refetch();return}if(Le.isError){Le.refetch();return}Ae.isError&&Ae.refetch()}return te.isLoading||ie.isLoading||Y.isLoading?e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("div",{"aria-hidden":"true",className:"mt-5 grid gap-4 sm:grid-cols-2",children:[0,1].map(S=>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"})]},S))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):Y.isError&&!Y.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",mt(Y.error)]}),e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{Y.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Mx,{workspace:T,onPrimaryAction:At,actionPending:be,actionError:Me?null:a,contracts:O,selectedContractId:ue?.id??null,onSelectContract:S=>we(S||null),contractError:Y.isError?mt(Y.error):null,onRetryContracts:()=>{Y.refetch()},onRetryEvidence:()=>{Promise.all([ae.refetch(),le.refetch()])},onChangeGoogleAdsSelection:qe,onChangeGtmSelection:jt,onAddContract:()=>At("declare-contract")}),o?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:o}):null,u?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:De(async S=>{S.preventDefault(),await Gt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:ts,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:d,onChange:S=>p(S.target.value),className:Rt,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:Xe.isPending,children:Xe.isPending?"Starting…":"Continue to Google"}),e.jsx(A,{type:"button",variant:"outline",onClick:Qe,children:"Cancel"})]})]})]}):null,h==="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"})]})}),St?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:St}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:Tt,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Wt?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(Xn,{id:"google-ads-customer",label:"Customer account",value:C,onChange:S=>{g(!0),Q(S);const oe=Nt.find(at=>at.customerId===S);R(oe?.parentCustomerId??"")},disabled:fe.isLoading,children:[e.jsx("option",{value:"",children:fe.isLoading?"Loading accessible customers…":"Select a customer"}),rt?e.jsxs("option",{value:C,disabled:Wt,children:["Saved customer ",C," (",bt,")"]}):null,Nt.map(S=>e.jsx("option",{value:S.customerId,children:S.descriptiveName??`Customer ${S.customerId}`},S.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:ts,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Rt,value:M,onChange:S=>{g(!0),R(S.target.value)},placeholder:"Use only when a manager context is required"})]})]}),I?e.jsx("p",{role:"status",className:`mt-3 text-sm ${fe.data?.truncated?"text-caution":"text-secondary"}`,children:I}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"button",disabled:Se.isPending||fe.isLoading||fe.isError||Wt||!C,onClick:De(kt),children:Se.isPending?"Saving…":"Save customer selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:vt,children:"Cancel"})]}),te.data?.connected?e.jsx(wi,{providerLabel:"Google Ads",disabled:be,onDisconnect:q}):null]}):null,h==="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"})]})}),St?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:St}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:ut,children:Fe.isError?"Retry account list":Le.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Qt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Qt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Xn,{id:"gtm-account",label:"Account",value:c,onChange:S=>{y(!0),S!==c&&($(""),w("")),v(S)},disabled:Fe.isLoading,children:[e.jsx("option",{value:"",children:Fe.isLoading?"Loading accounts…":"Select an account"}),us?e.jsxs("option",{value:c,disabled:Ft,children:["Saved account ",c," (",vs,")"]}):null,rs.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))]}),e.jsxs(Xn,{id:"gtm-container",label:"Container",value:N,onChange:S=>{y(!0),S!==N&&w(""),$(S)},disabled:!c||Le.isLoading,children:[e.jsx("option",{value:"",children:Le.isLoading?"Loading containers…":"Select a container"}),dt?e.jsxs("option",{value:N,disabled:Yt,children:["Saved container ",N," (",Pt,")"]}):null,is.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))]}),e.jsxs(Xn,{id:"gtm-workspace",label:"Draft workspace (optional)",value:D,onChange:S=>{y(!0),w(S)},disabled:!N||Ae.isLoading,children:[e.jsx("option",{value:"",children:Ae.isLoading?"Loading workspaces…":"No draft workspace"}),ys?e.jsxs("option",{value:D,disabled:wt,children:["Saved draft workspace ",D," (",hs,")"]}):null,ds.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[X?e.jsx("p",{role:"status",className:Fe.data?.truncated?"text-caution":"text-secondary",children:X}):null,ge?e.jsx("p",{role:"status",className:Le.data?.truncated?"text-caution":"text-secondary",children:ge}):null,se?e.jsx("p",{role:"status",className:Ae.data?.truncated?"text-caution":"text-secondary",children:se}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"button",disabled:et.isPending||Fe.isLoading||Le.isLoading||Ae.isLoading&&!!D||re||ms||!c||!N,onClick:De(ht),children:et.isPending?"Saving…":"Save container selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:vt,children:"Cancel"})]}),ie.data?.connected?e.jsx(wi,{providerLabel:"Tag Manager",disabled:be,onDisconnect:Ce}):null]}):null,U?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:De(async S=>{S.preventDefault(),await Je()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:ts,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Rt,value:B.name,onChange:S=>K(oe=>({...oe,name:S.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:ts,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Rt,value:B.eventName,onChange:S=>K(oe=>({...oe,eventName:S.target.value})),placeholder:"booking_complete"})]}),e.jsx(Si,{id:"contract-conversion-action",label:"Google Ads conversion action",options:P?.googleAds.conversionActions??[],synced:P?.googleAds.syncedAt!=null,loading:H.isLoading,failed:H.isError,onRetry:()=>{H.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:B.conversionActionId,onChange:S=>K(oe=>({...oe,conversionActionId:S}))}),e.jsx(Si,{id:"contract-gtm-tag",label:"Tag Manager tag",options:P?.gtm.tags??[],synced:P?.gtm.syncedAt!=null,loading:H.isLoading,failed:H.isError,onRetry:()=>{H.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:B.tagId,onChange:S=>K(oe=>({...oe,tagId:S}))})]}),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:ts,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Rt,value:B.conversionId,onChange:S=>K(oe=>({...oe,conversionId:S.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:ts,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Rt,value:B.conversionLabel,onChange:S=>K(oe=>({...oe,conversionLabel:S.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:ts,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Rt,value:B.triggerIds,onChange:S=>K(oe=>({...oe,triggerIds:S.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:ts,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Rt,value:B.variableIds,onChange:S=>K(oe=>({...oe,variableIds:S.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:ts,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Rt,value:B.campaignIds,onChange:S=>K(oe=>({...oe,campaignIds:S.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:ts,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Rt,value:B.productionHosts,onChange:S=>K(oe=>({...oe,productionHosts:S.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(hn,{id:"contract-primary-action",checked:B.requirePrimaryAction,onChange:S=>K(oe=>({...oe,requirePrimaryAction:S})),children:"Google Ads action is primary"}),e.jsx(hn,{id:"contract-biddable-goal",checked:B.requireBiddableGoal,onChange:S=>K(oe=>({...oe,requireBiddableGoal:S})),children:"Google Ads goal is biddable"}),e.jsx(hn,{id:"contract-runtime-verification",checked:B.verificationRequired,onChange:S=>K(oe=>({...oe,verificationRequired:S})),children:"Runtime proof is required"}),e.jsx(hn,{id:"contract-transaction-id",checked:B.requireTransactionId,onChange:S=>K(oe=>({...oe,requireTransactionId:S})),children:"Transaction ID is required"}),e.jsx(hn,{id:"contract-value",checked:B.requireValue,onChange:S=>K(oe=>({...oe,requireValue:S})),children:"Conversion value is required"}),e.jsx(hn,{id:"contract-currency",checked:B.requireCurrency,onChange:S=>K(oe=>({...oe,requireCurrency:S})),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:G.isPending,children:G.isPending?"Saving…":"Save conversion contract"}),e.jsx(A,{type:"button",variant:"outline",onClick:Ke,children:"Cancel"})]})]})]}):null]})}const Gx=6e4,Fx=["7d","14d","30d"],xr="not available",_x='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%.',Ux="No Google Ads snapshot stored yet",Bx="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.",Vx="No closed days yet",Kx="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.",zx={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},Ms=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),Ga=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Oo=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),Qx=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function xn(t,s){return t===null||!Number.isFinite(t)?xr:s===null?Qx.format(t/1e6):Qu(t,s)}function Fa(t){if(t===null||!Number.isFinite(t))return xr;const s=t*100;return s>0&&s<.1?"<0.1%":`${Oo.format(s)}%`}function Hx(t,s){if(t===null||!Number.isFinite(t))return`${xr} 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%":`${Oo.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function Wx(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function Yx(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function Jx(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 Xx({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=Re({...Oc({client:V,path:{name:t},query:{window:s}}),staleTime:Gx}),i=o.data,u=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(ze,{text:_x})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Ot(i.startDate)," to ",Ot(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(fa,{windows:Fx,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:[u,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(c=>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"})]},c))}),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:[u,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",mt(o.error)]}),e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{o.refetch()},children:"Retry performance"})]});const{totals:m,daily:d,campaigns:p,comparison:h,comparisonUnavailableReason:j,source:b}=i;if(!b){const c=j==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[u,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:c?Vx:Ux}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:c?Kx:Bx})]})]})}const g=b.currencyCode,f=b.campaignsInInventory>0&&b.campaignsQueried<b.campaignsInInventory?{queried:b.campaignsQueried,inInventory:b.campaignsInInventory}:null,y=m.costMicros>0&&m.conversions===0,C=[{key:"spend",comparable:!0,label:"Spend",value:xn(m.costMicros,g),change:h?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:Ga.format(m.conversions),change:h?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:y?"no conversions":xn(m.costPerConversionMicros,g),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Fa(m.conversionRate),change:h?.change.conversionRate??null,direction:"up-good",seriesKey:null}],Q=[{key:"clicks",label:"Clicks",value:Ms.format(m.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:Ms.format(m.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Fa(m.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:xn(m.cpcMicros,g),seriesKey:null}],M={costMicros:{label:"Spend",color:nt[1],axisId:"spend",formatValue:c=>xn(c,g)},conversions:{label:"Conversions",color:nt[0],axisId:"conversions",formatValue:c=>Ga.format(c)},clicks:{label:"Clicks",color:nt[2],axisId:"clicks",formatValue:c=>Ms.format(c)},impressions:{label:"Impressions",color:nt[3],axisId:"impressions",formatValue:c=>Ms.format(c)}},R=[...a].map(c=>({dataKey:c,...M[c]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[u,f!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",Ms.format(f.queried)," of"," ",Ms.format(f.inInventory)," campaigns, so they are a subset of the account."]}):null,b.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,!h&&j==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:zx["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:C.map(c=>{const v=c.seriesKey!==null&&a.has(c.seriesKey),N=v&&a.size===1,$=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[c.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?M[c.seriesKey].color:"var(--color-mono-600)"}}):null,c.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:c.value}),h&&c.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${Jx(c.change,c.direction)}`,children:Hx(c.change,h.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:c.comparable?`no prior ${s} period stored`:" "})]});return c.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:$},c.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:N,onClick:()=>r(D=>{const w=new Set(D);return w.has(c.seriesKey)?w.delete(c.seriesKey):w.add(c.seriesKey),w.size===0?D:w}),className:`rounded-md border px-3 py-2 text-left transition-colors ${v?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${N?"cursor-default":""}`,children:$},c.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:Q.map(c=>{const v=c.seriesKey!==null&&a.has(c.seriesKey),N=v&&a.size===1,$=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[c.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?M[c.seriesKey].color:"var(--color-mono-600)"}}):null,c.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:c.value})]});return c.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:$},c.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:N,onClick:()=>r(D=>{const w=new Set(D);return w.has(c.seriesKey)?w.delete(c.seriesKey):w.add(c.seriesKey),w.size===0?D:w}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${N?"cursor-default":"hover:bg-surface-hover"}`,children:$},c.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(mo,{data:d,xKey:"date",series:R,xTickFormatter:nn,labelFormatter:Ot}),e.jsx("ul",{className:"sr-only",children:d.map(c=>e.jsxs("li",{children:[Ot(c.date),":"," ",R.map(v=>`${v.label} ${M[v.dataKey].formatValue(c[v.dataKey])}`).join(", "),c.origin==="filled"?", no delivery reported":""]},c.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:p.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):p.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:c.name??c.campaignId,children:c.name??e.jsx("span",{className:"font-mono text-secondary",children:c.campaignId})}),e.jsx("td",{children:e.jsx(de,{tone:Wx(c.status),children:Yx(c.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ms.format(c.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ms.format(c.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:xn(c.totals.costMicros,g)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ga.format(c.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Fa(c.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:c.totals.costMicros>0&&c.totals.conversions===0?e.jsx(de,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:xn(c.totals.costPerConversionMicros,g)})})]},c.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Os(ks(b.capturedAt))," · ","customer ",b.customerId," · ","latest closed day ",Ot(b.asOfDate),b.openDate?e.jsxs(e.Fragment,{children:[" · ",Ot(b.openDate)," still open, excluded"]}):null,b.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",b.timeZone]}):null]})]})]})}const _a=20,Ss=50,Zx=50,ep=50;function pr(t){return t==="viewer"}function gr(t){return t?.status==="unavailable"}function Go(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Fo(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 Zn(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 tp(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 Ua(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 Ci(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function ki(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 ea(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 or(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Ba(t){return or(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function lr({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[o,i]=l.useState(""),[u,m]=l.useState(!1),d=o.trim().toLocaleLowerCase(),p=d?t.filter(g=>g.label.toLocaleLowerCase().includes(d)):t,h=u?p:p.slice(0,Zx),j=h.length<p.length;function b(){const g=new Set([...s,...h.map(f=>f.id)]);n(t.filter(f=>g.has(f.id)).map(f=>f.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:o,onChange:g=>i(g.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(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h.length===0,onClick:b,children:"Select all shown"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),p.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 ",h.length," of ",p.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:h.map(g=>{const f=s.includes(g.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 ${g.label}`,checked:f,type:"checkbox",onChange:y=>n(Go(s,g.id,y.currentTarget.checked))}),e.jsx("span",{children:g.label})]}),g.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[g.urlCount," URLs"]})]},g.id)})}),j?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>m(!0),children:"Show all Properties"}):null]})]})}function fr(){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 br({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 sp({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,i]=l.useState(null),u=t.preview,m=u?.counts.needsAttention??0,d=u?.rows.filter(N=>N.status==="matched")??[],p=u?.rows??[],h=p.filter(N=>N.status!=="matched"),j=Math.max(1,Math.ceil(p.length/Ss)),b=Math.min(s,j-1),g=p.slice(b*Ss,(b+1)*Ss),f=Math.max(1,Math.ceil(h.length/Ss)),y=Math.min(a,f-1),C=h.slice(y*Ss,(y+1)*Ss),Q=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,M=d.length>0&&!t.isApplying,R=u!==null&&o===u.previewChecksum,c=h.length>0&&y===f-1;l.useEffect(()=>{n(0),r(0),i(null)},[u?.previewChecksum]);async function v(N){if(N)try{t.onCsvChange(await N.text())}catch{}}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-group-import-title",className:"border-y border-default py-4",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h4",{id:"advanced-measurement-group-import-title",className:"text-sm font-medium text-heading",children:"Import groups from CSV"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Import market membership once instead of selecting the same Properties for every group."})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"CSV file"}),e.jsx("input",{"aria-label":"Group membership CSV file",type:"file",accept:".csv,text/csv",disabled:t.isReviewing||t.isApplying,onChange:N=>{v(N.currentTarget.files?.[0])},className:"mt-1 block min-h-11 w-full text-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary"})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Or paste CSV"}),e.jsx("textarea",{"aria-label":"Group membership CSV",rows:5,value:t.csv,disabled:t.isReviewing||t.isApplying,onChange:N=>t.onCsvChange(N.currentTarget.value),placeholder:`property,group,url
|
|
4
|
+
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(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!Q,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]}),u?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:[u.counts.matchedRows," matched · ",u.counts.groupsReady," group",u.counts.groupsReady===1?"":"s"," ready",m>0?` · ${m} need${m===1?"s":""} attention`:""]}),u.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:u.groupChanges.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:N.label}),e.jsx("td",{className:"text-secondary",children:N.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:N.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[N.addedTargetKeys.length,N.unchangedTargetKeys.length>0?` · ${N.unchangedTargetKeys.length} already members`:""]})]},N.groupKey))})]})}):null,u.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 (",u.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:g.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:N.dataRow}),e.jsx("td",{className:"text-heading",children:N.property}),e.jsx("td",{className:"text-secondary",children:N.group}),e.jsxs("td",{children:[e.jsx(de,{tone:Ci(N.status),children:ki(N.status)}),ea(N)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ea(N)}):null]})]},N.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",b+1," of ",j," · ",u.rows.length," rows"]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===0,onClick:()=>n(N=>Math.max(0,N-1)),children:"Previous 50 rows"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===j-1,onClick:()=>n(N=>Math.min(j-1,N+1)),children:"Next 50 rows"})]})]}):null,m>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 ",m," row",m===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:C.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:N.dataRow}),e.jsx("td",{className:"text-heading",children:N.property}),e.jsx("td",{className:"text-secondary",children:N.group}),e.jsxs("td",{children:[e.jsx(de,{tone:Ci(N.status),children:ki(N.status)}),ea(N)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ea(N)}):null]})]},N.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",y+1," of ",f]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:y===0,onClick:()=>r(N=>Math.max(0,N-1)),children:"Previous 50 exceptions"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:y===f-1,onClick:()=>r(N=>Math.min(f-1,N+1)),children:"Review next 50 exceptions"})]}),e.jsxs("label",{className:"mt-3 flex min-h-11 max-w-xl items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:R,disabled:t.isApplying||!c,onChange:N=>i(N.currentTarget.checked?u.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",m," row",m===1?"":"s"," will be skipped."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!M||!R,onClick:()=>{t.onApply(d.map(N=>N.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${d.length} matched row${d.length===1?"":"s"}`})]}):e.jsx(A,{type:"button",className:"mt-3 min-h-11",disabled:!M,onClick:()=>{t.onApply(d.map(N=>N.dataRow))},children:t.isApplying?"Creating groups…":`Create ${u.counts.groupsReady} group${u.counts.groupsReady===1?"":"s"} with ${d.length} membership${d.length===1?"":"s"}`})]}):null]})}const np="—";function ap({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:o=!1,isBusy:i=!1,canContinue:u=!0,onSelectedQueryIdsChange:m,onApplySelectedQueries:d,onClearQueryAssignments:p,onRemoveQuery:h,onCreateQueries:j,onCreateAndPairQuestions:b,isCreatingQueries:g=!1,createQueriesError:f=null,onManageProjectQueries:y,groups:C,audience:Q,onAudienceChange:M,assignmentImpact:R=null,isPreviewingAssignmentImpact:c=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:N,assignmentNotice:$=null,onReplaceAssignments:D,isReplacingAssignments:w=!1,onBack:U,onContinue:z}){const[B,K]=l.useState(""),[pe,we]=l.useState(!1),[F,te]=l.useState(!1),[ie,Y]=l.useState(""),[H,P]=l.useState(""),[ae,le]=l.useState(null);if(gr(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(br,{message:s.message})});const O=pr(t),W=Q,ue=M,_=Zn(W,n,C),Z=_.length,fe=Z>0&&r.length>0&&!o&&!i&&!c&&R!==null&&v===null,Fe=p??h,Le=B.trim().toLocaleLowerCase(),Ae=Le?a.filter(E=>Ba(E).toLocaleLowerCase().includes(Le)):a,Xe=Ae.filter(E=>(E.propertyIds?.length??0)===0),lt=F?Xe:Ae,Se=pe?lt:lt.slice(0,ep),et=Se.filter(E=>!or(E)),Ve=[...new Set(ie.split(`
|
|
5
|
+
`).map(E=>E.trim()).filter(Boolean))],_e=[...H.matchAll(/\{([a-z][\w-]*)\}/gi)].map(E=>E[1]),Ue=n.filter(E=>_.includes(E.id)),Ie=_e.length===0||H.trim()===""?[]:Ue.map(E=>({propertyId:E.id,text:_e.reduce((he,be)=>he.replaceAll(`{${be}}`,E.label),H.trim())})),G=[...new Set(Ie.map(E=>E.text))];function T(){const E=new Set([...r,...et.map(he=>he.id)]);m(a.filter(he=>E.has(he.id)).map(he=>he.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."})]})}),O?e.jsx(fr,{}):null,O?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:W.kind==="all"?"all":W.kind==="specific"?"specific":`group:${W.groupIds[0]??""}`,onChange:E=>{const he=E.currentTarget.value;he==="all"?ue({kind:"all"}):he==="specific"?ue({kind:"specific",propertyIds:[]}):he.startsWith("group:")&&ue({kind:"groups",groupIds:[he.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]}),C.length>0?e.jsx("optgroup",{label:"Groups",children:C.map(E=>{const he=Zn({kind:"groups",groupIds:[E.id]},n,C).length;return e.jsx("option",{value:`group:${E.id}`,disabled:he===0,children:Ua(E,n)},E.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),W.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:W.groupIds.map(E=>{const he=C.find(be=>be.id===E);return he?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:[Ua(he,n),e.jsx("button",{type:"button","aria-label":`Remove ${he.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 be=W.groupIds.filter(J=>J!==he.id);ue(be.length>0?{kind:"groups",groupIds:be}:{kind:"all"})},children:"×"})]},he.id):null})}),C.some(E=>!W.groupIds.includes(E.id)&&Zn({kind:"groups",groupIds:[E.id]},n,C).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:E=>{E.currentTarget.value&&ue({kind:"groups",groupIds:[...W.groupIds,E.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"}),C.filter(E=>!W.groupIds.includes(E.id)).map(E=>{const he=Zn({kind:"groups",groupIds:[E.id]},n,C).length;return e.jsx("option",{value:E.id,disabled:he===0,children:Ua(E,n)},E.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,W.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(lr,{legend:"Specific Properties",properties:n,selectedPropertyIds:W.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:E=>{ue({kind:"specific",propertyIds:E})}})}):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."})]}),O||!j?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:ie,onChange:E=>Y(E.currentTarget.value),placeholder:`best apartments in dallas
|
|
6
|
+
luxury apartments atlanta
|
|
7
|
+
pet friendly apartments austin`}),f?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:f}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ve.length===0||g||i,onClick:()=>{Promise.resolve(j(Ve)).then(()=>Y(""),()=>{})},children:g?"Adding…":`Add ${Ve.length||""} ${Ve.length===1?"query":"queries"}`.replace(" "," ")}),y?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:y,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:H,onChange:E=>P(E.target.value),placeholder:"apartments near {property}"}),H.trim()===""?null:_e.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."]}):Ue.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:[G.length," ",G.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:G.slice(0,3).map(E=>e.jsx("li",{className:"text-sm text-strong",children:E},E))}),G.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",G.length-3," more"]}):null]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Ie.length===0||g||i||!b,onClick:()=>{b&&Promise.resolve(b(Ie)).then(()=>P(""),()=>{})},children:g?"Adding…":`Add ${Ie.length||""} ${Ie.length===1?"query":"queries"}`.replace(" "," ")}),Ie.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"," ",Ie.length," assignment",Ie.length===1?"":"s","."]}):null]})]})]}),O?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(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:et.length===0,onClick:T,children:"Select all shown queries"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>m([]),children:"Clear query selection"}),e.jsx(A,{type:"button",size:"sm",className:"min-h-11",disabled:!fe,onClick:()=>{d({queryIds:r,propertyIds:_,...W.kind==="groups"?{groupIds:W.groupIds}:{}})},children:o?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${tp(W,C,Z)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[c?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",W.kind==="groups"?` · ${R.resolvedPropertyCount} unique ${R.resolvedPropertyCount===1?"Property":"Properties"}${R.overlapCount>0?`, ${R.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):v?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:v}),N?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:N,children:"Retry impact"}):null,U?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:U,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.jsx("p",{role:"status",className:"text-sm text-secondary",children:$}):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:B,onChange:E=>{K(E.currentTarget.value),we(!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 ",lt.length," queries,"," ",Ae.length-Xe.length," of ",Ae.length," applied"]}),O||Xe.length===0?null:e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{te(E=>!E),we(!1)},children:F?"Show all queries":`Show the ${Xe.length} not applied`})]})]}):null,Se.length>0?e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[O?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),O?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:Se.map(E=>{const he=or(E),be=Ba(E),J=r.includes(E.id),Ze=(E.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[O?null:he?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 ${be}`,checked:J,type:"checkbox",onChange:zt=>m(Go(r,E.id,zt.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:be})}),e.jsx("td",{className:"text-secondary",children:Fo(E.propertyIds??[],n)}),O?null:e.jsx("td",{className:"text-right",children:Ze?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[D?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||w,onClick:()=>le({queryId:E.id,propertyIds:[...E.propertyIds??[]]}),"aria-label":`Replace query assignments for ${be}`,children:"Replace assignments"}):null,e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{Fe(E.id)},"aria-label":`Clear query assignments for ${be}`,children:"Clear assignments"})]}):null})]},E.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,O||!ae?null:(()=>{const E=a.find(J=>J.id===ae.queryId),he=E?Ba(E):"this query",be=ae.propertyIds.filter(J=>n.some(Ze=>Ze.id===J));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 “",he,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(lr,{legend:"Properties for this query",properties:n,selectedPropertyIds:be,onSelectedPropertyIdsChange:J=>le(Ze=>Ze&&{...Ze,propertyIds:[...J]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:w||i,onClick:()=>le(null),children:"Keep current assignments"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:be.length===0||w||i||!D,onClick:()=>{D&&Promise.resolve(D({queryId:ae.queryId,propertyIds:be}))},children:w?"Replacing assignments…":`Replace with ${be.length} ${be.length===1?"Property":"Properties"}`})]})]})})(),Se.length<lt.length?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>we(!0),children:"Show all queries"}):null,O?null:e.jsxs(e.Fragment,{children:[u?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 ${U?"justify-between":"justify-end"}`,children:[U?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:U,children:"Back"}):null,e.jsx(A,{type:"button",variant:fe?"outline":"default",className:"min-h-11",disabled:!u||i,onClick:z,children:"Continue"})]})]})]})}function rp({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:o=!1,onGroupDraftChange:i,onSaveGroup:u,onEditGroup:m,onRemoveGroup:d,onClearGroupDraft:p,membershipImport:h,onBack:j,onContinue:b}){if(gr(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(br,{message:s.message})});const g=pr(t),f=r.name.trim().length>0&&r.propertyIds.length>0&&!o,y=n.filter(R=>r.propertyIds.includes(R.id)).length,C=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,Q=!g&&(m!==void 0||d!==void 0);function M(){if(p){p();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."})]})}),g?e.jsx(fr,{}):null,g||!h?null:e.jsx(sp,{value:h}),g?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:[y," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(lr,{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(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!f,onClick:()=>{u(r)},children:o?"Saving group…":"Save group"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!C,onClick:M,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."})]}),C?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"}),Q?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:Fo(R.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:R.competitors.length>0?R.competitors.join(", "):"None"}),Q?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[m?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${R.name}`,onClick:()=>m(R),children:"Edit"}):null,d?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${R.name}`,onClick:()=>{d(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,g?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${j?"justify-between":"justify-end"}`,children:[j?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",onClick:j,children:"Back"}):null,e.jsx(A,{type:"button",className:"min-h-11",disabled:C,onClick:b,children:a.length===0&&!C?"Continue without groups":"Continue"})]})]})}function ip({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:o,onReviewChanges:i,isReviewing:u=!1,canReviewChanges:m=!0,reviewedChanges:d,reviewChangesError:p,canPublish:h,isPublishing:j=!1,onPublish:b}){const[g,f]=l.useState(_a),[y,C]=l.useState(_a),[Q,M]=l.useState(_a);if(gr(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(br,{message:s.message})});const R=pr(t),c=r?.items??[],v=r?.coverageItems??[],N=c.slice(0,g),$=v.slice(0,y),D=a.slice(0,Q),w=i!==void 0,U=d!=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(fr,{}):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,")"]}),c.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:N.map(z=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:z.url}),e.jsx("p",{className:"mt-1 text-secondary",children:z.reason})]},`${z.url}-${z.reason}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected sitemap URLs before confirming."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",N.length," of ",c.length]}),N.length<c.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>f(z=>z+Ss),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,")"]}),$.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[$.map(z=>e.jsxs("section",{"aria-label":`${z.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:z.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:z.savedUrls.map(B=>e.jsx("li",{className:"break-all text-secondary",children:B},B))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),z.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:z.currentSitemapUrls.map(B=>e.jsx("li",{className:"break-all text-secondary",children:B},B))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},z.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",$.length," of ",v.length]}),$.length<v.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>C(z=>z+Ss),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(A,{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??np})]})})]})}),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,d?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:d.title}),d.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:d.items.map((z,B)=>e.jsx("li",{children:z},`${z}-${B}`))}):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(z=>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:z.title}),z.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:z.detail}):null]}),e.jsx(de,{tone:z.tone??"caution",children:"Needs attention"})]},z.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(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>M(z=>z+Ss),children:"Show next 50 exceptions"}):null]})]})]}),R?null:e.jsxs(e.Fragment,{children:[w&&p?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:p}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${o?"justify-between":"justify-end"}`,children:[o?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",onClick:o,children:"Back"}):null,i!==void 0&&!U?e.jsx(A,{type:"button",className:"min-h-11",disabled:u||!m,onClick:()=>{i()},children:u?"Reviewing changes…":"Review changes"}):e.jsx(A,{type:"button",className:"min-h-11",disabled:!h||j,onClick:()=>{b()},children:j?"Publishing setup…":"Publish setup"})]})]})]})}const op={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function lp(t){return t.trim().toLocaleLowerCase()}function cp(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function dp({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 up({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 u(m,d){n({...s,[m]:d})}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:m=>{m.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:m=>u("sitemapUrl",m.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:m=>u("examplePropertyUrl",m.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:m=>u("preferredHost",m.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:m=>u("propertyPathPattern",m.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:m=>u("additionalHost",m.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:m=>u("additionalPathPattern",m.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:m=>u("excludedPaths",m.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(A,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function mp({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:o,onSelectedPropertyIdsChange:i,onContinue:u,isContinuing:m=!1,onRetryProperties:d,onReturnToImport:p,maxVisibleProperties:h,onShowAllProperties:j}){const b=lp(a),g=s.filter(D=>cp(D,b)),f=Math.max(1,h??g.length),y=g.slice(0,f),C=new Set(o),Q=s.filter(D=>C.has(D.id)).map(D=>D.id),M=y.length<g.length;function R(D){const w=new Set(D);i(s.filter(U=>w.has(U.id)).map(U=>U.id))}function c(D,w){if(!t||m)return;const U=new Set(Q);w?U.add(D):U.delete(D),R(U)}function v(){!t||m||R([...Q,...y.map(D=>D.id)])}function N(){!t||m||i([])}function $(){!t||m||Q.length===0||u(Q)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||m,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(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:d,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(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:d,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(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:p,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:m,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(A,{type:"button",variant:"outline",size:"sm",disabled:m,onClick:v,children:"Select all shown"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:m||Q.length===0,onClick:N,children:"Clear selection"})]}):null]}),g.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(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:p,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",y.length," of ",g.length," Properties"]}),e.jsxs("p",{children:[Q.length," of ",s.length," selected"]})]}),e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"w-full min-w-150 text-left text-sm","aria-label":"Properties to review",children:[e.jsx("thead",{className:"bg-surface-subtle text-xs font-medium uppercase tracking-wide text-secondary",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-3 py-2",children:"Property"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"URL"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"State"}),t?e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Include"}):null]})}),e.jsx("tbody",{children:y.map(D=>{const w=op[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(dp,{property:D})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(de,{tone:w.tone,children:w.label})}),t?e.jsx("td",{className:"p-0 text-right",children:e.jsx("label",{className:"ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{type:"checkbox","aria-label":`Select ${D.name}`,checked:Q.includes(D.id),disabled:m,onChange:U=>c(D.id,U.target.checked),className:"size-6 accent-accent"})})}):null]},D.id)})})]})}),M&&j?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:m,onClick:j,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(A,{type:"button",variant:"ghost",disabled:m,onClick:p,children:"Back"}),e.jsx(A,{type:"button",disabled:m||Q.length===0,onClick:$,children:m?"Saving Properties…":"Continue"})]}):null]}):null]})}function hp(t){return t.activeStep==="import"?e.jsx(up,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(mp,{...t})}const xp=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function pp({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:o}){const i=l.useRef(null),u=l.useRef(null),m=l.useRef(null),d=l.useRef(null),p=l.useRef(!1),[h,j]=l.useState(!1);return l.useEffect(()=>{s||j(!1)},[s]),l.useEffect(()=>{const b=p.current;p.current=h,h?m.current?.focus():b&&d.current?.focus()},[h]),l.useEffect(()=>{const b=i.current;if(i.current=t,b===null||b===t)return;const g=u.current?.querySelector('h1, h2, h3, [role="heading"]');g&&(g.tabIndex=-1,g.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?h?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(A,{ref:m,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>j(!1),children:"Keep editing"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(A,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>j(!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:xp.map(b=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===b.id?"step":void 0,onClick:()=>r(b.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===b.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:b.label}):e.jsx("span",{"aria-current":t===b.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===b.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:b.label})},b.id))})}),e.jsx("div",{ref:u,children:o})]})}function gp(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(hp,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(ap,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(rp,{...t.groups,access:s}):"review"in t?e.jsx(ip,{...t.review,access:s}):null}function ta(t){return e.jsx(pp,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:gp(t)})}function _o(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Dt(t){return{"If-Match":t,"Idempotency-Key":_o()}}function zs(t){return t instanceof sn&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function es(t,s){return t instanceof sn?s:(t instanceof Error?t.message.trim():"")||s}function fp(t){const s="Could not calculate assignment impact.";if(!(t instanceof sn)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const bp={loadSetup:t=>ot(()=>id({client:V,path:{name:t}})),loadDraft:t=>ot(()=>rd({client:V,path:{name:t}})),createDraft:(t,s)=>ot(()=>ad({client:V,path:{name:t},headers:{"Idempotency-Key":_o()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>ot(()=>nd({client:V,path:{name:t},headers:Dt(s),body:n})),applySitemapSelection:(t,s,n,a)=>ot(()=>sd({client:V,path:{name:t},headers:Dt(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>ot(()=>td({client:V,path:{name:t},body:s})),applyAssignments:(t,s,n)=>ot(()=>ed({client:V,path:{name:t},headers:Dt(s),body:n})),replaceAssignments:(t,s,n)=>ot(()=>Zc({client:V,path:{name:t},headers:Dt(s),body:n})),applyPairedAssignments:(t,s,n)=>ot(()=>Xc({client:V,path:{name:t},headers:Dt(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>ot(()=>Jc({client:V,path:{name:t},headers:Dt(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>ot(()=>Yc({client:V,path:{name:t},headers:Dt(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>ot(()=>Wc({client:V,path:{name:t},headers:Dt(s),body:{target:n}})),upsertGroup:(t,s,n)=>ot(()=>Hc({client:V,path:{name:t},headers:Dt(s),body:{group:n}})),removeGroup:(t,s,n)=>ot(()=>Qc({client:V,path:{name:t},headers:Dt(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>ot(()=>zc({client:V,path:{name:t},headers:Dt(s),body:n})),removeCompetitor:(t,s,n,a)=>ot(()=>Kc({client:V,path:{name:t},headers:Dt(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>ot(()=>Vc({client:V,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>ot(()=>Bc({client:V,path:{name:t},headers:Dt(s),body:n})),compilePreview:t=>ot(()=>Uc({client:V,path:{name:t}})),diffPreview:t=>ot(()=>_c({client:V,path:{name:t}})),publish:(t,s,n)=>ot(()=>Fc({client:V,path:{name:t},headers:Dt(s),body:n})),discard:(t,s)=>ot(()=>Gc({client:V,path:{name:t},headers:Dt(s)}))},Ai={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},kn={name:"",propertyIds:[],competitorDomains:""},Pi=50;function Rn(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function yp(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 Ri(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 vp(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,u=i.startsWith("*"),m=i.endsWith("*"),d=i.slice(u?1:0,m?-1:void 0).trim();if(!d)throw new Error("Ignored URL patterns must include text besides *.");const p=u&&m?"contains":u?"suffix":m?"prefix":"exact",h=`${p}:${d}`;n.has(h)||(n.add(h),s.push({kind:p,value:d}))}return s}function jp(t){const s=yp(t.sitemapUrl),n=t.examplePropertyUrl.trim()?Rn(t.examplePropertyUrl):null,a=Rn(t.preferredHost)??n??Rn(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=Rn(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 u=vp(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:Ri(t)},...r?{aliases:[{host:r,pathTemplate:Ri({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...u.length>0?{excludedSlugPatterns:u}:{}}}}function Np(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 wp(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 Ii(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function Sp(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Va(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function cr(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function Ti(t){return Rn(t)}function Uo(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 Bo(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 Vo(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Ko(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Cp(t,s){const n=Uo(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 kp(t,s){const n=Bo(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=Ko(t.authoring,n.targetKeys[r]);return`${n.label} — ${o}`}return n.label}function Ap(t,s){const n=Vo(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${Ko(t.authoring,n.targetKey)} — ${a}`}function Pp(t,s){return s.path[0]==="identities"?"Project domain":Cp(t,s)??kp(t,s)??Ap(t,s)}function $i(t,s,n){const a=Vo(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 Rp(t,s){const n=Pp(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,$i(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,$i(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 sa(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function zo(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 Ip(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${sa(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${sa(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${sa(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${sa(n,"item")} need review.`:s}})()}${zo(a)}`}function Tp(t,s){const n=new Map;for(const a of t){const r=Rp(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:Ip(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function Ka(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function za(t,s,n){const a=Uo(n,t.path),r=Bo(n,t.path),o=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=o?n?.targets.find(p=>p.stableKey===o):void 0,u=a?.label??r?.label,m=zo(u?[u]:[]),d={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...d,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${m}`};case"excluded-target-has-assignments":return{...d,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${m}`};case"group-unknown-target":return{...d,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${m}`};case"measurement.discovery.proposed_new_target":{const p=Ka(a)??"the proposed Property";return{...d,title:"Review a new Property",detail:`Review ${p}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const p=Ka(a)??"the proposed Property",h=i?.label??"an existing Property";return{...d,title:"Review a moved Property",detail:`Review ${p}. It may be the same Property as ${h}.`}}case"measurement.discovery.rebind_ambiguous":{const p=Ka(a)??"the proposed Property",h=i?.label??"an existing Property";return{...d,title:"Choose an existing Property",detail:`Review ${p}. It may match ${h}; choose the correct Property.`}}default:return{...d,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function $p(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 fs(t){return[...new Set(t)]}function qs(t){return fs(t).sort()}function Mp(t,s,n){return t.kind==="groups"?{groupKeys:qs(t.groupIds),queryIds:qs(n)}:{targetKeys:qs(t.kind==="all"?s:t.propertyIds),queryIds:qs(n)}}function Lp(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 Mi(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function Dp(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(Mi).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(Mi).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:cr(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function Ep({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:o,canEdit:i=!0,onCreateQueries:u,onManageProjectQueries:m,onPublished:d,service:p=bp}){const[h,j]=l.useState(null),[b,g]=l.useState(null),[f,y]=l.useState("import"),[C,Q]=l.useState(!0),[M,R]=l.useState(null),[c,v]=l.useState(null),[N,$]=l.useState([]),[D,w]=l.useState({...Ai}),[U,z]=l.useState("idle"),[B,K]=l.useState(""),[pe,we]=l.useState(Pi),[F,te]=l.useState([]),[ie,Y]=l.useState([]),[H,P]=l.useState({kind:"all"}),[ae,le]=l.useState(null),[O,W]=l.useState(null),[ue,_]=l.useState(!1),[Z,fe]=l.useState(null),[Fe,Le]=l.useState(0),[Ae,Xe]=l.useState(null),[lt,Se]=l.useState({...kn}),[et,Ve]=l.useState(null),[_e,Ue]=l.useState(""),[Ie,G]=l.useState(null),[T,E]=l.useState(!1),[he,be]=l.useState(!1),[J,Ze]=l.useState(null),[zt,Ye]=l.useState(null),[Te,$e]=l.useState(null),[pt,ct]=l.useState(null),[Oe,Qe]=l.useState(null),vt=l.useRef(0),Ke=l.useRef(0),Ee=b?.draft??null,qe=b?.etag??null,jt=l.useMemo(()=>!i&&o?{baseActiveRevision:o.revision,authoring:Dp(o)}:null,[i,o]),Ge=Ee??jt;async function It(I){const X=++vt.current;Q(!0),R(null);try{let[ge,se]=await Promise.all([p.loadSetup(t),p.loadDraft(t)]);if(!se.draft&&I&&i&&(await p.createDraft(t,ge.activeRevision),[ge,se]=await Promise.all([p.loadSetup(t),p.loadDraft(t)])),X!==vt.current)return;j(ge),g(se),y(Np(se.draft));const re=Va(se.draft);te(re)}catch(ge){if(X!==vt.current)return;R(es(ge,"Could not load advanced measurement setup."))}finally{X===vt.current&&Q(!1)}}l.useEffect(()=>(It(!0),()=>{vt.current+=1}),[t,i,p]),l.useEffect(()=>{!C&&!Ee&&jt&&y("properties")},[Ee,C,jt]);async function Gt(){const I=await p.loadDraft(t);return g(I),I}async function gt(I){Qe(null);try{const[X,ge]=await Promise.all([p.loadSetup(t),p.loadDraft(t)]);j(X),g(ge);const se=Va(ge.draft);te(se),y(re=>wp(ge.draft,re)),v(I)}catch(X){v(es(X,I))}}async function kt(I,X,ge,se={}){const{preserveBusyAction:re=!1}=se;if(!i||!qe||Te&&!re)return null;re||$e(I),v(null),Qe(null);try{const Me=await X(qe),Tt=await Gt();return $((Me.warnings??[]).map((ut,Ps)=>za(ut,Ps,Tt.draft?.authoring))),Tt}catch(Me){return zs(Me)?await gt("This setup changed in another session. The latest draft is loaded; review your changes again."):v(es(Me,ge)),null}finally{re||$e(null)}}const ht=l.useMemo(()=>(Ge?.authoring.targets??[]).map(I=>{const X=Ii(I);return{id:I.stableKey,name:I.label,url:X[0]??"No URL",urls:X,state:Sp(I.status)}}),[Ge]),q=l.useMemo(()=>Ge?.authoring.targets.filter(I=>I.status==="included")??[],[Ge]),Ce=l.useMemo(()=>q.map(I=>({id:I.stableKey,label:I.label,urlCount:Ii(I).length})),[q]),ye=Ge?.authoring.assignments.length??0,je=l.useMemo(()=>{if(!Ge)return[];const I=new Set(s.map(se=>se.id)),X=s.map(se=>({id:se.id,text:se.query,source:"saved-project-queries",propertyIds:fs(Ge.authoring.assignments.filter(re=>re.queryId===se.id).map(re=>re.targetKey))})),ge=fs(Ge.authoring.assignments.map(se=>se.queryId).filter(se=>!I.has(se))).map(se=>({id:se,source:"unavailable-tracked-query",state:"missing",propertyIds:fs(Ge.authoring.assignments.filter(re=>re.queryId===se).map(re=>re.targetKey))}));return[...X,...ge]},[s,Ge]),ft=l.useMemo(()=>(Ge?.authoring.groups??[]).map(I=>({id:I.stableKey,name:I.label,propertyIds:I.targetKeys,competitors:I.competitors.map(X=>X.domain)})),[Ge]),Je=l.useMemo(()=>{if(ie.length===0)return null;const I=Mp(H,Ce.map(ge=>ge.id),ie);return(I.groupKeys?.length??I.targetKeys?.length??0)>0?I:null},[H,Ce,ie]),At=Je?JSON.stringify(Je):"";l.useEffect(()=>{const I=Je,X=++Ke.current;if(!i||!Ee||!qe||!I){le(null),W(null),fe(null),_(!1);return}le(null),W(null),fe(null),_(!0);const ge=window.setTimeout(()=>{p.previewAssignments(t,I).then(se=>{if(X===Ke.current){if(se.draftEtag!==qe){le(null),W(null),fe("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}le(se),W(At)}}).catch(se=>{X===Ke.current&&(le(null),W(null),fe(fp(se)))}).finally(()=>{X===Ke.current&&_(!1)})},250);return()=>{window.clearTimeout(ge),Ke.current+=1}},[Je,At,Fe,i,Ee,qe,t,p]);const Nt=l.useMemo(()=>[...ye===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"}]:[],...Ge?.authoring.assignments.some(I=>I.queryClass==="unclassified")&&!(jt&&o?.plan.schemaVersion===1)?[{id:"unclassified-query-assignments",title:"Remove an unavailable query",detail:"One or more saved assignments no longer have a tracked query. Clear them before publishing.",tone:"negative"}]:[],...N],[ye,jt,o,N,Ge]),rs=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 is(I){let X;try{X=jp(I)}catch(se){v(es(se,"Check the sitemap details and try again."));return}w(I),z("reviewing");const ge=await kt("import",se=>p.importSitemap(t,se,X),"Could not review this sitemap.");if(ge?.draft){const se=ge.draft.authoring.targets.filter(Me=>Me.status==="proposed").map(Me=>Me.stableKey),re=ge.draft.authoring.targets.filter(Me=>Me.status==="included").map(Me=>Me.stableKey);te([...re,...se]),K(""),we(Pi),y("properties"),z("idle")}else z("error")}async function ds(I){if(!u||I.length===0||Te)return[];$e("create-queries"),ct(null);try{return await u(I)}catch(X){throw ct(mt(X)),X}finally{$e(null)}}async function rt(I){if(!Ee||!qe||Te)return;const X=new Set(I),se=Ee.authoring.targets.filter(Me=>Me.status==="proposed"&&Me.discoveryIdentity).map(Me=>({discoveryIdentity:Me.discoveryIdentity,action:X.has(Me.stableKey)?"create":"ignore"})),re=se.length>0||Ee.authoring.targets.some(Me=>Me.status!=="proposed"&&Me.status==="included"!==X.has(Me.stableKey));$e("properties"),v(null),Qe(null);try{if(!re){te([...X]),P({kind:"all"}),y("groups");return}await p.applySitemapSelection(t,qe,se,[...X]);const Me=await Gt(),Tt=Va(Me.draft);te(Tt),P({kind:"all"}),y("groups")}catch(Me){zs(Me)?await gt("This setup changed in another session. The latest Properties are loaded."):v(es(Me,"Could not save the selected Properties."))}finally{$e(null)}}async function us(I){const X=I.groupIds&&I.groupIds.length>0?{groupKeys:qs(I.groupIds),queryIds:qs(I.queryIds)}:{targetKeys:qs(I.propertyIds),queryIds:qs(I.queryIds)};if(!ae||O!==JSON.stringify(X)||!qe||ae.draftEtag!==qe){v("Review the latest assignment impact before assigning queries.");return}await kt("assignments",se=>p.applyAssignments(t,se,X),"Could not apply these queries.")&&(Y([]),Xe(`${ae.assignments.added} new assignment${ae.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function dt(I){if(I.propertyIds.length===0)return;await kt("replace-assignments",ge=>p.replaceAssignments(t,ge,{targetKeys:fs(I.propertyIds),queryIds:[I.queryId]}),"Could not replace this query assignment.")&&(Y(ge=>ge.filter(se=>se!==I.queryId)),Xe("Query assignments replaced."))}async function ys(I,X=!1){if(I.length===0)return;if(!await kt("paired-assignments",se=>p.applyPairedAssignments(t,se,[...I]),"Could not assign these queries.",{preserveBusyAction:X}))throw new Error("Could not assign these queries.")}async function Wt(I){if(!(!i||!u||I.length===0||Te)){$e("create-and-pair-questions"),ct(null);try{let X;try{X=await u(fs(I.map(re=>re.text)))}catch(re){throw ct(mt(re)),re}const ge=new Map(X.map(re=>[re.query,re.id])),se=I.map(re=>({targetKey:re.propertyId,queryId:ge.get(re.text)})).filter(re=>re.queryId!==void 0);if(se.length!==I.length){const re=new Error("The created queries could not be matched to their Properties.");throw ct("The queries were added, but could not be paired with every Property. Try again to pair them."),re}try{await ys(se,!0)}catch(re){throw ct("The queries were added, but could not be assigned to their Properties. Try again to pair them."),re}}finally{$e(null)}}}async function Ft(I){if(!Ee)return;const X=fs(Ee.authoring.assignments.filter(se=>se.queryId===I).map(se=>se.targetKey));if(X.length===0)return;await kt(`remove-${I}`,se=>p.removeAssignment(t,se,X,I),"Could not clear this query assignment.")&&Y(se=>se.filter(re=>re!==I))}async function Yt(I){if(!Ee||!qe||Te)return;const X=I.name.trim();if(!X)return;const ge=et??cr(X,"group"),se=Ee.authoring.groups.find(ut=>ut.stableKey===ge);if(se&&et===null){v(`A group named "${se.label}" already exists. Edit it or choose a different name.`);return}const re=I.competitorDomains.split(/[\s,]+/).map(ut=>ut.trim()).filter(Boolean),Me=re.find(ut=>Ti(ut)===null);if(Me){v(`"${Me}" is not a valid competitor domain.`);return}const Tt=fs(re.map(ut=>Ti(ut)));$e("group"),v(null),Qe(null);try{const ut=await p.upsertGroup(t,qe,{stableKey:ge,label:X,targetKeys:fs(I.propertyIds),competitors:Tt.map(S=>se?.competitors.find(oe=>oe.domain===S)??{stableKey:cr(S,"competitor"),label:S,domain:S,aliases:[]})}),Ps=await Gt();$(ut.warnings.map((S,oe)=>za(S,oe,Ps.draft?.authoring))),Se({...kn}),Ve(null)}catch(ut){zs(ut)?await gt("This setup changed in another session. The latest groups are loaded."):v(es(ut,"Could not save this group."))}finally{$e(null)}}function wt(I){const X=Ee?.authoring.groups.find(ge=>ge.stableKey===I);X&&(Ve(I),Se({name:X.label,propertyIds:[...X.targetKeys],competitorDomains:X.competitors.map(ge=>ge.domain).join(", ")}))}async function ms(I){await kt("remove-group",ge=>p.removeGroup(t,ge,I),"Could not remove this group.")&&(P(ge=>ge.kind==="groups"&&ge.groupIds.includes(I)?{kind:"all"}:ge),et===I&&(Ve(null),Se({...kn})))}function Qt(I){Ue(I),G(null),Ze(null),Ye(null)}async function bt(){if(!(!i||!_e.trim()||T||he)){E(!0),Ze(null),Ye(null);try{G(await p.previewGroupMembership(t,{csv:_e}))}catch(I){G(null),Ze(es(I,"Could not review this CSV."))}finally{E(!1)}}}async function vs(I){if(!(!i||!qe||!Ie||I.length===0||Te)){if(Ie.draftEtag!==qe){Ze("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}be(!0),$e("group-import"),Ze(null),Ye(null),Qe(null);try{const X=await p.applyGroupMembership(t,qe,{csv:_e,sourceChecksum:Ie.sourceChecksum,previewChecksum:Ie.previewChecksum,acceptedRows:fs(I.map(String)).map(Number)}),ge=await Gt();$(X.warnings.map((se,re)=>za(se,re,ge.draft?.authoring))),Ue(""),G(null),Ye(`${X.addedMemberships} membership${X.addedMemberships===1?"":"s"} added${X.unchangedMemberships>0?`; ${X.unchangedMemberships} already present`:""}.`)}catch(X){zs(X)?(await gt("This setup changed in another session. The latest draft is loaded; review the CSV again."),Ze("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Ze(es(X,"Could not apply this CSV."))}finally{$e(null),be(!1)}}}async function Pt(){if(!(!Ee||!qe||Te||ye===0)){$e("review"),v(null),Qe(null);try{const[I,X]=await Promise.all([p.compilePreview(t),p.diffPreview(t)]),ge=[...I.checks,...X.checks],se=ge.some(re=>re.ruleId==="active-revision-schema-v1");if($(Tp(ge.filter(re=>re.ruleId!=="active-revision-schema-v1"),{authoring:Ge?.authoring,queries:s})),!I.ok||!X.ok)return;if(X.diff.activeRevision!==Ee.baseActiveRevision){await gt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(I.compiledChecksum!==X.compiledChecksum){v("The setup changed while it was being reviewed. Review the latest changes again.");return}Qe({etag:qe,baseActiveRevision:Ee.baseActiveRevision,compiledChecksum:I.compiledChecksum,changes:$p(X.diff,se),providerCalls:I.plan.executionNodes.reduce((re,Me)=>re+Me.expectedSnapshots,0)})}catch(I){v(es(I,"Could not review this setup."))}finally{$e(null)}}}async function hs(){if(!(!Ee||!qe||!Oe||Te)){if(qe!==Oe.etag||Ee.baseActiveRevision!==Oe.baseActiveRevision){Qe(null),v("The setup changed after review. Review the latest changes before publishing.");return}$e("publish"),v(null);try{await p.publish(t,qe,{expectedActiveRevision:Oe.baseActiveRevision,expectedCompiledChecksum:Oe.compiledChecksum}),g({draft:null,etag:null}),Qe(null),d?.()}catch(I){zs(I)?await gt("The setup changed before it could be published. Review the latest draft and publish again."):v(es(I,"Could not publish this setup."))}finally{$e(null)}}}async function xs(){if(!(!qe||Te)){$e("discard"),v(null);try{await p.discard(t,qe),g({draft:null,etag:null}),Qe(null),d?.()}catch(I){zs(I)?await gt("This setup changed in another session. The latest draft is loaded."):v(es(I,"Could not discard these changes."))}finally{$e(null)}}}async function ps(){if(!(!Ee||!qe||!h||Te)){$e("restart"),v(null),Qe(null);try{await p.discard(t,qe),await p.createDraft(t,h.activeRevision),w({...Ai}),K(""),te([]),Y([]),P({kind:"all"}),le(null),fe(null),Xe(null),Se({...kn}),Ve(null),Ue(""),G(null),Ze(null),Ye(null),await It(!1)}catch(I){zs(I)?await gt("The setup changed again. Reloaded the latest draft and published setup."):v(es(I,"Could not restart this setup."))}finally{$e(null)}}}if(C)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(M)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:M}),e.jsx(A,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{It(!0)},children:"Try again"})]})]});if(!Ge||i&&!qe)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&&h&&Ee.baseActiveRevision!==h.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(A,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:Te==="restart",onClick:()=>{ps()},children:Te==="restart"?"Restarting…":"Discard draft and restart"})]}),c?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:c}):null]});const St=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(A,{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:[h?.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,c?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:c}):null,St,f==="import"||f==="properties"?e.jsx(ta,{currentStep:f,hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{xs()},importProperties:{importDraft:D,onImportDraftChange:I=>{w(I),z("idle"),v(null)},onReviewSitemap:I=>{is(I)},reviewState:U,properties:ht,propertiesState:"ready",propertiesSearch:B,onPropertiesSearchChange:K,maxVisibleProperties:pe,onShowAllProperties:()=>we(ht.length),selectedPropertyIds:F,onSelectedPropertyIdsChange:I=>te([...I]),onContinue:I=>{rt(I)},isContinuing:Te==="properties",onRetryProperties:()=>{Gt()},onReturnToImport:()=>y("import")}}):f==="queries"?e.jsx(ta,{currentStep:"queries",hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{xs()},onManageProjectQueries:m,queries:{onCreateQueries:u?I=>ds(I):void 0,isCreatingQueries:Te==="create-queries"||Te==="create-and-pair-questions",isBusy:Te!==null,createQueriesError:pt,availability:rs,properties:Ce,queries:je,selectedQueryIds:ie,isApplying:Te==="assignments"||Te==="paired-assignments",onSelectedQueryIdsChange:I=>Y([...I]),onApplySelectedQueries:I=>us(I),groups:ft,audience:H,onAudienceChange:I=>{P(I),Xe(null)},assignmentImpact:ae&&O===At?Lp(ae):null,isPreviewingAssignmentImpact:ue,assignmentImpactError:Z,onRetryAssignmentImpact:()=>Le(I=>I+1),assignmentNotice:Ae,onReplaceAssignments:dt,isReplacingAssignments:Te==="replace-assignments",onCreateAndPairQuestions:i&&u?Wt:void 0,onClearQueryAssignments:Ft,onRemoveQuery:Ft,canContinue:ye>0,onBack:()=>y("groups"),onContinue:()=>y("review")}}):f==="groups"?e.jsx(ta,{currentStep:"groups",hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{xs()},groups:{properties:Ce,groups:ft,groupDraft:lt,isSaving:Te==="group",onGroupDraftChange:Se,onSaveGroup:Yt,onEditGroup:I=>wt(I.id),onRemoveGroup:ms,onClearGroupDraft:()=>{Ve(null),Se({...kn})},membershipImport:{csv:_e,preview:Ie,isReviewing:T,isApplying:he,error:J,notice:zt,onCsvChange:Qt,onReview:bt,onApply:vs},onBack:()=>{y("properties")},onContinue:()=>y("queries")}}):e.jsx(ta,{currentStep:"review",hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{xs()},review:{counts:{properties:q.length,queries:new Set(Ge.authoring.assignments.map(I=>I.queryId)).size,groups:Ge.authoring.groups.length,assignments:Ge.authoring.assignments.length,providerCalls:Oe?.providerCalls},flaggedExceptions:Nt,reviewedChanges:Oe?.changes,isReviewing:Te==="review",canReviewChanges:ye>0&&!Te,onReviewChanges:Pt,onBack:()=>y("queries"),canPublish:Oe!==null&&!Te,isPublishing:Te==="publish",onPublish:hs}})]})}const qp=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function Li(t){return t.label!=="Complete"}const Qs="__all_properties__",Op=50,Qo=50,Gp=20,Fp=50,_p=250,Up=5,Bp=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Vp={"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"},Ho={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."},Kp={numerator:null,denominator:null,reason:"plan_v1"};function $n(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 zp(t){return $n(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function Wo(t){if($n(t))return"";const s=t.reason??"unavailable";return Ho[s]??s}function Di(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 Qp(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function Hp(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function Wp(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function In({metric:t,compact:s=!1}){const n=s?$n(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":$n(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",...$n(t)?{}:{title:Wo(t)},children:e.jsx("span",{className:n,children:zp(t)})})}function yr({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(A,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Ei({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,o]=l.useState(Qo),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((u,m)=>e.jsx("li",{className:a,children:u},`${u}:${m}`))}),e.jsx(yr,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>o(Number.MAX_SAFE_INTEGER)})]})]})}function Yp({evidence:t,state:s="ready",onRetry:n}){const[a,r]=l.useState(Qo),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(A,{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:Vp[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(yr,{shown:o.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function Jp({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Ei,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Ei,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(Yp,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function Xp({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(In,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function qi({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function o(i){if(r)return;const u=n.findIndex(p=>p.value===s);let m=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?m=(u+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?m=(u-1+n.length)%n.length:i.key==="Home"?m=0:i.key==="End"&&(m=n.length-1),m===null)return;i.preventDefault();const d=n[m];a(d.value),i.currentTarget.querySelectorAll('[role="radio"]')[m].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:o,children:n.map(i=>{const u=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":u,tabIndex:u?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${u?"segmented-option-active":""}`,children:i.label},i.value)})})}function Zp({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(ze,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function eg({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:o=!1,isViewLoading:i=!1,isLoadingMore:u=!1,isLoadMoreError:m=!1,viewSearch:d,onViewChange:p,onLoadMore:h,onPropertyExpand:j,onRetryEvidence:b,renderPropertyLink:g}){const f=t.currentView!=null,y=t.classReporting==="available"&&(f||t.classScopes!=null),[C,Q]=l.useState(t.currentView?.queryClass??"all"),[M,R]=l.useState(t.currentView?.scope.key??Qs),[c,v]=l.useState(d??""),[N,$]=l.useState(Op),[D,w]=l.useState(Gp),[U,z]=l.useState(t.currentView?.sort??"label-asc"),[B,K]=l.useState(null),pe=l.useRef(d??""),we=y&&!f&&C!=="all"?C==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,F=f?{aggregate:t.currentView.aggregate,groups:[]}:we,te=l.useCallback(G=>{if(!f||!p)return;const T=G.scope??(M===Qs?"all":"group"),E=G.search??c;pe.current=E,p({scope:T,...T==="group"?{groupKey:G.groupKey??M}:{},queryClass:G.queryClass??C,...E?{search:E}:{},...G.sort?{sort:G.sort}:{}})},[p,c,C,M,f]);l.useEffect(()=>{!t.currentView||i||(Q(t.currentView.queryClass),R(t.currentView.scope.key??Qs),t.currentView.sort&&z(t.currentView.sort))},[i,t.currentView]),l.useEffect(()=>{d!==void 0&&(pe.current=d,v(G=>G.trim()===d.trim()?G:d))},[d]),l.useEffect(()=>{if(!f||!p||c===pe.current)return;const G=window.setTimeout(()=>te({search:c}),_p);return()=>window.clearTimeout(G)},[p,te,c,f]);const ie=t.availableGroups??F.groups;l.useEffect(()=>{M===Qs||ie.some(G=>G.id===M)||R(Qs)},[ie,M]);const Y=f?void 0:F.groups.find(G=>G.id===M),H=Y?.aggregate??F.aggregate,P=G=>y?G:Kp,ae=U,le=c.trim().toLocaleLowerCase(),O=l.useMemo(()=>!f&&le?H.properties.filter(G=>G.name.toLocaleLowerCase().includes(le)):H.properties,[H.properties,le,f]),W=f?O:O.slice(0,N),ue=(f?t.currentView?.scope.kind==="group":Y!=null)&&C==="non-brand"&&y&&(f||Y.confirmedCompetitorCount>0)&&(H.shareOfVoice?.length??0)>0,_=y?H.unavailablePropertyCount??0:0,Z=t.flaggedResults.reduce((G,T)=>G+(T.count??1),0),fe=t.flaggedResultsTotal??Z,Fe=[P(H.metrics.propertiesMentioned),P(H.metrics.mentionCoverage),P(H.metrics.citationCoverage)].map(Wo).find(Boolean),Le=y?t.nextActionText??Fe??(_>0?`${_} ${_===1?"property is":"properties are"} unavailable.`:fe>0?`${fe} flagged ${fe===1?"result needs":"results need"} review.`:null):Ho.plan_v1,lt=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?Qp(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Se=Hp(t.latestMeasurement.date),et=[{value:Qs,label:"All properties"},...ie.map(G=>({value:G.id,label:G.label}))],Ve=ie.length>Up;function _e(G){R(G),te(G===Qs?{scope:"all"}:{scope:"group",groupKey:G})}function Ue(G){Q(G),te({queryClass:G})}function Ie(G){const T=B!==G;K(T?G:null),T&&j?.(G)}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,lt?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:lt}):null,Se?e.jsx("span",{className:"text-sm text-secondary",children:Se}):null,Le?e.jsx("span",{className:"text-sm text-secondary",children:Le}):null,s&&y&&n?e.jsx(A,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!y?e.jsx(A,{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:Ve?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),Ve?e.jsx("select",{id:"advanced-measurement-group",value:M,onChange:G=>_e(G.target.value),className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-mono-400",children:et.map(G=>e.jsx("option",{value:G.value,children:G.label},G.value))}):e.jsx(qi,{ariaLabelledBy:"advanced-measurement-group-label",value:M,options:et,onChange:_e})]}),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(qi,{ariaLabelledBy:"advanced-measurement-class-label",value:C,options:Bp,onChange:Ue,disabled:!y})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:c,onChange:G=>v(G.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&&ue?e.jsx(Xp,{values:H.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(ze,{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??O.length," ",(t.currentView?.propertyTotal??O.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(Zp,{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:[qp.map(G=>{const T=ae.startsWith(`${G.key}-`),E=T&&ae.endsWith("-desc")?"descending":T?"ascending":"none";return e.jsx("th",{"aria-sort":E,className:(G.numeric,void 0),children:p?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const he=`${G.key}-${T&&ae.endsWith("-asc")?"desc":"asc"}`;z(he),te({sort:he})},"aria-label":`Sort by ${G.label.toLowerCase()}`,children:[G.label,e.jsx(Ln,{className:`h-3 w-3 transition-transform ${T?"opacity-100":"opacity-0"} ${E==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):G.label},G.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[W.map(G=>{const T=B===G.id;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:E=>{Wp(E.target)||Ie(G.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[g?g({id:G.id,name:G.name}):G.name,Li(G.status)||G.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[Li(G.status)?e.jsx(de,{tone:G.status.tone,children:G.status.label}):null,G.historical?e.jsx(de,{tone:"caution",children:"Historical"}):null]}):null,Di(G)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Di(G)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(In,{metric:G.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(In,{metric:G.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{size:"icon",variant:"ghost","aria-expanded":T,"aria-label":T?`Hide details for ${G.name}`:`Show details for ${G.name}`,onClick:()=>Ie(G.id),children:e.jsx(Ln,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${T?"rotate-180":""}`,"aria-hidden":"true"})})})]},G.id),T?(G.providers??[]).map(E=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:E.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(In,{metric:E.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(In,{metric:E.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${G.id}:${E.provider}`)):null,T?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(Jp,{property:G,onRetryEvidence:b})})},`${G.id}:details`):null]},G.id)}),W.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"py-8 text-center text-sm text-secondary",children:"No properties match this search."})}):null]})]})}),f&&t.currentView.nextCursor&&h?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",W.length," of ",t.currentView.propertyTotal]}),m?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(A,{size:"sm",variant:"outline",disabled:u,onClick:()=>h(t.currentView.nextCursor),children:u?"Loading…":m?"Retry loading more properties":"Show 50 more"})]}):f?W.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",W.length," of ",t.currentView.propertyTotal]}):null:e.jsx(yr,{shown:W.length,total:O.length,itemLabel:"properties",onShowAll:()=>$(Number.MAX_SAFE_INTEGER)})]}),!i&&!le&&fe>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 (",fe,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,D).map(G=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(de,{tone:G.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:G.property}),e.jsx("span",{className:"text-secondary",children:G.summary})]},G.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((G,T)=>G+(T.count??1),0)," of ",fe," flagged results"]}),e.jsx(A,{size:"sm",variant:"outline",onClick:()=>w(G=>Math.min(t.flaggedResults.length,G+Fp)),children:"Show 50 more"})]}):Z<fe?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 ",fe," flagged results"]}),f&&t.currentView.nextCursor&&h?e.jsx(A,{size:"sm",variant:"outline",disabled:u,onClick:()=>h(t.currentView.nextCursor),children:u?"Loading…":m?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function Yo(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function tg(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 sg({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:o,onRunMeasurement:i,onRetryReport:u,onViewChange:m,onLoadMore:d,onPropertyExpand:p,onRetryEvidence:h,renderPropertyLink:j,isRunningMeasurement:b,isOpeningSetup:g,isViewLoading:f,isLoadingMore:y,isLoadMoreError:C,viewSearch:Q}){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(A,{type:"button",size:"sm",disabled:g,onClick:o,children:g?"Opening setup…":Yo(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."}),u?e.jsx(A,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:u,children:"Retry report"}):null]}):a?e.jsx(eg,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:o,onViewChange:m,onLoadMore:d,onPropertyExpand:p,onRetryEvidence:h,renderPropertyLink:j,isRunningMeasurement:b,isRepublishingSetup:g,isViewLoading:f,isLoadingMore:y,isLoadMoreError:C,viewSearch:Q}):e.jsx("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-secondary",children:"No advanced measurement report is available yet."})]})}const pn={numerator:null,denominator:null,reason:"plan_v1"};function ng(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Oi(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function ag(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function rg(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function ig(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 og(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function lg(t){const s=new Map;for(const n of t){const a=og(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function cg(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(g=>[g.stableKey,g])),r=new Map(n.querySnapshots.map(g=>[g.queryId,g.queryText])),o=new Map;for(const g of n.targetQuerySelections){const f=o.get(g.targetKey)??[];f.push(...g.queryIds.map(y=>r.get(y)).filter(y=>!!y)),o.set(g.targetKey,[...new Set(f)])}const i=lg(s.evidence),u=n.executionNodes.reduce((g,f)=>g+f.expectedSnapshots,0),m=s.run?.status==="completed"&&u>0,d=m?u:0,p=m?u:0,h=s.targets.map(g=>{const f=a.get(g.id),y=i.get(g.id)??[],C=y.map(R=>({id:`${R.observationId}:${R.usageEdgeId}:${R.sourceUrl}`,kind:ag(R.classification),query:R.queryText,url:R.sourceUrl,tone:rg(R.classification),historical:R.historical||R.bridged})),Q=y.some(R=>R.historical||R.bridged),M=s.run?g.completeness.complete?f?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${g.completeness.executed} of ${g.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:g.id,name:g.label,mentionCoverage:Oi(g.mentionCoverage),citationCoverage:Oi(g.citationCoverage),status:M,assignedQueries:o.get(g.id)??[],urls:f?.urls.map(ng)??[],evidence:C,historical:Q}}),j=new Map(h.map(g=>[g.id,g])),b=new Map(n.groups.map(g=>[g.stableKey,g]));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:d,totalSlots:p,date:ig(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:pn,mentionCoverage:pn,citationCoverage:pn},properties:h},groups:s.groups.map(g=>({id:g.id,label:g.label,confirmedCompetitorCount:b.get(g.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:pn,mentionCoverage:pn,citationCoverage:pn},properties:g.targetIds.map(f=>j.get(f)).filter(f=>!!f)}}))},flaggedResults:[]}}const dg={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function xt(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 ug(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 mg(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function hg({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[o,i]=l.useState(od),u=Re({...ld({client:V,path:{name:t},query:{period:o}}),placeholderData:Qi});async function m(){n(!0),r(null);try{await dd(t,"client",o)}catch(p){const h=p instanceof sn||p instanceof Error?p.message:"Download failed";r(h)}finally{n(!1)}}if(u.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(u.error){const p=u.error instanceof Error?u.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:p})})}const d=u.data;return d?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:d.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[d.meta.project.canonicalDomain," · ",d.meta.project.country," / ",d.meta.project.language.toUpperCase(),d.meta.location?` · Location: ${mg(d.meta.location)}`:" · No location set"," · ","Last ",d.meta.periodDays," days"," · ","Generated ",ug(d.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(xg,{period:o,onChange:i}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:De(m),disabled:s,children:[e.jsx(co,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(jg,{report:d}),e.jsx(Ag,{report:d,audience:"client"}),e.jsx(fg,{report:d}),e.jsx(Sg,{report:d,audience:"client",projectName:t}),e.jsx(Cg,{report:d})]}):null}function xg({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:cd.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 Gi="AI Visibility — Server-Side",Fi="AI engine attention",pg=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,gg="Live telemetry from your server logs.";function fg({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(qn,{eyebrow:Fi,title:Gi,subtitle:gg}),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:Gu(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,r=`vs prior ${a} days`,o=Ca(n,"requests",r),i=`${xt(s.verifiedCrawlerHits.current)} verified · ${xt(s.unverifiedCrawlerHits.current)} unverified${o?` · ${o}`:""}`,u=Ca(s.aiUserFetchHits,"requests",r),m=Ca(s.referralArrivals,"sessions",r),d=s.referralRedirects>0?`${xt(s.referralRedirects)} blocked by redirects`:"",p=[m,s.referralArrivalsClassSummary,d].filter(Boolean).join(" · "),h=s.byOperator.filter(j=>j.verifiedHits>0||j.unverifiedHits>0||j.userFetchHits>0||j.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(qn,{eyebrow:Fi,title:Gi,subtitle:pg(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Wa,{label:"AI bot requests observed",value:xt(n.current),subtitle:i}),e.jsx(Wa,{label:"AI user-fetch requests",value:xt(s.aiUserFetchHits.current),subtitle:u||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(Wa,{label:"AI referral sessions",value:xt(s.referralArrivals.current),subtitle:p})]}),h.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:h.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:j.operator}),e.jsx("td",{children:xt(j.verifiedHits+j.unverifiedHits)}),e.jsx("td",{children:xt(j.userFetchHits)}),e.jsx("td",{children:xt(j.referralArrivals)})]},j.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 bg(t,s){return t.audience==="both"||t.audience===s}const yg={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function pa(t){return yg[t]??t.charAt(0).toUpperCase()+t.slice(1)}function vg(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 jg({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=vg(t.whatsChanged.mentionRate),u=n.providers.length>0?n.providers.map(pa).join(", "):`${xt(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(Qa,{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(Qa,{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(Qa,{label:"AI tools tested",value:xt(s.providerCount),subtitle:u})]}),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((m,d)=>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(d+1).padStart(2,"0")}),e.jsxs("span",{children:['"',m,'"']})]},d))})]}),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(m=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:pa(m.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(m.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[m.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",m.mentionedCount,"/",m.totalCount,")"]})]})]},m.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((m,d)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:m},d))})]})}function Qa({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 Ng(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function wg(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function Sg({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(h=>bg(h,s)),r=Vu(t,a),o=s==="client",i=ud(),[u,m]=l.useState(new Set),d=u.size>0?r.filter(h=>!h.targetRef||!u.has(h.targetRef)):r,p=h=>{if(!h.targetRef)return;const j=h.targetRef;m(b=>new Set(b).add(j)),i.mutate({projectName:n,body:{targetRef:j}},{onSuccess:()=>{ke({tone:"positive",title:`Dismissed "${h.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:b=>{ke({tone:"negative",title:`Couldn't dismiss "${h.title}"`,detail:String(b)}),m(g=>{const f=new Set(g);return f.delete(j),f})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(qn,{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."}),d.length===0?e.jsx(Nr,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:d.map((h,j)=>{const b=h.evidence.length>0?h.evidence:h.why,g=h.why.length>0||h.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:j+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:hd(h),children:o?Ng(h.horizon):md(h.horizon)}),!o&&e.jsx(de,{tone:"neutral",children:xd(h.category)}),e.jsx(de,{tone:"neutral",children:o?wg(h.confidence):`${pd(h.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:h.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:h.action}),e.jsx(Pg,{items:b,limit:3,className:"mt-3"}),g&&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"}),h.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:h.why.map((f,y)=>e.jsx("li",{children:f},y))})]}),h.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:h.evidence.map((f,y)=>e.jsx("li",{children:f},y))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:o?"What success looks like:":"Win condition:"})," ",h.successMetric]}),h.targetRef&&!ee()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>p(h),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"})})]},`${h.priority}-${h.title}`)})})]})}function _i({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 Cg({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=Ku(t).slice(0,5),o=s.length>0?Math.max(...s.map(m=>m.count)):0,i=n?Math.max(...n.topQueries.slice(0,5).map(m=>m.impressions),1):0,u=s.length>0||n!==null||a!==null||r.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(qn,{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."}),u?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(m=>e.jsx(_i,{label:m.domain+(m.isCompetitor?" (competitor)":""),value:m.count,displayValue:`${xt(m.count)}×`,max:o,barClass:"bg-mono-400/70"},m.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:[xt(a.indexed)," of ",xt(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:xt(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:xt(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:xt(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(m=>e.jsx(_i,{label:m.query,value:m.impressions,displayValue:`${xt(m.impressions)} ${m.impressions===1?"search":"searches"}`,max:i,barClass:"bg-info-500/70"},m.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((m,d)=>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:m.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[gd(m.action),m.winnabilityClass==="ceded"&&e.jsx(de,{tone:"caution",children:"Ceded surface"})]})]},d))})]})]}):e.jsx(Nr,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function vr(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function jr(t){return t==="up"?"↑":t==="down"?"↓":"→"}function Ha({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=vr(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}%`:Fu(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:jr(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function Ui({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=vr(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=_u(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:[xt(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:jr(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function kg({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=vr(r.direction),u=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?pa(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:u,children:[o,r.deltaAbs.toFixed(1),"% ",jr(r.direction)]})]},r.provider)})})]})})]})}function Bi({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:dg[o.severity],children:fd(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?pa(o.provider):o.provider})]},o.id))})]})})]})}function Ag({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(qn,{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(Nr,{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(Ha,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(Ha,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(Ha,{label:a?"Queries AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(Ui,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(Ui,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(kg,{movements:n.providerMovements,audience:s}),e.jsx(Bi,{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(Bi,{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 Wa({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 qn({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 Pg({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 Nr({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function Rg({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[u,m]=l.useState(null),[d,p]=l.useState(t.displayName),[h,j]=l.useState(t.canonicalDomain),[b,g]=l.useState(t.country),[f,y]=l.useState(t.language),[C,Q]=l.useState(t.ownedDomains??[]),[M,R]=l.useState(""),[c,v]=l.useState(t.aliases??[]),[N,$]=l.useState(""),[D,w]=l.useState(null),[U,z]=l.useState(!1),[B,K]=l.useState(!1),[pe,we]=l.useState(""),[F,te]=l.useState(""),[ie,Y]=l.useState(""),[H,P]=l.useState(""),[ae,le]=l.useState(""),[O,W]=l.useState(null),[ue,_]=l.useState(null);l.useEffect(()=>{a||(p(t.displayName),j(t.canonicalDomain),g(t.country),y(t.language),Q(t.ownedDomains??[]),v(t.aliases??[]))},[t,a]);function Z(){r(!1),m(null),p(t.displayName),j(t.canonicalDomain),g(t.country),y(t.language),Q(t.ownedDomains??[]),v(t.aliases??[]),R(""),$("")}function fe(){const T=M.trim();T&&(C.includes(T)||Q([...C,T]),R(""))}function Fe(T){Q(C.filter(E=>E!==T))}function Le(){const T=N.trim();if(!T)return;const E=T.toLowerCase();c.some(he=>he.toLowerCase()===E)||v([...c,T]),$("")}function Ae(T){v(c.filter(E=>E!==T))}async function Xe(){if(!(!d.trim()||!h.trim()||!b.trim()||!f.trim())){i(!0),m(null);try{await s(t.name,{displayName:d.trim(),canonicalDomain:h.trim(),ownedDomains:C,aliases:c,country:b.trim(),language:f.trim()}),r(!1),ke({title:"Project settings saved",detail:`${d.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(T){m(T instanceof Error?T.message:"Failed to save")}finally{i(!1)}}}async function lt(){const T=pe.trim(),E=F.trim(),he=ie.trim(),be=H.trim();if(!(!T||!E||!he||!be)){z(!0),w(null);try{const J={label:T,city:E,region:he,country:be};ae.trim()&&(J.timezone=ae.trim()),await vd(t.name,J),n(),we(""),te(""),Y(""),P(""),le(""),K(!1),ke({title:"Location added",detail:`${T} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${T}`,dedupeMode:"drop"})}catch(J){w(J instanceof Error?J.message:"Failed to add location")}finally{z(!1)}}}async function Se(T){z(!0),w(null);try{await yd(t.name,T),n(),ke({title:"Location removed",detail:`${T} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${T}`,dedupeMode:"drop"})}catch(E){w(E instanceof Error?E.message:"Failed to remove location")}finally{z(!1)}}async function et(T){z(!0),w(null);try{await bd(t.name,T),n(),ke({title:"Default location updated",detail:`${T} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(E){w(E instanceof Error?E.message:"Failed to set default location")}finally{z(!1)}}async function Ve(T){W(T),_(null);try{await jd(t.name,T),ke({title:`${T.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(E){_(E instanceof Error?E.message:"Could not download tracking results.")}finally{W(null)}}const _e=d!==t.displayName||h!==t.canonicalDomain||b!==t.country||f!==t.language||JSON.stringify(C)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(c)!==JSON.stringify(t.aliases??[]),Ue="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",Ie="mb-1 block text-sm font-medium text-secondary",G=pe.trim()&&F.trim()&&ie.trim()&&H.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"})]}),!ee()&&!a&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),u&&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:[u,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>m(null),children:"×"})]}),!ee()&&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:Ie,children:"Display name"}),e.jsx("input",{className:Ue,type:"text",value:d,onChange:T=>p(T.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Canonical domain"}),e.jsx("input",{className:Ue,type:"text",value:h,onChange:T=>j(T.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Country"}),e.jsx("input",{className:Ue,type:"text",value:b,onChange:T=>g(T.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Language"}),e.jsx("input",{className:Ue,type:"text",value:f,onChange:T=>y(T.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:C.map(T=>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:[T,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Fe(T),"aria-label":`Remove ${T}`,children:"×"})]},T))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ue} flex-1`,type:"text",placeholder:"docs.example.com",value:M,onChange:T=>R(T.target.value),onKeyDown:T=>T.key==="Enter"&&(T.preventDefault(),fe())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!M.trim(),onClick:fe,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,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:c.map(T=>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:[T,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Ae(T),"aria-label":`Remove ${T}`,children:"×"})]},T))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ue} flex-1`,type:"text",placeholder:"Facebook",value:N,onChange:T=>$(T.target.value),onKeyDown:T=>T.key==="Enter"&&(T.preventDefault(),Le())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!N.trim(),onClick:Le,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(A,{type:"button",disabled:o||!_e||!d.trim()||!h.trim(),onClick:De(Xe),children:o?"Saving...":"Save changes"}),e.jsx(A,{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(T=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:T},T))}):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(T=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:T},T))}):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:()=>w(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-faint",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(T=>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 ${T.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[T.label,T.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:T.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:T.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:T.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:T.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!ee()&&T.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:U,onClick:()=>{et(T.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${T.label} as default location`,children:"Set default"}),!ee()&&e.jsx("button",{type:"button",disabled:U,onClick:()=>{Se(T.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${T.label}`,children:"Remove"})]})})]},T.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),ee()?null:B?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:Ue,type:"text",value:pe,onChange:T=>we(T.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:Ue,type:"text",value:F,onChange:T=>te(T.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:Ue,type:"text",value:ie,onChange:T=>Y(T.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:Ue,type:"text",value:H,onChange:T=>P(T.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:Ue,type:"text",value:ae,onChange:T=>le(T.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(A,{type:"button",size:"sm",disabled:U||!G,onClick:De(lt),children:U?"Adding...":"Add location"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:U,onClick:()=>{K(!1),w(null)},children:"Cancel"})]})]}):e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:()=>K(!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(A,{type:"button",variant:"outline",size:"sm",disabled:O!==null,onClick:De(()=>Ve("csv")),children:O==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:O!==null,onClick:De(()=>Ve("json")),children:O==="json"?"Preparing JSON...":"Download JSON"})]})]}),ue&&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:ue})]})]})]})}function An(t){return{...t??{}}}function Ig(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 u=a[i];return u?.[0]===r&&u[1]===o})}function Tg({project:t,onSave:s}){const n=Re({queryKey:["settings"],queryFn:Xi,staleTime:6e4}),[a,r]=l.useState(t.providers.length===0),[o,i]=l.useState(t.providers),[u,m]=l.useState(()=>An(t.providerModels)),[d,p]=l.useState({providers:t.providers,providerModels:An(t.providerModels)}),[h,j]=l.useState(!1),[b,g]=l.useState(!1),[f,y]=l.useState(null),[C,Q]=l.useState(null),M=l.useRef(null),R=n.data?.providerCatalog??[],c=l.useMemo(()=>new Set((n.data?.providers??[]).filter(B=>B.configured).map(B=>B.name)),[n.data]),v=l.useMemo(()=>{const B=new Map(R.map(K=>[K.name,K]));for(const K of Object.keys(u))B.has(K)||B.set(K,{name:K,displayName:K,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...B.values()].sort((K,pe)=>K.displayName.localeCompare(pe.displayName))},[R,u]),N=!Ig(u,d.providerModels);l.useEffect(()=>{if(h||b)return;const B={providers:t.providers,providerModels:An(t.providerModels)};p(B),r(B.providers.length===0),i(B.providers),m(B.providerModels)},[t]);function $(){g(!0),r(!1),o.length===0&&i([...c])}function D(B,K,pe=!1){g(!0),m(we=>{const F={...we};return K==="__inherit__"?delete F[B]:K==="__custom__"?F[B]=pe?"":F[B]??"":F[B]=K,F}),K==="__custom__"&&queueMicrotask(()=>M.current?.focus())}function w(B,K){g(!0),i(pe=>K?[...new Set([...pe,B])]:pe.filter(we=>we!==B))}function U(){g(!1),r(d.providers.length===0),i(d.providers),m(An(d.providerModels)),y(null),Q(null)}async function z(){if(!(n.isError||n.isLoading||!a&&o.length===0)){j(!0),y(null),Q(null);try{const B=Object.fromEntries(Object.entries(u).filter(([pe,we])=>we.trim()!==""&&(a||o.includes(pe)))),K={providers:a?[]:o,providerModels:B};await s(K),p({providers:[...K.providers],providerModels:An(K.providerModels)}),g(!1),Q("Engine settings saved. They apply on the next sweep.")}catch(B){y(ur(B))}finally{j(!1)}}}return ee()?null:n.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…"})}):n.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(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):R.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(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):c.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(bs,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":h,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:h,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:a,onChange:()=>{g(!0),r(!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:!a,onChange:$})," Choose engines"]}),!a&&e.jsx("div",{className:"project-engine-list",children:v.map(B=>{const K=o.includes(B.name),pe=c.has(B.name),we=K&&!pe,F=u[B.name],te=B.knownModels.some(Y=>Y.id===F),ie=F===void 0?"__inherit__":te?F:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:K,disabled:!pe&&!K,onChange:Y=>w(B.name,Y.target.checked)})," ",e.jsx("span",{children:B.displayName}),we&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),K&&(B.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${B.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${B.name}`,value:ie,onChange:Y=>D(B.name,Y.target.value,te),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",B.defaultModel||"default"]}),B.knownModels.map(Y=>e.jsx("option",{value:Y.id,children:Y.displayName},Y.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),ie==="__custom__"&&e.jsx("input",{ref:M,"aria-label":`${B.displayName} custom model ID`,value:F??"",onChange:Y=>{g(!0),m(H=>({...H,[B.name]:Y.target.value}))},"aria-describedby":`project-model-hint-${B.name}`}),e.jsxs("p",{id:`project-model-hint-${B.name}`,className:"project-engine-help",children:[F?"Project override":"Inherited from instance settings",". ",B.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},B.name)})})]}),!a&&o.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}),C&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:C}),N&&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(A,{type:"button",onClick:()=>{z()},disabled:h||!a&&o.length===0,children:h?"Saving engines…":"Save engines"}),e.jsx(A,{type:"button",variant:"outline",onClick:U,disabled:h,children:"Cancel"})]})]})}const $g=[{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:"custom",label:"Custom cron expression"}],Vi=["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 Mg({projectName:t}){const s=cs(),n=!ee()&&!s,a=As(),[r,o]=l.useState(!1),[i,u]=l.useState("daily"),[m,d]=l.useState(6),[p,h]=l.useState(""),[j,b]=l.useState("UTC"),[g,f]=l.useState(!1),[y,C]=l.useState(""),[Q,M]=l.useState(!1),[R,c]=l.useState(!1),[v,N]=l.useState(null),[$,D]=l.useState(void 0),w=Nd({client:V,path:{name:t}}),U=Re({...ro({client:V,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),z=U.isPending||U.isFetching,B=U.isError,K=U.data?.find(O=>O.kind==="answer-visibility")??null,pe=r&&$!==void 0&&(K?.updatedAt??null)!==$,we=O=>{a.setQueryData(w,W=>{const ue=(W??[]).filter(_=>_.kind!=="answer-visibility");return O?[...ue,O]:ue})},F=O=>{if(O){const W=kd(O.preset??null,O.cronExpr);u(W.freq),d(W.hour),h(W.customCron);const ue=Vi.includes(O.timezone);b(ue?O.timezone:"Other"),f(!ue),C(ue?"":O.timezone)}else u("daily"),d(6),h(""),b("UTC"),f(!1),C("");D(O?.updatedAt??null)},te=()=>{n&&(F(K),N(null),o(!0))},ie=()=>{F(K),N(null)},Y=async()=>{(await U.refetch()).isError?N("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):N(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},H=async(O,W)=>{if(O instanceof sn&&O.code==="SCHEDULE_VERSION_CONFLICT"){await Y();return}N(O instanceof Error?O.message:W)},P=async()=>{if(n&&!(pe||$===void 0)){M(!0),N(null);try{const O=await U.refetch();if(O.isError||O.data===void 0){N("Canonry could not verify the latest schedule. Try again before saving.");return}if(((O.data.find(fe=>fe.kind==="answer-visibility")??null)?.updatedAt??null)!==$)return;const _={timezone:g?y.trim()||"UTC":j,expectedUpdatedAt:$};i==="custom"?_.cron=p.trim():_.preset=Cd(i,m);const Z=await Lr(t,_);o(!1),D(void 0),we(Z),ke({title:"Schedule saved",detail:wa(Z.preset??null,Z.cronExpr,Z.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(O){await H(O,"Failed to save schedule")}finally{M(!1)}}},ae=async()=>{if(!n||!K)return;const O=K.updatedAt;M(!0),N(null);try{const W=await U.refetch();if(W.isError||W.data===void 0){N("Canonry could not verify the latest schedule. Try again before updating it.");return}const ue=W.data.find(fe=>fe.kind==="answer-visibility")??null;if(!ue||ue.updatedAt!==O){N("This schedule changed elsewhere. Review the latest version and try again.");return}const _={timezone:ue.timezone,enabled:!ue.enabled,expectedUpdatedAt:O};ue.preset?_.preset=ue.preset:_.cron=ue.cronExpr;const Z=await Lr(t,_);we(Z),ke({title:Z.enabled?"Schedule resumed":"Schedule paused",detail:wa(Z.preset??null,Z.cronExpr,Z.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(W){await H(W,"Failed to update schedule")}finally{M(!1)}},le=async()=>{if(!n||!K)return;const O=K.updatedAt;c(!0),N(null);try{await Sd(t,O),we(null),o(!1),D(void 0),ke({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(W){await H(W,"Failed to remove schedule")}finally{c(!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&&!z&&!B&&!r&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:te,children:K?"Edit schedule":"+ Set schedule"})]}),z&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),v&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:v}),!z&&B&&e.jsxs(xe,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{U.refetch()},children:"Retry"})]}),!z&&!B&&!r&&K===null&&e.jsx(xe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?_s:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!z&&!B&&!r&&K!==null&&e.jsx(xe,{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:_s}),e.jsx("p",{className:"text-sm font-medium text-strong",children:wa(K.preset??null,K.cronExpr,K.timezone)}),e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:K.cronExpr})]}),K.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",new Date(K.nextRunAt).toLocaleString()]}),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(A,{type:"button",variant:"outline",size:"sm",disabled:Q,onClick:De(ae),children:K.enabled?"Pause":"Resume"}),n&&e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:R,onClick:De(le),children:R?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[pe&&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(A,{type:"button",variant:"outline",size:"sm",onClick:ie,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",value:i,onChange:O=>u(O.target.value),children:$g.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))})]}),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:m,disabled:i==="twice-daily"||i==="custom",onChange:O=>d(parseInt(O.target.value)),children:Array.from({length:24},(O,W)=>e.jsx("option",{value:W,children:wd(W)},W))})]})]}),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:p,onChange:O=>h(O.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",value:g?"Other":j,onChange:O=>{O.target.value==="Other"?(f(!0),b("Other")):(f(!1),b(O.target.value))},children:[Vi.map(O=>e.jsx("option",{value:O,children:O},O)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),g&&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:y,onChange:O=>C(O.target.value)})]}),v&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:v}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{o(!1),D(void 0),N(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:Q||U.isFetching||B||pe||i==="custom"&&!p.trim(),onClick:De(P),children:Q?"Saving...":"Save schedule"})]})]})]})}const Lg=[{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 Dg({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[o,i]=l.useState(""),[u,m]=l.useState(["citation.lost","citation.gained"]),[d,p]=l.useState(!1),[h,j]=l.useState(null),[b,g]=l.useState({}),[f,y]=l.useState(new Set);l.useEffect(()=>{Ad(t).then(n).catch(()=>n([]))},[t]);const C=c=>{m(v=>v.includes(c)?v.filter(N=>N!==c):[...v,c])},Q=async()=>{if(!(!o.trim()||u.length===0)){p(!0),j(null);try{const c=await Pd(t,{channel:"webhook",url:o.trim(),events:u});n(v=>v==="loading"?[c]:[...v,c]),i(""),m(["citation.lost","citation.gained"]),r(!1),ke({title:"Webhook added",detail:`Notifications will be sent to ${c.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(c){j(c instanceof Error?c.message:"Failed to add webhook")}finally{p(!1)}}},M=async c=>{if(!f.has(c)){y(v=>new Set(v).add(c));try{await Id(t,c),n(v=>v==="loading"?v:v.filter(N=>N.id!==c)),ke({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${c}`,dedupeMode:"drop"})}catch(v){j(v instanceof Error?v.message:"Failed to remove webhook")}finally{y(v=>{const N=new Set(v);return N.delete(c),N})}}},R=async c=>{g(v=>({...v,[c]:{state:"testing"}}));try{const v=await Rd(t,c);g(N=>({...N,[c]:{state:v.ok?"ok":"fail",status:v.status}})),v.ok&&ke({title:"Test notification sent",detail:`Webhook returned status ${v.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${c}`,dedupeMode:"replace"})}catch{g(v=>({...v,[c]:{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"})]}),!ee()&&s!=="loading"&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),j(null)},children:a?"Cancel":"+ Add webhook"})]}),!ee()&&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:c=>i(c.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:Lg.map(c=>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:u.includes(c.value),onChange:()=>C(c.value)}),e.jsx("span",{className:"text-sm text-neutral",children:c.label})]},c.value))})]}),h&&e.jsx("p",{className:"text-negative-400 text-sm",children:h}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),j(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:d||!o.trim()||u.length===0,onClick:De(Q),children:d?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(xe,{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(c=>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:c.urlHost,children:c.urlDisplay??c.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:c.events.map(v=>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:v.replace("."," ")},v))})}),e.jsx("td",{children:e.jsx(de,{tone:c.enabled?"positive":"neutral",children:c.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[b[c.id]&&(()=>{const v=b[c.id],N=v.state==="testing"?"Sending…":v.state==="ok"?`Delivered${v.status?` (${v.status})`:""}`:`Failed${v.status?` (${v.status})`:""}`;return e.jsx(de,{tone:v.state==="ok"?"positive":v.state==="fail"?"negative":"neutral",children:N})})(),!ee()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:b[c.id]?.state==="testing",onClick:()=>{R(c.id)},children:"Test"}),!ee()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:f.has(c.id),onClick:()=>{M(c.id)},children:f.has(c.id)?"Removing…":"Remove"})]})})]},c.id))})]}),h&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:h})]})]})}const Ki=2e3,zi=3e5;function Eg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function qg(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 Og({projectName:t,refreshNonce:s}){const n=As(),[a,r]=l.useState(null),[o,i]=l.useState([]),[u,m]=l.useState(null),[d,p]=l.useState([]),[h,j]=l.useState([]),[b,g]=l.useState(null),[f,y]=l.useState(""),[C,Q]=l.useState(""),[M,R]=l.useState(""),[c,v]=l.useState(!0),[N,$]=l.useState(!1),[D,w]=l.useState(null),[U,z]=l.useState("performance");l.useEffect(()=>{B()},[t,s]);async function B(){v(!0),w(null);try{const P=await n.fetchQuery({...oo({client:V,path:{name:t}}),staleTime:qt});if(r(P),P.connected){const[ae,le,O,W]=await Promise.all([n.fetchQuery({...ou({client:V,path:{name:t}}),staleTime:qt}).catch(()=>null),n.fetchQuery({...lu({client:V,path:{name:t}}),staleTime:qt}).catch(()=>[]),n.fetchQuery({...cu({client:V,path:{name:t}}),staleTime:qt}).catch(()=>[]),P.siteUrl?Promise.resolve([]):n.fetchQuery({...du({client:V,path:{name:t}}),staleTime:qt}).then(ue=>ue.sites).catch(()=>[])]);m(ae),p(le),j(O),i(W)}else m(null),p([]),j([]),i([])}catch(P){w(P instanceof Error?P.message:"Failed to load Bing data")}finally{v(!1)}}async function K(){if(C.trim()){w(null);try{const P=await uu(t,C.trim());await yt(n,"bing"),Q(""),P.availableSites.length>0&&i(P.availableSites),await B()}catch(P){w(P instanceof Error?P.message:"Failed to connect")}}}async function pe(){try{await mu(t),await yt(n,"bing"),r(null),i([]),m(null),p([]),j([]),g(null),R(""),w(null)}catch(P){w(P instanceof Error?P.message:"Failed to disconnect")}}async function we(){if(M)try{await hu(t,M),await yt(n,"bing"),await B()}catch(P){w(P instanceof Error?P.message:"Failed to set site")}}async function F(){if(f.trim())try{const P=await xu(t,f.trim());await yt(n,"bing"),g(P),p(ae=>[P,...ae])}catch(P){w(P instanceof Error?P.message:"Inspection failed")}}async function te(P){$(!0),w(null);try{const ae=await Er(t,{urls:[P]}),{succeeded:le,failed:O,total:W}=ae.summary;ke({title:"Bing submission requested",detail:O===0?`${le} URL submitted to Bing.`:`${le}/${W} submitted successfully, ${O} failed.`,tone:O===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${P}`,dedupeMode:"replace"})}catch(ae){const le=ae instanceof Error?ae.message:"Submission failed";w(le),ke({title:"Bing submission failed",detail:le,tone:"negative",dedupeKey:`bing:indexing:${t}:${P}`,dedupeMode:"replace"})}finally{$(!1)}}async function ie(){$(!0),w(null),ke({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const P=await Er(t,{allUnindexed:!0}),{succeeded:ae,failed:le,total:O}=P.summary;ke({title:"Bing submissions requested",detail:le===0?`${ae}/${O} URL${O!==1?"s":""} submitted to Bing.`:`${ae}/${O} submitted successfully, ${le} failed.`,tone:le===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(P){const ae=P instanceof Error?P.message:"Batch submission failed";w(ae),ke({title:"Bing submissions failed",detail:ae,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{$(!1)}}if(c)return e.jsx(xe,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return ee()?e.jsxs(xe,{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(xe,{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:C,onChange:P=>Q(P.target.value),onKeyDown:P=>{P.key==="Enter"&&K()}}),e.jsx(We,{size:"sm",disabled:!C.trim(),onClick:De(K),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(xe,{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"}),!ee()&&e.jsx(We,{size:"sm",variant:"ghost",onClick:De(pe),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?Vt(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:M,onChange:P=>R(P.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),o.map(P=>e.jsxs("option",{value:P.url,children:[P.url,P.verified?" (verified)":""]},P.url))]}),!ee()&&e.jsx(We,{size:"sm",disabled:!M,onClick:De(we),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 Y=[{key:"performance",label:"Performance",eyebrow:"Performance",title:"Search performance"},{key:"coverage",label:"Coverage",eyebrow:"Coverage",title:"Index monitoring"},{key:"inspections",label:"Inspections",eyebrow:"Inspection",title:"URL inspection history"}],H=Y.find(P=>P.key===U)??Y[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(xe,{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"}),!ee()&&e.jsx(We,{size:"sm",variant:"ghost",onClick:De(pe),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?Vt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(xe,{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:H.eyebrow}),e.jsx("h3",{children:H.title})]}),e.jsx("p",{className:"text-xs text-muted",children:u?.lastInspectedAt?`Last inspected ${Vt(u.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:Y.map(P=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${U===P.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>z(P.key),children:P.label},P.key))}),U==="coverage"&&u&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Vn,{label:"Indexed",value:u.summary.indexed,tone:"positive"}),e.jsx(Vn,{label:"Not in index",value:u.summary.notIndexed+(u.summary.unknown??0),tone:"negative"}),e.jsx(Vn,{label:"Status unknown",value:u.summary.unknown??0,tone:"neutral"}),e.jsx(Vn,{label:"Coverage",value:`${u.summary.percentage}%`,tone:"neutral"})]}),u.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 (",u.notIndexed.length,")"]}),!ee()&&e.jsx(We,{size:"sm",variant:"ghost",disabled:N,onClick:De(ie),children:N?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!ee()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:u.notIndexed.map(P=>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:P.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.httpCode??"—"}),!ee()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:N,onClick:()=>{te(P.url)},children:"Submit"})})]},P.id))})]})})]}),(u.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 (",(u.unknown??[]).length,")"]}),!ee()&&e.jsx(We,{size:"sm",variant:"ghost",disabled:N,onClick:De(ie),children:N?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!ee()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(u.unknown??[]).map(P=>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:P.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.lastCrawledDate?Vt(P.lastCrawledDate):"—"}),!ee()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:N,onClick:()=>{te(P.url)},children:"Submit"})})]},P.id))})]})})]}),u.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",u.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:u.indexed.map(P=>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:P.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.lastCrawledDate?Vt(P.lastCrawledDate):"—"})]},P.id))})]})})]})]}),U==="coverage"&&!u&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),U==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!ee()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:f,onChange:P=>y(P.target.value),onKeyDown:P=>{P.key==="Enter"&&F()}}),e.jsx(We,{size:"sm",disabled:!f.trim(),onClick:De(F),children:"Inspect"})]}),b&&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:b.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:b.inIndex?"text-positive-400":"text-negative-400",children:b.inIndex?"Yes":"No"})," · ","HTTP: ",b.httpCode??"—"," · ","Crawled: ",b.lastCrawledDate??"—"]})]}),d.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:d.map(P=>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:P.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(de,{tone:P.inIndex?"positive":"negative",children:P.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Vt(P.inspectedAt)})]},P.id))})]})})]}),U==="performance"&&e.jsx("div",{className:"mt-4",children:h.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:Bn[Xs.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Bn[Xs.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Bn[Xs.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Bn[Xs.Position]})]})}),e.jsx("tbody",{children:h.map((P,ae)=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:P.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:P.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:P.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(P.ctr)?P.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:P.averagePosition.toFixed(1)})]},ae))})]})})})]})]})}function Gg({projectName:t}){const s=As(),[n,a]=l.useState("google"),[r,o]=l.useState(!0),[i,u]=l.useState("idle"),[m,d]=l.useState(null),p=l.useRef(null),[h,j]=l.useState(null),[b,g]=l.useState(null),[f,y]=l.useState(0);async function C(M=!1){M||o(!0),d(null);try{const[R,c]=await Promise.all([s.fetchQuery({...dr({client:V,path:{name:t}}),staleTime:qt}).catch(()=>[]),s.fetchQuery({...oo({client:V,path:{name:t}}),staleTime:qt}).catch(()=>null)]),v=R.find(N=>N.connectionType==="gsc")??null;j(v),g(c)}catch(R){d(R instanceof Error?R.message:"Failed to load search engine connections")}finally{o(!1)}}async function Q(){if(i!=="idle")return;p.current?.abort();const M=new AbortController;p.current=M;const R=M.signal;u("syncing"),d(null),ke({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const c=[],v=[];try{async function N(){if(!h)return;const w=await ru(t);if(!w?.id)return;const U=Date.now()+zi;for(;Date.now()<U;){if(R.aborted||(await new Promise(B=>setTimeout(B,Ki)),R.aborted))return;const z=await Ja(w.id).catch(()=>null);if(!z)break;if(["completed","failed","cancelled"].includes(z.status)){z.status!=="completed"&&c.push(`Google sync ${z.status}`);return}}v.push("Google sync is still running — search data will appear shortly")}async function $(){if(!b?.connected)return;const w=await iu(t).catch(()=>null);if(!w?.id){c.push("Bing sweep could not be started");return}const U=Date.now()+zi;for(;Date.now()<U;){if(R.aborted||(await new Promise(B=>setTimeout(B,Ki)),R.aborted))return;const z=await Ja(w.id).catch(()=>null);if(!z)break;if(["completed","failed","cancelled","partial"].includes(z.status)){z.status==="failed"?c.push("Bing sweep failed"):z.status==="partial"&&v.push("Bing sweep finished with some pages unverified");return}}v.push("Bing sweep is still running — coverage will update shortly")}const D=await Promise.allSettled([N(),$()]);for(const w of D)w.status==="rejected"&&c.push(w.reason instanceof Error?w.reason.message:"Sync failed");if(await Promise.all([yt(s,"gsc"),yt(s,"bing")]),R.aborted)return;if(u("reloading"),await C(!0),y(w=>w+1),c.length>0){const w=`Partial refresh: ${[...c,...v].join("; ")}`;d(w),ke({title:"Search coverage partially refreshed",detail:w,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else v.length>0?ke({title:"Search coverage refresh incomplete",detail:v.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):ke({title:"Search coverage refreshed",detail:"Google and Bing workspaces are reloaded with the latest stored coverage.",tone:"positive",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}catch(N){if(!R.aborted){const $=N instanceof Error?N.message:"Refresh failed";d($),ke({title:"Search coverage refresh failed",detail:$,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{R.aborted||u("idle")}}return l.useEffect(()=>(C(),()=>{p.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(([M,R])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===M,className:`project-subnav-link ${n===M?"project-subnav-link-active":""}`,onClick:()=>a(M),children:R},M))}),!ee()&&e.jsxs(We,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{Q()},children:[e.jsx(la,{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"]})]}),m&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:m}),n==="google"&&e.jsx(Km,{projectName:t,refreshNonce:f}),n==="bing"&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(Og,{projectName:t,refreshNonce:f})]})]})}function ga({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(ze,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${Hi[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 Fg({model:t,sweepRunning:s,hasVisibilityBaseline:n}){const a=t.citationMovement,r=t.mentionMovement,o=t.movementComparison,i=t.recentRuns.find(b=>b.kind===Fs["answer-visibility"]&&(b.status===oa.completed||b.status===oa.partial)),u=b=>b.tone==="positive"?"improved":b.tone==="negative"?"declined":b.gained>0||b.lost>0?"mixed":"steady",m=u(r),d=u(a),p=(()=>{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(m===d)return m==="steady"?"Answer mentions and citation coverage held steady":m==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${m}`;const b=m==="mixed"?"Answer mention movement was mixed":m==="steady"?"Answer mentions held steady":`Answer mentions ${m}`,g=d==="mixed"?"citation movement was mixed":d==="steady"?"citation coverage held steady":`citation coverage ${d}`;return`${b}; ${g}`})(),h=[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(", "),j=`${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(ze,{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:p})]}),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(ga,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(ga,{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?`${h||"Query set changed"} · ${j}.`:`${j}.`})]}):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:cs()?_s:"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.":cs()?_s:"Complete your first AI Visibility sweep to measure both signals."})]})})]})}function Ya({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(Ln,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:o})]})}function sf(t){const{projectName:s}=al({from:"/projects/$projectName"}),a=io()?.dashboard.projects.find(b=>b.project.name===s||b.project.id===s)?.project.name??null,r=Re({...Td({client:V}),enabled:!a}),o=a??r.data?.find(b=>b.name===s||b.id===s)?.name??null,{commandCenter:i,isLoading:u,latestVisibilityRevision:m,competitorHistoryRevision:d,refetch:p}=$d(o),h=!a&&r.isLoading||u;return!o&&!a&&r.isSuccess&&!u?e.jsx("div",{className:"page-container",children:e.jsxs(xe,{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(A,{asChild:!0,children:e.jsx(bs,{to:"/",children:"Return to overview"})})]})}):!i||h?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(b=>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"})]},b))}),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(b=>e.jsx("div",{className:"skeleton-text-sm w-full"},b))})]})]}):e.jsx(Ug,{model:i,refetch:p,latestVisibilityRevision:m,competitorHistoryRevision:d,...t})}function _g({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null);if(l.useEffect(()=>{if(!n)return;const i=m=>{r.current&&!r.current.contains(m.target)&&a(!1)},u=m=>{m.key==="Escape"&&a(!1)};return document.addEventListener("pointerdown",i),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("keydown",u)}},[n]),t.length===0)return null;const o=t.some(i=>i.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${o?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(i=>!i),children:["More",e.jsx(Ln,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(i=>e.jsx(bs,{to:i.href,role:"menuitem",className:`project-subnav-menu-item ${i.key===s?"project-subnav-menu-item-active":""}`,"aria-current":i.key===s?"page":void 0,onClick:()=>a(!1),children:i.label},i.key))}):null]})}function Ug({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r}){const o=rl(),i=As(),{canWrite:u}=ao(),m=io(),d=s.project.name,p=Re({...Md({client:V,path:{name:d}}),enabled:!ee()&&!!d&&(u||t==="portfolio"||t==="overview"||t==="settings"),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),h=m?m.dashboard.settings.providerStatuses.filter(k=>k.state==="ready").map(k=>Dr(k.name)):void 0,j=p.data?.answerVisibilityProviderReady,b=h,g=s.project.providers.map(Dr),f=b?.some(k=>g.length===0||g.includes(k))===!0,y=g.length===0||g.includes(Ld),C=Re({...Dd({client:V}),enabled:!ee()&&u&&j===void 0&&y&&!f,staleTime:6e4,retry:!1}),Q=y?C.isSuccess?typeof C.data.browserVersion=="string":C.isError?!1:void 0:!1,M=j??Ed({projectProviders:g,configuredApiProviders:b,cdpConfigured:Q}),R=l.useMemo(()=>{const k=qd();return k?Od(k.projectTabs):void 0},[]),c=Gd(t,R),v=l.useMemo(()=>s.competitors.map(k=>k.domain),[s.competitors]),[N,$]=l.useState(!1),[D,w]=l.useState(!1),U=Fd(),z=il({strict:!1}),B=z.manageQueries===!0,K=l.useCallback(()=>{o({to:".",replace:!0,search:k=>({...k,siteHealthRunId:void 0})})},[o]),[pe,we]=l.useState(B),[F,te]=l.useState(""),[ie,Y]=l.useState(!1),[H,P]=l.useState(null),[ae,le]=l.useState("30d"),[O,W]=l.useState(void 0),[ue,_]=l.useState(!1),[Z,fe]=l.useState(null),[Fe,Le]=l.useState(!1),Ae=Yu(z),[Xe,lt]=l.useState(void 0),[Se,et]=l.useState(void 0),Ve=l.useCallback(k=>{lt(k.search),k.sort&&et(k.sort),o({to:".",search:ce=>({...ce,...Xu(k)}),replace:!1})},[o]),[_e,Ue]=l.useState(!1),Ie=s?.visibilityEvidence??[],G=s?.project.displayName||s?.project.name||d,T=_d(),E=Re({...Ud({client:V,path:{name:d}}),enabled:c==="portfolio"&&!!d,staleTime:0,refetchOnMount:"always"}),he=Re({...Bd({client:V,path:{name:d}}),enabled:!ee()&&!!d&&(u||c==="portfolio"||c==="overview"||c==="settings"),staleTime:0,refetchOnMount:"always"}),be=he.data?.active??null,J=he.data!==void 0,Ze=new Set(be&&Number(be.plan.schemaVersion)===2?be.plan.groups?.map(k=>k.stableKey)??[]:[]),Ye={...Ae.scope==="group"&&!!Ae.groupKey&&J&&!Ze.has(Ae.groupKey)?{scope:"all",queryClass:Ae.queryClass}:Ae,...Xe?{search:Xe}:{}},Te=be===null?null:Number(be.plan.schemaVersion),$e=be?.revision??0,pt=J?`${d}:${$e}`:null,ct=l.useRef(null);l.useEffect(()=>{const k=ct.current;pt!==null&&(ct.current=pt),Ju(k,pt)&&(Ve({scope:"all",queryClass:"all"}),Ue(!1))},[pt,Ve]);const Oe={client:V,path:{name:d},query:{scope:Ye.scope,...Ye.groupKey?{groupKey:Ye.groupKey}:{},queryClass:Ye.queryClass,...Ye.search?{search:Ye.search}:{},...Se?{sort:Se}:{},limit:50}},Qe=ol({...Vd(Oe),enabled:c==="overview"&&!!d&&Te===2,initialPageParam:Oe,getNextPageParam:(k,ce)=>{if(!k.properties.nextCursor)return;const Ne=ce[0]?.measurement.displayedRunId;return{path:Oe.path,query:{...Oe.query,cursor:k.properties.nextCursor,...Ne?{runId:Ne}:{}}}},placeholderData:Qi,staleTime:0,refetchOnMount:"always"}),vt=Qe.data?.pages[0]?.measurement.displayedRunId,Ke=Re({...Kd({client:V,path:{name:d},query:{revision:$e,...vt?{runId:vt}:{}}}),enabled:c==="overview"&&!!d&&be!==null&&(Te===1||_e&&vt!==void 0),staleTime:0,refetchOnMount:"always"}),Ee=he.data!==void 0,qe=E.data!==void 0,jt=he.isPending&&!Ee,Ge=he.isError&&!Ee,It=E.isPending&&!qe,Gt=E.isError&&!qe,gt=Ke.data!==void 0,kt=tg({activePlanSchemaVersion:p.data?.activeSchemaVersion??Te,hasDraft:p.data?.draft!==null&&p.data?.draft!==void 0}),ht=p.data===void 0&&he.data===void 0&&(he.isLoading||p.isLoading),q=Te===2&&Ye.scope==="group"?Ye.groupKey:void 0,Ce=Te===2&&Ye.scope==="all",ye=l.useMemo(()=>{if(!(be?.plan.schemaVersion!==2||!q))return be.plan.groups.find(k=>k.stableKey===q)},[be,q]),je={client:V,path:{name:d},query:{window:ae,queryClass:Te===2?Ye.queryClass:"non-brand",...q?{groupKey:q}:{},...Ce?{scope:"all-markets"}:{}}},ft=c==="overview"&&!!d&&!ht,Je=Re({...zd(je),enabled:ft,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});Qd(d,JSON.stringify([r,s.competitors.map(k=>k.domain).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,$e,p.data?.draft?.etag??null]),ft);const At=Je.isError?Je.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,Nt=l.useMemo(()=>s.competitors.map(k=>({domain:k.domain,label:k.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:k.citationCount,answeredResults:k.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),rs=l.useMemo(()=>{if(be?.plan.schemaVersion!==2)return Nt;const k=q?ye?.competitors??[]:be.plan.groups.flatMap(Ne=>Ne.competitors),ce=new Map;for(const Ne of k){const Ut=Ne.domain.trim().toLowerCase();!Ut||ce.has(Ut)||ce.set(Ut,{domain:Ne.domain,label:Ne.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const Ne of Nt){const Ut=Ne.domain.trim().toLowerCase();!Ut||ce.has(Ut)||ce.set(Ut,Ne)}return[...ce.values()]},[be,q,Nt,ye]),is=Te===2?rs:Nt,ds=Et({...Hd({client:V}),meta:{skipGlobalErrorToast:!0}}),rt=p.data!==void 0?"success":p.isError?"error":"pending",us=l.useMemo(()=>{const k=Qe.data?.pages;return k?!Lu(k):!1},[Qe.data]),dt=l.useMemo(()=>{const k=Qe.data?.pages,ce=k?.[0],Ne=k?.at(-1);if(!(!ce||!Ne||us))return{...ce,properties:{...ce.properties,items:k.flatMap(Ut=>Ut.properties.items),nextCursor:Ne.properties.nextCursor}}},[us,Qe.data]),ys=l.useMemo(()=>{if(be)return be.plan.schemaVersion===1?Ke.data?cg(be,Ke.data):void 0:dt?Du({overview:dt,activePlan:be,sort:Se,report:Ke.data,reportState:dt.measurement.displayedRunId===void 0?"ready":Ke.isFetching&&Ke.data===void 0?"loading":Ke.isError&&Ke.data===void 0?"error":Ke.data?"ready":"loading"}):void 0},[be,Ke.data,Ke.isError,Ke.isFetching,dt]),Wt=Te===2?us?"error":Qe.isPending?"loading":Qe.isError&&ys===void 0?"error":"ready":Ke.isPending&&!gt?"loading":Ke.isError&&!gt?"error":"ready",Ft=(s?.recentRuns??[]).some(k=>k.kind===Fs["answer-visibility"]&&(k.status===oa.running||k.status===oa.queued)),Yt=s.queryCounts.total>0,wt=l.useMemo(()=>(s?.project.locations??[]).map(k=>k.label),[s?.project.locations]),ms=l.useMemo(()=>new Set(Ie.map(k=>k.location??"")),[Ie]),Qt=ms.has(""),bt=l.useMemo(()=>[...new Set(Ie.map(k=>k.query))].sort((k,ce)=>k.localeCompare(ce)),[Ie]),vs=bt.length>0||s.queryCounts.total>0,hs=vs||be!==null,xs=u&&!vs&&he.data===void 0&&he.isPending,ps=u&&p.isError&&!p.isFetching,St=u&&!ps&&(xs||M===void 0||p.isFetching),X=u&&!St&&!(!St&&hs&&M===!0),se=Re({...ro({client:V,path:{name:d}}),enabled:!ee()&&!cs()&&!!d,retry:!1}).data?.find(k=>k.kind===Fs["answer-visibility"]),re=se?.enabled&&se.nextRunAt?`Next AI sweep ${new Date(se.nextRunAt).toLocaleString()}`:null,Me=l.useMemo(()=>{const k=[...ms].filter(Boolean);return k.length>1?k:wt},[ms,wt]);l.useEffect(()=>{if(O===void 0||O===""||!d){fe(null),Le(!1);return}Le(!0),Wd(d,O,20).then(k=>{fe(k),Le(!1)}).catch(()=>{fe(null),Le(!1)})},[O,d]);const Tt=l.useMemo(()=>{if(!Z)return null;const k=new Map;for(const ce of Z){for(const[Ne,Ut]of Object.entries(ce.providerRuns??{}))k.set(`${ce.query}::${Ne}`,Ut.map(Bt=>({runId:Bt.runId,citationState:Bt.citationState,createdAt:Bt.createdAt,answerMentioned:Bt.answerMentioned,visibilityState:Bt.visibilityState,visibilityTransition:Bt.visibilityTransition,mentionState:Bt.mentionState,mentionTransition:Bt.mentionTransition})));(!ce.providerRuns||Object.keys(ce.providerRuns).length===0)&&k.set(`${ce.query}::`,ce.runs.map(Ne=>({runId:Ne.runId,citationState:Ne.citationState,createdAt:Ne.createdAt,answerMentioned:Ne.answerMentioned,visibilityState:Ne.visibilityState,visibilityTransition:Ne.visibilityTransition,mentionState:Ne.mentionState,mentionTransition:Ne.mentionTransition})))}return k},[Z]),ut=l.useMemo(()=>{const k=O!==void 0?Ie.filter(ce=>O===""?!ce.location:ce.location===O):Ie;return Tt?k.map(ce=>{const Ne=Tt.get(`${ce.query}::${ce.provider}`)??Tt.get(`${ce.query}::`);return Ne?{...ce,runHistory:Ne}:ce}):k},[Ie,O,Tt]);async function Ps(){try{await T.mutateAsync({projectName:d,projectLabel:G,sourceAction:"project-run"}),n()}catch{}}function S(){o({to:"/setup",search:{experience:"legacy",setupProject:d}})}async function oe(){w(!0);try{await au(d),ke({title:"Project deleted",detail:`${G} was removed.`,tone:"positive",dedupeKey:`project:delete:${d}`,dedupeMode:"drop"}),o({to:"/"}),n()}catch(k){console.error("Failed to delete project:",k)}finally{w(!1)}}async function at(){const k=F.split(`
|
|
8
|
+
`).map(ce=>ce.trim()).filter(Boolean);if(k.length!==0){Y(!0);try{await eu(d,k),n(),te("")}finally{Y(!1)}}}async function Pe(k){P(k);try{await Zd(d,[k]),n()}catch(ce){ke({title:"Could not remove query",detail:ce instanceof Error?ce.message:`Failed to remove "${k}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{P(null)}}async function it(k){const ce=k.trim();if(!ce)return!1;try{return await Jd(d,[ce]),n(),!0}catch(Ne){return ke({title:"Could not add competitor",detail:Ne instanceof Error?Ne.message:`Failed to add ${ce}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function Jt(k){const ce=s.competitors.find(Ne=>Ne.domain===k);if(!ce)return ke({title:"Could not remove competitor",detail:`Could not find ${k} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await Xd(d,ce.id),n(),!0}catch(Ne){return ke({title:"Could not remove competitor",detail:Ne instanceof Error?Ne.message:`Failed to remove ${ce.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function $t(k){const ce=k.trim();if(!ce||!q||Te!==2||!u||ee()||ds.isPending)return!1;try{const Ne=await ds.mutateAsync({client:V,path:{name:d},headers:{"Idempotency-Key":Eg()},body:{expectedActiveRevision:$e,groupKey:q,domain:ce}});return Promise.allSettled([p.refetch()]),ke({title:Ne.draftCreated?"Competitor added to a market draft":"Market competitor updated",detail:`Publish the Advanced Measurement draft before ${ce} is used in future market runs.`,tone:"positive",dedupeKey:`competitor:market-pin:${q}:${ce}`,dedupeMode:"replace"}),!0}catch(Ne){return ke({title:"Could not add market competitor",detail:Ne instanceof Error?Ne.message:`Failed to add ${ce} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function _t(k,ce){const Ne=await tu(k,ce);return await i.invalidateQueries({queryKey:no({client:V})}),i.setQueryData(su({client:V,path:{name:k}}),Ne),qg(i,Ne),ce.providers!==void 0&&await i.invalidateQueries({queryKey:nu({client:V,path:{name:k}}),exact:!0}),Ne}const Ht=`/projects/${encodeURIComponent(s.project.name)}`,Mt=[{key:"overview",label:"AI Visibility",href:Ht},{key:"search-console",label:"Search Engines",href:`${Ht}/search-console`},{key:"activity",label:"Activity",href:`${Ht}/activity`},{key:"technical-aeo",label:"Site Health",href:`${Ht}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${Ht}/conversions`},{key:"local",label:"Local Presence",href:`${Ht}/local`},{key:"discovery",label:"Query Discovery",href:`${Ht}/discovery`},{key:"backlinks",label:"Backlinks",href:`${Ht}/backlinks`}],js=[{key:"report",label:"Report",href:`${Ht}/report`},{key:"history",label:"Change History",href:`${Ht}/history`}],Nn=Mt.filter(k=>Sa(k.key,R)),Fn=js.filter(k=>Sa(k.key,R)),dn=Sa("settings",R)?{key:"settings",label:"Settings",href:`${Ht}/settings`}:null;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]}),!ee()&&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(k=>e.jsx("span",{className:"tag",children:k},k))]})]}),e.jsxs("div",{className:cs()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:s.dateRangeLabel}),!ee()&&(cs()?e.jsx(Yd,{projectName:d,running:Ft}):e.jsxs("div",{className:"flex items-center gap-3",children:[re?e.jsx("p",{className:"text-sm text-secondary",children:re}):null,e.jsx(We,{type:"button",variant:"outline",disabled:T.isPending||Ft||St,onClick:ps?()=>{p.refetch()}:X?S:De(Ps),children:T.isPending?"Starting…":Ft?"AI sweep running…":St?"Checking AI readiness…":ps?"Retry AI readiness":X?"Set up AI Visibility":"Run AI sweep"})]}))]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[Nn.map(k=>e.jsx(bs,{to:k.href,className:`project-subnav-link ${k.key===c?"project-subnav-link-active":""}`,"aria-current":k.key===c?"page":void 0,children:k.label},k.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(_g,{items:Fn,activeTab:c}),dn&&e.jsx(bs,{to:dn.href,className:`project-subnav-link ${c==="settings"?"project-subnav-link-active":""}`,"aria-current":c==="settings"?"page":void 0,children:dn.label},dn.key)]})]}),c==="portfolio"&&!ee()?e.jsx(Ep,{projectName:d,canEdit:u,queries:E.data??[],isQueryLoading:It,isQueryError:Gt,onRetryQueries:()=>{E.refetch()},publishedPlan:be,onCreateQueries:async k=>(await U.mutateAsync({projectName:d,queries:[...k]}),(await E.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{o({to:"/projects/$projectName",params:{projectName:d},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([p.refetch(),he.refetch()]).finally(()=>{o({to:"/projects/$projectName",params:{projectName:d}})})}},d):c==="overview"?ht?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"})]}):e.jsxs(e.Fragment,{children:[Ge?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(A,{type:"button",size:"sm",variant:"outline",onClick:()=>{he.refetch()},children:"Retry setup check"})]}):null,e.jsx(sg,{mode:kt,canEdit:u&&!ee()&&!jt&&!Ge,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(Zh,{projectName:s.project.name,competitorDomains:v,analyticsRevision:a})}),e.jsx(Fg,{model:s,sweepRunning:Ft,hasVisibilityBaseline:Yt}),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."})]})}),Yt?e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsx(nm,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:v},s.project.name),e.jsx("div",{className:"competitive-gaps",children:e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(ga,{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(ga,{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.jsx("section",{className:"page-section-divider",children:e.jsx(Fr,{window:ae,landscape:Je.data,pinnedFallback:Nt,canWrite:u,isEmbed:ee(),onWindowChange:le,onPin:u&&!ee()?it:void 0,onUnpin:u&&!ee()?Jt:void 0,onAddCompetitor:u&&!ee()?it:void 0,error:At,onRetry:ft?()=>{Je.refetch()}:void 0,isLoading:ft&&Je.isPending&&Je.data===void 0})}),e.jsxs(Ya,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[!ee()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(We,{type:"button",variant:"outline",size:"sm",onClick:()=>we(!pe),children:pe?"Done":"Manage queries"})}),!ee()&&pe&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[bt.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:bt.map(k=>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:k,children:k}),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 ${k}`,title:`Stop tracking "${k}"`,disabled:H!==null,onClick:()=>{Pe(k)},children:H===k?"Removing…":"Remove"})]},k))}):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:F,onChange:k=>te(k.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[F.split(`
|
|
9
|
+
`).filter(k=>k.trim()).length," to add"]}),e.jsx(We,{type:"button",size:"sm",disabled:!F.trim()||ie,onClick:De(at),children:ie?"Adding...":"Add queries"})]})]}),s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${O===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":O===void 0,onClick:()=>{W(void 0)},children:"All locations"}),s.project.locations.map(k=>e.jsx("button",{className:`filter-chip ${O===k.label?"filter-chip-active":""}`,type:"button","aria-pressed":O===k.label,onClick:()=>{W(k.label),_(!1)},children:k.label},k.label)),Qt&&e.jsx("button",{className:`filter-chip ${O===""?"filter-chip-active":""}`,type:"button","aria-pressed":O==="",onClick:()=>{W(""),_(!1)},children:"No location"}),Me.length>1&&O===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${ue?"filter-chip-active":""}`,type:"button","aria-pressed":ue,onClick:()=>_(k=>!k),title:"Side-by-side location comparison",children:"Compare"})]}),e.jsx(pm,{evidence:ut,compareLocations:ue})]}),e.jsxs(Ya,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:ee(),children:[e.jsx(bh,{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(ze,{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(k=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(Mn,{provider:k.provider}),k.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:k.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[k.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[k.cited," of ",k.total]})]},`${k.provider}::${k.model??"unknown"}`))})]})})]})]}),!ee()&&e.jsx(Ya,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(k=>e.jsx(Su,{run:k},k.id))})})]}),report:ys,reportState:Wt,onOpenSetup:ee()?void 0:()=>{o({to:"/projects/$projectName/portfolio",params:{projectName:d}})},onRetryReport:()=>{Te===2?Promise.all([Qe.refetch(),Ke.refetch()]):Ke.refetch()},onViewChange:k=>{Ve({scope:k.scope,...k.groupKey?{groupKey:k.groupKey}:{},queryClass:k.queryClass,...k.search?.trim()?{search:k.search.trim()}:{}})},onLoadMore:k=>{k===dt?.properties.nextCursor&&Qe.fetchNextPage()},onPropertyExpand:()=>{_e&&Ke.isError&&Ke.refetch(),Ue(!0)},onRetryEvidence:()=>{Ke.refetch()},renderPropertyLink:Te===2&&!ee()?({id:k,name:ce})=>e.jsx(bs,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:d,targetKey:k},className:"text-link hover:underline",children:ce}):void 0,isViewLoading:Qe.isPlaceholderData,isLoadingMore:Qe.isFetchingNextPage,isLoadMoreError:Qe.isFetchNextPageError,viewSearch:Ye.search??""},`${d}:${$e}`),kt.surface!=="simple-overview"?e.jsx("section",{className:"page-section-divider",children:e.jsx(Fr,{window:ae,landscape:Je.data,pinnedFallback:is,canWrite:u,isEmbed:ee(),onWindowChange:le,onPin:q&&u&&!ee()?$t:!Ce&&u&&!ee()?it:void 0,onUnpin:q||Ce||!u||ee()?void 0:Jt,onAddCompetitor:q&&u&&!ee()?$t:!Ce&&u&&!ee()?it:void 0,error:At,onRetry:ft?()=>{Je.refetch()}:void 0,isLoading:ft&&Je.isPending&&Je.data===void 0,scopeLabel:q?`${ye?.label??q} market`:Ce?"All markets":"Project-wide"})}):null]}):c==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(Rg,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(k,ce)=>{await _t(k,ce)},onRefresh:()=>{n()}}),e.jsx(Tg,{project:s.project,onSave:async k=>{await _t(s.project.name,k)}}),u&&!ee()?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."}),rt==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):rt==="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(A,{type:"button",size:"sm",variant:"outline",onClick:()=>{p.refetch()},children:"Retry"})]}):e.jsx(A,{type:"button",variant:"outline",onClick:()=>{o({to:"/projects/$projectName/portfolio",params:{projectName:d}})},children:Yo(kt.setupAction)})]}):null,e.jsx(Mg,{projectName:s.project.name}),e.jsx(Dg,{projectName:s.project.name}),u&&!ee()?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."}),N?e.jsxs(xe,{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(A,{type:"button",variant:"destructive",disabled:D,onClick:De(oe),children:D?"Deleting...":"Yes, delete project"}),e.jsx(A,{type:"button",variant:"outline",disabled:D,onClick:()=>$(!1),children:"Cancel"})]})]}):e.jsxs(We,{type:"button",variant:"outline",onClick:()=>$(!0),children:[e.jsx(wu,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):c==="report"?e.jsx(hg,{projectName:s.project.name}):c==="discovery"?e.jsx(lx,{projectName:d}):c==="technical-aeo"?e.jsx(Cu,{projectName:s.project.name,projectId:s.project.id,initialRunId:z.siteHealthRunId,onReleaseInitialRun:K}):c==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(Xx,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(Ox,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):c==="history"?e.jsx(xx,{projectName:s.project.name}):c==="activity"?e.jsx(Tm,{projectName:s.project.name}):c==="backlinks"?e.jsx(fh,{projectName:s.project.name}):c==="local"?e.jsx(Qm,{projectName:s.project.name,projectId:s.project.id}):c==="search-console"?e.jsx(Gg,{projectName:s.project.name}):null]})}export{sf as ProjectPage,qg as patchProjectDashboardCache};
|