@canonry/canonry 4.147.0 → 4.147.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/assets/assets/{AuditHistoryPanel-DiQ0Ynw5.js → AuditHistoryPanel-BbEZ_0W9.js} +1 -1
  2. package/assets/assets/{BacklinksPage-DLUQuPE_.js → BacklinksPage-B72RKxC-.js} +1 -1
  3. package/assets/assets/{ChartPrimitives-BoEy1qo7.js → ChartPrimitives-Cf-jQ3c8.js} +1 -1
  4. package/assets/assets/{HistoryPage-mYR2vk8n.js → HistoryPage-C2U1kxKw.js} +1 -1
  5. package/assets/assets/{MeasurementPropertyPage-BocyGHJN.js → MeasurementPropertyPage-ltcSZ0tw.js} +1 -1
  6. package/assets/assets/ProjectPage-ZcGjsDlb.js +12 -0
  7. package/assets/assets/{RunRow-Ct-A6H9e.js → RunRow-DxO-zxCm.js} +1 -1
  8. package/assets/assets/{RunsPage-CsDtq0Qw.js → RunsPage-B1ON2nQC.js} +1 -1
  9. package/assets/assets/{SettingsPage-BXwFGc1P.js → SettingsPage-Cp0bHFHk.js} +1 -1
  10. package/assets/assets/{TrafficPage-B2omyoI8.js → TrafficPage-QzitDjhV.js} +1 -1
  11. package/assets/assets/{TrafficSourceDetailPage-CoEqc6OJ.js → TrafficSourceDetailPage-BjfFyG2y.js} +1 -1
  12. package/assets/assets/{arrow-left-Dh0vsQxe.js → arrow-left-DJ8ZwUlj.js} +1 -1
  13. package/assets/assets/{extract-error-message-DvWJ0xRn.js → extract-error-message-CX8ZNJ8S.js} +1 -1
  14. package/assets/assets/{index-CXe6S1ey.css → index-D5NO3NEG.css} +1 -1
  15. package/assets/assets/{index-FE8JPHmT.js → index-DF8X6nM0.js} +73 -73
  16. package/assets/assets/{trash-2-D1_8ZseY.js → trash-2-UHAxuTT7.js} +1 -1
  17. package/assets/assets/{v2-overview-adapter-owDeFdUc.js → v2-overview-adapter-BHmxTmCf.js} +1 -1
  18. package/assets/index.html +2 -2
  19. package/dist/{chunk-4BL24FQA.js → chunk-2NTWZHNF.js} +352 -345
  20. package/dist/{chunk-ZDYS24LW.js → chunk-GNKVF6TZ.js} +6 -3
  21. package/dist/{chunk-DRDNHYIF.js → chunk-ZRUNFIGA.js} +61 -15
  22. package/dist/cli.js +199 -3
  23. package/dist/index.js +3 -3
  24. package/dist/{intelligence-service-7CGZ537D.js → intelligence-service-2E5YAXI3.js} +1 -1
  25. package/dist/mcp.js +1 -1
  26. package/package.json +7 -7
  27. package/assets/assets/ProjectPage-Q5wQ7nSW.js +0 -12
@@ -0,0 +1,12 @@
1
+ import{j as e,r as l,L as Ut,o as as,u as Le,p as tn,B as Wr,C as al,k as rl,l as il,D as ll}from"./vendor-tanstack-BjS7iY3g.js";import{c as ln,T as oe,t as ol,a as cl,S as dl,X as ul,C as Aa,u as Yr,b as ml,P as Is,B as k,h as hl,d as xl,e as pl,f as me,i as Z,g as it,j as Ie,I as Ze,k as zs,l as gl,m as Q,n as fl,o as bl,p as jl,q as yl,r as Jr,s as vl,v as Nl,w as xs,x as wl,y as Sl,z as ms,A as _t,D as Cl,E as tr,F as Xr,G as ct,H as Ra,J as kl,K as Pl,L as Al,M as Rl,N as sr,O as Ne,Q as Zr,R as $l,U as Vn,V as Il,W as Ll,Y as Ml,Z as Tl,_ as Dl,$ as El,a0 as ql,a1 as Ol,a2 as Fl,a3 as _l,a4 as Ul,a5 as Gl,a6 as Bl,a7 as zl,a8 as Vl,a9 as Kl,aa as bs,ab as Ql,ac as ei,ad as $n,ae as Hl,af as Wl,ag as Yl,ah as Jl,ai as In,aj as Xl,ak as Zl,al as eo,am as Ls,an as to,ao as so,ap as ga,aq as no,ar as ao,as as Ms,at as ti,au as si,av as ro,aw as ni,ax as io,ay as lo,az as oo,aA as co,aB as ai,aC as uo,aD as mo,aE as ho,aF as Js,aG as ps,aH as xo,aI as po,aJ as go,aK as fo,aL as ri,aM as bo,aN as jo,aO as yo,aP as vo,aQ as No,aR as ii,aS as wo,aT as $a,aU as So,aV as Co,aW as ko,aX as We,aY as Po,aZ as Ao,a_ as Ro,a$ as $o,b0 as Io,b1 as Lo,b2 as Mo,b3 as To,b4 as Do,b5 as Eo,b6 as qo,b7 as Oo,b8 as Fo,b9 as _o,ba as Uo,bb as Go,bc as Bo,bd as zo,be as Vo,bf as Ko,bg as Qo,bh as Ho,bi as Wo,bj as Yo,bk as Jo,bl as Xo,bm as Zo,bn as ec,bo as tc,bp as sc,bq as nc,br as ac,bs as rc,bt as ic,bu as lc,bv as oc,bw as cc,bx as dc,by as Kn,bz as uc,bA as mc,bB as nr,bC as hc,bD as xc,bE as pc,bF as gc,bG as fc,bH as bc,bI as jc,bJ as yc,bK as vc,bL as Nc,bM as wc,bN as Sc,bO as Cc,bP as li,bQ as kc,bR as Pc,bS as Ac,bT as Rc,bU as $c,bV as Ic,bW as ar,bX as Lc,bY as Qn,bZ as ft,b_ as Mc,b$ as Tc,c0 as Dc,c1 as Ec,c2 as qc,c3 as Oc,c4 as Fc,c5 as _c,c6 as oi,c7 as ci,c8 as Uc,c9 as di,ca as Gc,cb as ui,cc as Bc,cd as zc,ce as fn,cf as Vc,cg as Kc,ch as Qc,ci as rr}from"./index-DF8X6nM0.js";import{R as Hc}from"./RunRow-DxO-zxCm.js";import{C as Wc,R as sn,f as fa,a as Ht,b as Lt,c as Ln,d as gs,e as gt,g as pt,h as Qt,i as Ia,j as La,k as ns,o as Gt,p as Yc}from"./ChartPrimitives-Cf-jQ3c8.js";import{u as Jc,t as Xc,e as Zc,a as ir}from"./extract-error-message-CX8ZNJ8S.js";import{R as Ts,C as Ds,X as Es,Y as qs,T as Os,L as mi,A as ks,a as Ma,b as ed,d as Ta,e as td}from"./vendor-recharts-33ACLxsD.js";import{D as hi,C as sd,E as nd,T as ad}from"./trash-2-UHAxuTT7.js";import{A as rd}from"./AuditHistoryPanel-BbEZ_0W9.js";import{a as id,b as ld}from"./v2-overview-adapter-BHmxTmCf.js";import"./vendor-radix-DnzzbllM.js";import"./vendor-markdown-CpDJch4G.js";const od=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],xi=ln("circle-check",od);const cd=[["path",{d:"M5 12h14",key:"1ays0h"}]],dd=ln("minus",cd);const ud=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]],md=ln("scan-search",ud);const hd=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],xd=ln("unplug",hd);const pd=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],gd=ln("upload",pd);function An(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 fd(t,s){return s<=0?null:Math.round((t-s)/s*100)}function Hn(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${An(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${An(t.prior)} ${s})`:`Flat ${n} (${An(t.prior)} ${s})`}const pi=30;function lr(t){return Math.round(t*10)/10}function bd(t){return t.prior>=pi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${lr(t.deltaAbs)} vs ${lr(t.prior)}`}function jd(t,s,n){return t.prior>=pi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${An(Math.round(t.deltaAbs))} ${s} ${n}`}const yd=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function gi(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function fi(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 bi(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(gi).map(fi).filter(Boolean)):new Set}function ji(t,s){const n=gi(t).map(fi).filter(Boolean).filter(a=>!yd.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function vd(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Nd(t,s){const n=bi(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,r=[];for(const i of s){if(i.category!=="content"){r.push(i);continue}const o=ji(vd(i),n);!o||a.has(o)||(a.add(o),r.push(i))}return r}function wd(t){const s=bi(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const i=ji(r.query,s);return!i||a.has(i)?!1:(a.add(i),!0)})}function ba({state:t,label:s}){return e.jsx(oe,{tone:cl(t),children:s??ol(t)})}const Et=25;function Sd(t){return t.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function yi(t){let s=t;try{s=decodeURIComponent(t.replace(/\+/g," "))}catch{}let n="";const a=t.indexOf("?");return a>=0&&new URLSearchParams(t.slice(a+1)).forEach((i,o)=>{n+=` ${o} ${i}`}),`${t} ${s}${n}`}function Cd(t,s=36,n=18){const a=[...t];return a.length<=s+n+1?t:`${a.slice(0,s).join("")}…${a.slice(-n).join("")}`}function Xs({value:t,headLength:s,tailLength:n,className:a,title:r}){const i=Cd(t,s,n);return e.jsx("span",{className:a,title:r??t,children:i===t?t:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sr-only",children:t}),e.jsx("span",{"aria-hidden":"true",children:i})]})})}function nn({rows:t,getSearchText:s,pageSize:n=Et}){const[a,r]=l.useState(""),[i,o]=l.useState(1),u=l.useMemo(()=>Sd(a),[a]),d=l.useMemo(()=>u.length===0||!s?t:t.filter(b=>{const p=s(b).toLocaleLowerCase();return u.every(L=>p.includes(L))}),[s,t,u]),h=Math.max(1,Math.ceil(d.length/n)),x=Math.min(Math.max(1,i),h),c=(x-1)*n,y=l.useMemo(()=>d.slice(c,c+n),[d,n,c]),N=l.useCallback(b=>{r(b),o(1)},[]),f=l.useCallback(b=>{o(Math.max(1,b))},[]);return{query:a,setQuery:N,page:x,setPage:f,rows:y,filteredRows:d,totalRows:d.length,totalPages:h,pageSize:n,rangeStart:d.length===0?0:c+1,rangeEnd:c+y.length,hasQuery:a.trim().length>0}}function As({value:t,onChange:s,label:n,placeholder:a="Filter rows",className:r}){return e.jsxs("div",{className:`relative ${r??""}`,children:[e.jsx(dl,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted"}),e.jsx("input",{type:"search",value:t,onChange:i=>s(i.target.value),"aria-label":n,placeholder:a,autoComplete:"off",spellCheck:!1,className:"h-9 w-full rounded-md border border-default bg-surface/50 pl-9 pr-9 text-sm text-strong placeholder:text-muted outline-none transition focus:border-mono-500 focus:ring-1 focus:ring-mono-500 [&::-webkit-search-cancel-button]:appearance-none"}),t.trim().length>0?e.jsx("button",{type:"button",onClick:()=>s(""),"aria-label":`Clear ${n.toLocaleLowerCase()}`,className:"absolute right-2 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-muted transition-colors hover:bg-surface-hover hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:e.jsx(ul,{"aria-hidden":"true",className:"size-3.5"})}):null]})}function fs({page:t,pageSize:s=Et,visibleRows:n,totalRows:a,hasNextPage:r,onPageChange:i,itemLabel:o="rows",className:u,disabled:d=!1}){if(n===0)return null;const h=(t-1)*s+1,x=h+n-1,c=a===void 0?void 0:Math.max(1,Math.ceil(a/s)),y=r??(c!==void 0&&t<c),N=t>1||y;return e.jsxs("div",{className:`mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-secondary ${u??""}`,children:[e.jsxs("p",{className:"tabular-nums",children:[h.toLocaleString("en-US"),"–",x.toLocaleString("en-US"),a===void 0?`${y?"+":""} ${o}`:` of ${a.toLocaleString("en-US")} ${o}`]}),N?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>i(t-1),disabled:d||t<=1,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:[e.jsx(Wc,{"aria-hidden":"true",className:"size-3.5"}),"Previous"]}),e.jsx("span",{className:"tabular-nums",children:c===void 0?`Page ${t}`:`Page ${t} of ${c}`}),e.jsxs("button",{type:"button",onClick:()=>i(t+1),disabled:d||!y,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:["Next",e.jsx(Aa,{"aria-hidden":"true",className:"size-3.5"})]})]}):null]})}function or({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"},i=n.length-1,o=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(n[i].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),d=n.map((h,x)=>{const c=new Date(h.createdAt).toLocaleDateString();return`${x===i?"Latest run, ":""}${c}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${d}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:o}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,x)=>{const c=!!(h.model&&x>0&&n[x-1]?.model&&n[x-1].model!==h.model),y=x===i;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${c?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${y?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,c?"model changed":null,y?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function ja(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const i=s.get(r.createdAt);i?i.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:i}])=>({runId:i,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const kd=320;function Pd(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function cr(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 dr(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 ur(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,i=t[t.length-2].citationState;if(i!=="cited"&&r==="cited")return`Newly ${n}`;if(i==="cited"&&r!=="cited")return"Lost since last run";let o=0;for(let u=t.length-1;u>=0&&t[u].citationState===r;u--)o++;return r==="cited"?o<=1?`${a} in latest run`:`${a} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function Ad(t,s){return t.map(n=>vi(n,s))}function vi(t,s){return s==="citations"?t:{...t,citationState:cr(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:cr(n,s)}))}}function mr(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,i=t.length>=2?t[t.length-2].citationState:null,o=r==="cited"||r==="emerging",u=i==="cited"||i==="emerging";return r==="lost"||i!==null&&u&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||i!==null&&!u&&o?{key:s,label:`New ${n}`,tone:"positive"}:i===null&&o?{key:s,label:`First ${n}`,tone:"positive"}:o?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Rd(t){const s=ja(Ad(t,"mentions")),n=ja(t);return[mr(s,"mentions"),mr(n,"citations")]}function $d({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 hr({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Rd(t).map(s=>e.jsx($d,{signal:s},s.key))})}function Id({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Yr(),[r,i]=l.useState(new Set),[o,u]=l.useState("mentions"),[d,h]=l.useState(n),x=l.useMemo(()=>{const E=new Map;for(const q of t){const $=q.query,g=s?q.location??null:null,v=s?JSON.stringify([$,g]):$,w=E.get(v)??{key:v,phrase:$,location:g,items:[],rawItems:[]};w.items.push(vi(q,o)),w.rawItems.push(q),E.set(v,w)}return[...E.values()]},[t,o,s]),c=nn({rows:x,getSearchText:Pd}),y=c.rows.map(E=>E.key),N=y.length>0&&y.every(E=>r.has(E)),f=E=>{i(q=>{const $=new Set(q);return $.has(E)?$.delete(E):$.add(E),$})},b=o==="mentions"?"mentioned":"cited",p=o==="mentions"?"Mention History":"Citation History",L=o==="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":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="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":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="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:o==="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:()=>{i(E=>{const q=new Set(E);for(const $ of y)N?q.delete($):q.add($);return q})},children:N?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":d==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":d==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),x.length>0?e.jsx(As,{value:c.query,onChange:c.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"mb-3 max-w-md"}):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:p}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:c.rows.map(({key:E,phrase:q,location:$,items:g,rawItems:v})=>{const w=r.has(E),ee=g.map(S=>S.citationState),W=ee.includes("cited")?"cited":ee.includes("emerging")?"emerging":ee.includes("lost")?"lost":ee.every(S=>S==="pending")?"pending":"not-cited",A=ja(g),j=g.filter(S=>S.citationState===ml.cited||S.citationState==="emerging").length,D=ur(A,o);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:()=>f(E),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),f(E))},tabIndex:0,role:"button","aria-expanded":w,children:[e.jsx("td",{children:e.jsx(Aa,{size:14,className:`transition-transform duration-150 text-muted ${w?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:q}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:$??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:g.map(S=>e.jsx(Is,{provider:S.provider},S.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ba,{state:W,label:dr(W,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${j} of ${g.length} engines ${L}`,children:[j,"/",g.length]})]})}),e.jsx("td",{children:e.jsx(or,{history:A})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:D}),e.jsx(hr,{items:v})]}),e.jsx("td",{})]}),w&&g.map((S,V)=>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(Is,{provider:S.provider})}),e.jsx("td",{children:e.jsx(ba,{state:S.citationState,label:dr(S.citationState,o)})}),e.jsx("td",{children:e.jsx(or,{history:S.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ur(S.runHistory,o)}),e.jsx(hr,{items:[v[V]??S]})]}),e.jsx("td",{children:e.jsx(k,{variant:"ghost",size:"sm",type:"button",onClick:pe=>{pe.stopPropagation(),a(S.id)},children:"View"})})]}),d==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Td,{item:S,onViewFull:()=>a(S.id)})})]})]},S.id))]},E)})})]})}),c.totalRows===0&&c.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(fs,{page:c.page,pageSize:c.pageSize,visibleRows:c.rows.length,totalRows:c.totalRows,onPageChange:c.setPage,itemLabel:c.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",b==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Ld(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...t.competitorDomains.flatMap(r=>{const i=xl(r);return i.length>=4?[i]:[]}),...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 Md(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 Td({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}=Md(t.answerSnippet,kd),i=Ld(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:hl(a,i)}),(t.citedDomains.length>0||t.competitorDomains.length>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(o=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-bg-elevated/60 px-2 py-0.5 text-[11px] text-neutral",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>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:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.competitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function Dd({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const r=s!=null,i=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),i&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const u=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),d=[r?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",u?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:d,onClick:r?()=>s(o.domain):void 0,title:r?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:o.domain}),e.jsx("td",{children:e.jsx(oe,{tone:pl(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),i&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"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","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:h=>{h.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function bn({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})]})}const Ed=6,Fs="__other__",Rs="_socialTotal";function qd(t,s=Ed){const n=new Map;for(const x of t)n.set(x.source,(n.get(x.source)??0)+x.sessions);const a=[...n.entries()].sort((x,c)=>c[1]!==x[1]?c[1]-x[1]:x[0].localeCompare(c[0])),r=a.slice(0,s),i=new Set(r.map(([x])=>x)),o=Math.max(0,a.length-s),u=new Map;for(const x of t){let c=u.get(x.date);c||(c={date:x.date,[Rs]:0},u.set(x.date,c));const y=i.has(x.source)?x.source:Fs;c[y]=(c[y]??0)+x.sessions,c[Rs]=(c[Rs]??0)+x.sessions}const d=[...u.values()].sort((x,c)=>String(x.date).localeCompare(String(c.date))),h=r.map(([x])=>x);return o>0&&h.push(Fs),{data:d,sources:h,otherCount:o}}function $s(t){return t.replace(/\+/g," ")}function Ni(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const xr="_totalSessions",pr="_organicSessions";function Od(t,s){const n=new Map;for(const o of s)n.set(o.date,{[xr]:o.sessions,[pr]:o.organicSessions});for(const o of t.days){let u=n.get(o.date);u||(u={[xr]:0,[pr]:0},n.set(o.date,u));for(const d of o.bySource)u[d.source]=(u[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([o],[u])=>o.localeCompare(u)).map(([o,u])=>({date:o,...u})),r=a.map(o=>o.date),i=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:i}}const Fd=["7d","30d","90d","all"],es=pt,ya=gt.textDim,wi=gt.textFaint,Vs=25;function _d(t){return yi(t.landingPage)}const Ud=25,Wn={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function jn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Si(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 Gd({projectName:t}){const{data:s,isLoading:n,isError:a}=Jc(t);if(n)return e.jsx(me,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(me,{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."," ",!Z()&&e.jsx(Ut,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(me,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!Z()&&e.jsxs(e.Fragment,{children:[e.jsx(Ut,{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(me,{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(i=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:i.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(oe,{tone:Xc(i.status),children:i.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:i.lastSyncedAt?Si(i.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:Z()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Ut,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:i.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},i.id))})]})})]})}function Bd({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Gd,{projectName:t}),e.jsx(zd,{projectName:t})]})}function zd({projectName:t}){const s=as(),[n,a]=l.useState(null),[r,i]=l.useState(null),[o,u]=l.useState(!0),[d,h]=l.useState(!1),[x,c]=l.useState(!1),[y,N]=l.useState(null),[f,b]=l.useState(null),[p,L]=l.useState("sessions"),[E,q]=l.useState("desc"),[$,g]=l.useState("sessions"),[v,w]=l.useState("desc"),[ee,W]=l.useState("sessions"),[A,j]=l.useState("desc"),[D,S]=l.useState("sessions"),[V,pe]=l.useState("desc"),[ne,X]=l.useState(Wn),[te,ce]=l.useState([]),[B,G]=l.useState([]),[P,re]=l.useState(!1),[le,C]=l.useState("30d");async function U(F){u(!0),N(null);try{const Ce=await s.fetchQuery({...gl({client:Q,path:{name:t}}),staleTime:zs});if(F.current)return;if(a(Ce),!Ce.connected){i(null),X(Wn),ce([]),G([]),u(!1);return}const de=le==="all"?void 0:le,[ve,Ke,Wt,st]=await Promise.all([s.fetchQuery({...fl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).then(kt=>kt),s.fetchQuery({...bl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).catch(()=>Wn),s.fetchQuery({...jl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).catch(()=>[]),s.fetchQuery({...yl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).catch(()=>[])]);if(F.current)return;i(ve),X(Ke),ce(Wt),G(st),u(!1)}catch(Ce){if(F.current)return;N(Ce instanceof Error?Ce.message:"Failed to load GA4 data"),u(!1)}}l.useEffect(()=>{const F={current:!1};return U(F),()=>{F.current=!0}},[t,le,s]);async function se(){h(!0),N(null),b(null);try{const F=await Jr(t);b(`Synced ${F.rowCount.toLocaleString()} page rows, ${F.aiReferralCount.toLocaleString()} AI and ${F.socialReferralCount.toLocaleString()} social referral rows (${F.days} days)`),await it(s,"ga"),await U({current:!1})}catch(F){N(F instanceof Error?F.message:"Sync failed")}finally{h(!1)}}async function M(){c(!0),N(null),b(null);try{await vl(t),await it(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),i(null),b("GA4 disconnected")}catch(F){N(F instanceof Error?F.message:"Disconnect failed")}finally{c(!1)}}function z(F){p===F?q(Ce=>Ce==="desc"?"asc":"desc"):(L(F),q("desc"))}function we(F){$===F?w(Ce=>Ce==="desc"?"asc":"desc"):(g(F),w("desc"))}function Oe(F){ee===F?j(Ce=>Ce==="desc"?"asc":"desc"):(W(F),j("desc"))}const K=l.useMemo(()=>r?.topPages?[...r.topPages].sort((F,Ce)=>{const de=F[p],ve=Ce[p];return typeof de=="string"&&typeof ve=="string"?E==="asc"?de.localeCompare(ve):ve.localeCompare(de):E==="asc"?de-ve:ve-de}):[],[r?.topPages,p,E]),ge=l.useMemo(()=>r?.aiReferrals?[...r.aiReferrals].sort((F,Ce)=>{const de=F[$],ve=Ce[$];return typeof de=="string"&&typeof ve=="string"?v==="asc"?de.localeCompare(ve):ve.localeCompare(de):v==="asc"?de-ve:ve-de}):[],[r?.aiReferrals,$,v]),Te=l.useMemo(()=>r?.aiReferralLandingPages?[...r.aiReferralLandingPages].sort((F,Ce)=>{const de=F[D],ve=Ce[D];return typeof de=="string"&&typeof ve=="string"?V==="asc"?de.localeCompare(ve):ve.localeCompare(de):V==="asc"?de-ve:ve-de}):[],[r?.aiReferralLandingPages,D,V]),je=nn({rows:Te,getSearchText:_d,pageSize:Ud}),Be=je.totalRows>0?`${je.totalRows.toLocaleString()} ${je.hasQuery?je.totalRows===1?"match":"matches":je.totalRows===1?"row":"rows"}`:je.hasQuery&&(r?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function et(F){je.setPage(1),D===F?pe(Ce=>Ce==="desc"?"asc":"desc"):(S(F),pe("desc"))}const Me=l.useMemo(()=>r?.socialReferrals?[...r.socialReferrals].sort((F,Ce)=>{const de=F[ee],ve=Ce[ee];return typeof de=="string"&&typeof ve=="string"?A==="asc"?de.localeCompare(ve):ve.localeCompare(de):A==="asc"?de-ve:ve-de}):[],[r?.socialReferrals,ee,A]),{socialChartData:J,socialChartSources:De,socialOtherCount:xe}=l.useMemo(()=>{const F=qd(B);return{socialChartData:F.data,socialChartSources:F.sources,socialOtherCount:F.otherCount}},[B]),{chartData:Qe,chartSources:O,dateRange:_}=l.useMemo(()=>{const F=Od(ne,te);return{chartData:F.data,chartSources:F.sources,dateRange:F.dateRange}},[ne,te]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return Z()?e.jsx(me,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Vd,{projectName:t,onConnected:()=>{(async()=>(await it(s,"ga"),await U({current:!1})))()}});const fe=r?.organicSharePctDisplay??"0%",Ee=r?.channelBreakdown?.organic.sharePctDisplay??fe,Ue=r?.channelBreakdown?.organic.sessions??r?.totalOrganicSessions??0,Ve=r?.aiSessionsDeduped??0,Nt=r?.channelBreakdown?.ai.sessions??r?.aiSessionsBySession??0,bt=r?.channelBreakdown?.ai.sharePctDisplay??r?.aiSharePctBySessionDisplay??"0%",ke=r?.paidAiSessionsBySession??0,Fe=r?.paidAiSharePctBySessionDisplay??"0%",qt=r?new Set(r.aiReferrals.map(F=>F.source.toLowerCase())).size:0,tt=ge[0]??null,dt=r?.totalDirectSessions??0,Ye=r?.directSharePctDisplay??"0%",wt=r?.channelBreakdown?.direct.sessions??dt,St=r?.channelBreakdown?.direct.sharePctDisplay??Ye,Re=r?.channelBreakdown?.other.sessions??r?.otherSessions??0,Ae=r?.channelBreakdown?.other.sharePctDisplay??r?.otherSharePctDisplay??"0%",lt=r?.socialSessions??0,Ge=r?.socialSharePctDisplay??"0%",Ot=r?.channelBreakdown?.social.sessions??lt,Ct=r?.channelBreakdown?.social.sharePctDisplay??Ge,Je=r?new Set(r.socialReferrals.map(F=>F.source.toLowerCase())).size:0,He=Me[0]??null;return e.jsxs(e.Fragment,{children:[y&&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:y}),f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:f}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:n.clientEmail})]})]})]}),!Z()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(k,{variant:"outline",size:"sm",disabled:d,onClick:Ie(se),children:[e.jsx(sn,{className:`w-3.5 h-3.5 mr-1.5 ${d?"animate-spin":""}`}),d?"Syncing…":"Sync"]}),e.jsxs(k,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Ie(M),children:[e.jsx(xd,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsxs("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. Sessions and users are summed across the selected period.${r?.periodStart&&r?.periodEnd?` Data available: ${new Date(r.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(r.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:Fd.map(F=>e.jsx("button",{type:"button","aria-pressed":le===F,className:`segmented-option ${le===F?"segmented-option-active":""}`,onClick:()=>C(F),children:F==="all"?"All":F},F))})]}),r?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Yn,{value:jn(r.totalSessions),label:"Total Sessions",subtitle:r.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Yn,{value:jn(r.totalOrganicSessions),label:"Organic Sessions",subtitle:`${fe} of total`,tone:"positive"}),e.jsx(Yn,{value:jn(r.totalUsers),label:"Total Users",subtitle:r.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."}),!Z()&&e.jsxs(k,{variant:"outline",size:"sm",disabled:d,onClick:Ie(se),children:[e.jsx(sn,{className:`w-3.5 h-3.5 mr-1.5 ${d?"animate-spin":""}`}),"Sync from GA4"]})]})]}),r&&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."})]})]}),_&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(_.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(_.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),Qe.length>0&&e.jsxs(me,{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:O.length>0?"AI vs. total sessions":"All sessions (baseline)"}),O.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),O.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(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:Qe,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Es,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:Ht},tickFormatter:fa}),e.jsx(qs,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Os,{...gs,labelFormatter:Ln,formatter:(F,Ce)=>{const de=typeof F=="number"?F.toLocaleString():String(F??0),ve=String(Ce??"");return ve==="_totalSessions"?[de,"Total Sessions"]:ve==="_organicSessions"?[de,"Organic Sessions"]:[de,ve]}}),e.jsx(mi,{wrapperStyle:{fontSize:11,color:gt.text},formatter:F=>F==="_totalSessions"?"Total Sessions":F==="_organicSessions"?"Organic Sessions":F}),e.jsx(ks,{type:"monotone",dataKey:"_totalSessions",stroke:gt.textFaint,fill:gt.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),O.map((F,Ce)=>e.jsx(ks,{type:"monotone",dataKey:F,stackId:"ai",stroke:es[Ce%es.length],fill:es[Ce%es.length],fillOpacity:.4,strokeWidth:1.5},F))]})})})]}),e.jsxs(me,{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:"Channel breakdown"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Dt,{label:"Organic",value:Ee,hint:`${Ue.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(Dt,{label:"Social",value:Ct,hint:`${Ot.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(Dt,{label:"Direct",value:St,hint:`${wt.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(Dt,{label:"Known AI referrers (lower bound)",value:bt,hint:ke>0?`${Nt.toLocaleString()} sessions · ${ke.toLocaleString()} paid`:`${Nt.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(Dt,{label:"Other channels",value:Ae,hint:`${Re.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."})]}),tt&&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:tt.source})," via ",tt.medium,", accounting for ",tt.sessions.toLocaleString()," sessions.",ke>0&&e.jsxs("span",{children:[" Paid AI: ",ke.toLocaleString()," sessions (",Fe,")."]})]})]}),e.jsxs(me,{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:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-muted",children:r.aiReferrals.length>0?`${qt} unique sources, ${r.aiReferrals.length} rows`:"No source rows"})]}),r.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(vt,{label:"Source",sortKey:"source",current:$,dir:v,onSort:we,align:"left"}),e.jsx(vt,{label:"Medium",sortKey:"medium",current:$,dir:v,onSort:we,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(vt,{label:"Sessions",sortKey:"sessions",current:$,dir:v,onSort:we,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:ge.map(F=>e.jsx(Qd,{referral:F,totalSessions:Ve},`${F.source}:${F.medium}:${F.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(me,{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:"Known AI referrers by landing page"})]}),e.jsx("p",{className:"text-xs text-muted",children:Be})]}),r.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(As,{value:je.query,onChange:je.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),je.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(vt,{label:"Landing Page",sortKey:"landingPage",current:D,dir:V,onSort:et,align:"left"}),e.jsx(vt,{label:"Source",sortKey:"source",current:D,dir:V,onSort:et,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(vt,{label:"Sessions",sortKey:"sessions",current:D,dir:V,onSort:et,align:"right"})]})}),e.jsx("tbody",{children:je.rows.map(F=>e.jsx(Hd,{row:F},`${F.landingPage}:${F.source}:${F.medium}:${F.sourceDimension}`))})]})}),e.jsx(fs,{page:je.page,pageSize:je.pageSize,visibleRows:je.rows.length,totalRows:je.totalRows,onPageChange:je.setPage,itemLabel:je.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:()=>je.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 landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),r&&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."})]})]}),J.length>0&&e.jsxs(me,{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:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions over time"})]}),xe>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",De.length-1," sources · ",xe," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:J,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Es,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:Ht},tickFormatter:fa}),e.jsx(qs,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Os,{...gs,labelFormatter:Ln,formatter:(F,Ce)=>{const de=typeof F=="number"?F.toLocaleString():String(F??0),ve=String(Ce??"");if(ve===Rs)return[de,"Total Social"];if(ve===Fs){const Ke=`Other (${xe} source${xe===1?"":"s"})`;return[de,Ke]}return[de,$s(ve)]}}),e.jsx(ks,{type:"monotone",dataKey:Rs,stroke:wi,fill:gt.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),De.map((F,Ce)=>{const ve=F===Fs?ya:es[Ce%es.length];return e.jsx(ks,{type:"monotone",dataKey:F,stackId:"social",stroke:ve,fill:ve,fillOpacity:.4,strokeWidth:1.5},F)})]})})}),e.jsx(Yd,{sources:De,otherCount:xe})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(me,{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:"Social media visits"})]}),r.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Dt,{label:"Social Sessions",value:jn(lt),hint:`${lt.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Dt,{label:"Share of Traffic",value:Ge,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Dt,{label:"Platforms",value:String(Je),hint:`${r.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),He&&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:`${He.source} via ${He.medium}`,children:Ni($s(He.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:He.medium,children:["via ",$s(He.medium)," · ",He.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(Dt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Dt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Dt,{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."})]})]})]}),e.jsxs(me,{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:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-muted",children:r.socialReferrals.length>0?Me.length>Vs&&!P?`Top ${Vs} of ${Me.length}`:`${Me.length} rows`:"No source rows"})]}),r.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(vt,{label:"Source",sortKey:"source",current:ee,dir:A,onSort:Oe,align:"left"}),e.jsx(vt,{label:"Medium",sortKey:"medium",current:ee,dir:A,onSort:Oe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(vt,{label:"Sessions",sortKey:"sessions",current:ee,dir:A,onSort:Oe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(vt,{label:"Users",sortKey:"users",current:ee,dir:A,onSort:Oe,align:"right"})]})}),e.jsx("tbody",{children:(P?Me:Me.slice(0,Vs)).map(F=>e.jsx(Wd,{referral:F,totalSessions:lt},`${F.source}:${F.medium}:${F.channelGroup}`))})]})}),Me.length>Vs&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>re(F=>!F),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:P?`Show top ${Vs}`:`Show all ${Me.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."})]})]})]})]})]}),r&&r.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("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(vt,{label:"Landing Page",sortKey:"landingPage",current:p,dir:E,onSort:z,align:"left"}),e.jsx(vt,{label:"Sessions",sortKey:"sessions",current:p,dir:E,onSort:z,align:"right"}),e.jsx(vt,{label:"Organic",sortKey:"organicSessions",current:p,dir:E,onSort:z,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:K.map(F=>e.jsx(Kd,{page:F},F.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:r?.lastSyncedAt?`Last synced ${Si(r.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:r?`${r.topPages.length} pages · ${r.aiReferrals.length} AI rows · ${r.socialReferrals.length} social rows`:""})]})]})}function Vd({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,i]=l.useState(null),[o,u]=l.useState(null),[d,h]=l.useState(!1),[x,c]=l.useState(null),y=l.useRef(null),N=l.useCallback(b=>{const p=b.target.files?.[0];if(!p)return;c(null),i(p.name);const L=new FileReader;L.onload=()=>{const E=L.result;try{const q=JSON.parse(E);if(!q.client_email||!q.private_key){c("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(E)}catch{c("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},L.onerror=()=>{c("Failed to read file."),u(null)},L.readAsText(p)},[]);async function f(){if(c(null),!n.trim()){c("Property ID is required.");return}if(!o){c("Please upload a service account key file.");return}h(!0);try{await Nl(t,{propertyId:n.trim(),keyJson:o});try{await Jr(t)}catch{}s()}catch(b){c(b instanceof Error?b.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(me,{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."}),x&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:x}),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:b=>a(b.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:y,type:"file",accept:".json,application/json",onChange:N,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>y.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(gd,{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(k,{variant:"default",size:"sm",disabled:d||!n.trim()||!o,onClick:Ie(f),children:d?"Connecting & syncing…":"Connect GA4"})]})}function vt({label:t,sortKey:s,current:n,dir:a,onSort:r,align:i}){const o=n===s;return e.jsx("th",{className:`py-1 ${i==="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}${o?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Ci={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Yn({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 ${Ci[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Dt({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 ${Ci[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Kd({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 ki={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Pi={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 Qd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=ki[t.sourceDimension]??t.sourceDimension,r=Pi[t.sourceDimension]??"",i=t.trafficClass==="paid"?"Paid":"Organic",o=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:o,children:i})}),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 Hd({row:t}){const s=ki[t.sourceDimension]??t.sourceDimension,n=Pi[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(Xs,{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 Wd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=$s(t.source),i=$s(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:i}),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,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function Yd({sources:t,otherCount:s}){const n=[{key:Rs,color:wi,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Fs)n.push({key:Fs,color:ya,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const i=$s(r);n.push({key:r,color:es[a%es.length]??ya,label:Ni(i,32),tooltip:i})}}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 Jd(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 Xd=["7d","30d","90d","all"],yn=500,Xt=25,Zd="canonry:google-oauth-complete";function gr(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function fr(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 br(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function eu({projectName:t,refreshNonce:s}){const n=as(),[a,r]=l.useState(!1),[i,o]=l.useState([]),[u,d]=l.useState([]),[h,x]=l.useState([]),[c,y]=l.useState(null),[N,f]=l.useState([]),[b,p]=l.useState([]),[L,E]=l.useState(null),[q,$]=l.useState(""),[g,v]=l.useState(""),[w,ee]=l.useState("30"),[W,A]=l.useState(!1),[j,D]=l.useState("30d"),[S,V]=l.useState({startDate:"",endDate:"",query:"",page:""}),[pe,ne]=l.useState(0),[X,te]=l.useState(!1),[ce,B]=l.useState(0),[G,P]=l.useState(!1),[re,le]=l.useState(""),[C,U]=l.useState(!0),[se,M]=l.useState(!1),[z,we]=l.useState(!1),[Oe,K]=l.useState(!1),[ge,Te]=l.useState(!1),[je,Be]=l.useState(!1),[et,Me]=l.useState(!1),[J,De]=l.useState(null),[xe,Qe]=l.useState(!1),[O,_]=l.useState(!1),[fe,Ee]=l.useState(null),[Ue,Ve]=l.useState(null),[Nt,bt]=l.useState([]),[ke,Fe]=l.useState(new Set),[qt,tt]=l.useState({}),[dt,Ye]=l.useState(new Set),[wt,St]=l.useState(""),[Re,Ae]=l.useState(null),[lt,Ge]=l.useState(""),[Ot,Ct]=l.useState(!1),[Je,He]=l.useState(!1),[F,Ce]=l.useState(!1),[de,ve]=l.useState(!1),[Ke,Wt]=l.useState("indexed"),[st,kt]=l.useState(null),rs=!!(S.query.trim()||S.page.trim()||st),R=st!==null,be=l.useMemo(()=>{if(!st)return h;const{key:m,dir:T}=st;return[...h].sort((ae,ue)=>{const $e=m===xs.CTR?Number.isFinite(ae.ctr)?ae.ctr:0:ae[m],qe=m===xs.CTR?Number.isFinite(ue.ctr)?ue.ctr:0:ue[m];return T==="asc"?$e-qe:qe-$e})},[h,st]),ye=nn({rows:be,pageSize:Et}),Pt=G?ye.rows:be,nt=nn({rows:(fe??[]).filter(m=>m.path.toLowerCase().includes(wt.trim().toLowerCase())),pageSize:Et}),[At,dn]=l.useState([]),[jt,is]=l.useState(null),[En,un]=l.useState(1),ls=l.useMemo(()=>{if(At.length<2)return null;const m=At[At.length-1],T=At[At.length-2];return{indexed:m.indexed-T.indexed,notIndexed:m.notIndexed-T.notIndexed}},[At]);l.useEffect(()=>{un(1)},[J,Ke,jt]);const js=l.useMemo(()=>jt?(J?.reasonGroups??[]).find(m=>m.reason===jt):void 0,[J,jt]),Us=l.useMemo(()=>J?Ke==="indexed"?J.indexed:Ke==="deindexed"?J.deindexed:Ke==="notIndexed"?jt?js?.urls??[]:(J.reasonGroups??[]).length===0?J.notIndexed:[]:[]:[],[J,Ke,jt,js]),qn=Math.max(1,Math.ceil(Us.length/Xt)),mn=Math.min(Math.max(1,En),qn),ut=(mn-1)*Xt,ys=l.useMemo(()=>J?.indexed.slice(ut,ut+Xt)??[],[J,ut]),On=l.useMemo(()=>J?.notIndexed.slice(ut,ut+Xt)??[],[J,ut]),Fn=l.useMemo(()=>J?.deindexed.slice(ut,ut+Xt)??[],[J,ut]),I=l.useMemo(()=>(js?.urls??[]).slice(ut,ut+Xt),[js,ut]),[Y,he]=l.useState(!1),[ie,H]=l.useState(null),[Se,Mt]=l.useState(null),[ot,yt]=l.useState(null);function Yt(m,T){const ae=Zc(m),ue=Jd(ae);ue?(Mt(ue),H(null)):(Mt(null),H(ae.message||T))}const at=i.find(m=>m.connectionType==="gsc"),os=(at?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),_n=Nt.length>0?Nt:(fe??[]).map(m=>m.path),Va=_n.filter(m=>fe?.some(T=>T.path===m&&T.isSitemapsIndex)).length,Qi=Va===1?"Resubmit sitemap index":Va>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Hi=h.length>0||N.length>0||b.length>0,Un=wl(),Gn=Sl();async function Ka(m,T=!1){if(!m){d([]),$("");return}we(!0);try{const{sites:ae}=await n.fetchQuery({...ql({client:Q,path:{name:t}}),staleTime:T?0:ct});d(ae),$(m.propertyId??ae[0]?.siteUrl??""),Mt(null)}catch(ae){d([]),Yt(ae,"Failed to load Search Console properties")}finally{we(!1)}}async function Gs(m){Te(!0);const T=m??pe;try{const ae=rs?yn:Et,ue=rs?0:T,$e={limit:String(ae)};S.startDate&&($e.startDate=S.startDate),S.endDate&&($e.endDate=S.endDate),S.query&&($e.query=S.query),S.page&&($e.page=S.page),ue>0&&($e.offset=String(ue)),j&&j!=="all"&&!S.startDate&&($e.window=j);const qe=await n.fetchQuery({...kl({client:Q,path:{name:t},query:$e}),staleTime:ct}),_e=qe.rows;rs?(te(!1),x(_e),B(_e.length),P(!0)):(te(ue+_e.length<qe.totalMatching),x(_e),B(0),P(!1))}catch(ae){x([]),te(!1),B(0),H(ae instanceof Error?ae.message:"Failed to load GSC performance data")}finally{Te(!1)}}async function Bn(){try{const m={};S.startDate&&(m.startDate=S.startDate),S.endDate&&(m.endDate=S.endDate),j&&j!=="all"&&!S.startDate&&(m.window=j);const T=await n.fetchQuery({...Pl({client:Q,path:{name:t},query:m}),staleTime:ct});y(T)}catch{y(null)}}async function hn(m=!1){Be(!0);try{const T=re.trim()||void 0,ae={limit:"20"};T&&(ae.url=T);const[ue,$e]=await Promise.all([n.fetchQuery({...Dl({client:Q,path:{name:t},query:ae}),staleTime:m?0:ct}),n.fetchQuery({...El({client:Q,path:{name:t}}),staleTime:m?0:ct})]);f(ue),p($e)}catch(T){f([]),p([]),H(T instanceof Error?T.message:"Failed to load GSC inspection history")}finally{Be(!1)}}async function Qa(m=!1){Qe(!0);try{const[T,ae]=await Promise.all([n.fetchQuery({...Zr({client:Q,path:{name:t}}),staleTime:m?0:ct}),n.fetchQuery({...$l({client:Q,path:{name:t}}),staleTime:m?0:ct}).catch(()=>[])]);De(T),dn(ae)}catch(T){De(null),dn([]),H(T instanceof Error?T.message:"Failed to load coverage data")}finally{Qe(!1)}}async function Ha(m){he(!0),H(null);try{const T=await sr(t,{urls:m}),{succeeded:ae,failed:ue,total:$e}=T.summary;Ne({title:"Indexing requested",detail:ue===0?`${ae} URL${ae!==1?"s":""} submitted for indexing.`:`${ae}/${$e} submitted successfully, ${ue} failed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(T){H(T instanceof Error?T.message:"Failed to request indexing")}finally{he(!1)}}async function Wi(){he(!0),H(null);try{const m=await sr(t,{urls:[],allUnindexed:!0}),{succeeded:T,failed:ae,total:ue}=m.summary;Ne({title:"Indexing requested",detail:ae===0?`${T} unindexed URL${T!==1?"s":""} submitted for indexing.`:`${T}/${ue} submitted successfully, ${ae} failed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(m){H(m instanceof Error?m.message:"Failed to request indexing")}finally{he(!1)}}async function zn(){_(!0),H(null);try{const m=await Vn(t);n.setQueryData(Il({client:Q,path:{name:t}}),m),Ee(m.sitemaps),Ve(m.summary),bt(m.preferredSubmissionUrls),Fe(new Set),tt({}),m.sitemaps.length===0&&yt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(m){H(m instanceof Error?m.message:"Failed to list sitemaps")}finally{_(!1)}}async function Yi(m){const T=ke.has(m);if(Fe(ae=>{const ue=new Set(ae);return T?ue.delete(m):ue.add(m),ue}),!(T||qt[m])){Ye(ae=>new Set(ae).add(m));try{const ae=await Vn(t,m);tt(ue=>({...ue,[m]:ae.sitemaps}))}catch(ae){H(ae instanceof Error?ae.message:"Failed to load sitemap files")}finally{Ye(ae=>{const ue=new Set(ae);return ue.delete(m),ue})}}}async function vs(m){if(!os||m.length===0)return;const T=[...new Set(m)];He(!0),H(null),Ae({completed:0,total:T.length});let ae=0,ue=0,$e=0,qe=null;try{for(let Xe=0;Xe<T.length;Xe+=50){const Pe=T.slice(Xe,Xe+50);try{const mt=await Ll(t,Pe);ae+=mt.summary.accepted,ue+=mt.summary.failed,$e+=Pe.length,Ae({completed:$e,total:T.length})}catch(mt){$e+=Pe.length;const Tt=Pe.length,cs=T.length-$e,Ns=mt instanceof Error?mt.message:"The batch request failed",Bs=`${ae} accepted, ${ue} failed, ${Tt} unconfirmed, ${cs} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;qe=`Sitemap submission stopped after a batch request failed. ${Bs} ${Ns}`,H(qe),Ne({title:"Sitemap resubmission partially completed",detail:Bs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const _e=T.length;Ne({title:ue===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ue===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ae}/${_e} sitemap submissions; ${ue} failed. Indexing is not guaranteed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Ge("")}catch(_e){H(_e instanceof Error?_e.message:"Failed to submit sitemap to Google")}finally{He(!1),Ae(null),await zn(),qe&&H(qe)}}async function Ji(){He(!0);const m=fe??[];try{const T=m.filter(ue=>ue.isSitemapsIndex),ae=[];for(let ue=0;ue<T.length;ue+=4)(await Promise.all(T.slice(ue,ue+4).map(async qe=>{const _e=qt[qe.path];if(_e)return _e;const Xe=await Vn(t,qe.path);return tt(Pe=>({...Pe,[qe.path]:Xe.sitemaps})),Xe.sitemaps}))).forEach((qe,_e)=>{ae.push(...qe.length>0?qe.map(Xe=>Xe.path):[T[ue+_e].path])});await vs([...m.filter(ue=>!ue.isSitemapsIndex).map(ue=>ue.path),...ae])}catch(T){H(T instanceof Error?T.message:"Failed to load sitemap files"),He(!1)}}async function Wa(m){Ct(!0),H(null);try{await Ml(t,"gsc",m),await it(n,"google"),o(T=>T.map(ae=>ae.connectionType==="gsc"?{...ae,sitemapUrl:m}:ae)),Ne({title:"Default sitemap updated",detail:m,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(T){H(T instanceof Error?T.message:"Failed to set the default sitemap")}finally{Ct(!1)}}async function Ya(m){try{await Gn.mutateAsync({projectName:t,projectLabel:t,opts:m?{sitemapUrl:m}:void 0})}catch{}}async function Ja(){U(!0),H(null);try{const[m,T]=await Promise.all([Xr().catch(()=>null),n.fetchQuery({...Ra({client:Q,path:{name:t}}),staleTime:ct}).catch(()=>[])]);r(!!m?.google?.configured),o(T);const ae=T.find(ue=>ue.connectionType==="gsc");await Promise.all([Ka(ae),Gs(),Bn(),hn(),Qa(),ae?.propertyId?zn():Promise.resolve()])}finally{U(!1)}}l.useEffect(()=>{Ja()},[t,s]),l.useEffect(()=>{ne(0),Gs(0),Bn()},[j]);const Xa=l.useRef(!1);l.useEffect(()=>{if(!Xa.current){Xa.current=!0;return}ne(0),Gs(0)},[R]);async function Za(){if(!a){H("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}M(!0),H(null),yt(null);try{let m=function(mt){if(mt.source!==ue||mt.origin!==$e||!mt.data||typeof mt.data!="object")return;const Tt=mt.data;Tt.type!==Zd||Tt.connectionType!=="gsc"||Pe(!0)};const{authUrl:T,redirectUri:ae}=await Rl(t,"gsc");if(!T.startsWith("https://accounts.google.com/")){H("Unexpected OAuth redirect URL. Please try again.");return}const ue=window.open(T,"_blank","width=600,height=700");if(!ue){window.location.assign(T);return}const $e=ae?new URL(ae).origin:window.location.origin;let qe=!1,_e=null;const Xe=()=>{_e!==null&&window.clearInterval(_e),window.removeEventListener("message",m)},Pe=async mt=>{if(!qe){qe=!0,Xe(),yt(mt?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await it(n,"google"),await Ja()}finally{yt(null)}}};window.addEventListener("message",m),yt("Finish the Google consent flow in the popup. This page will refresh automatically."),_e=window.setInterval(()=>{ue.closed&&Pe(!1)},1e3)}catch(m){H(m instanceof Error?m.message:"Failed to start OAuth flow")}finally{M(!1)}}async function Xi(){H(null),yt(null);try{await Al(t,"gsc"),await it(n,"google"),o(m=>m.filter(T=>T.connectionType!=="gsc")),d([]),$("")}catch(m){H(m instanceof Error?m.message:"Failed to disconnect")}}async function Zi(){if(q){K(!0),H(null);try{await Ol(t,"gsc",q),await it(n,"google"),o(m=>m.map(T=>T.connectionType==="gsc"?{...T,propertyId:q}:T)),Ne({title:"GSC property updated",detail:`${t} is now linked to ${q}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(m){H(m instanceof Error?m.message:"Failed to save GSC property")}finally{K(!1)}}}async function el(){H(null),yt(null);try{await Un.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(w,10)||void 0,full:W||void 0}}),await it(n,"gsc")}catch{}}async function er(){if(g.trim()){Me(!0),H(null),yt(null);try{const m=await Tl(t,g.trim());await it(n,"gsc"),E(m),v(""),await hn()}catch(m){H(m instanceof Error?m.message:"Failed to inspect URL")}finally{Me(!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"})]})}),Se&&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:Se.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Se.message}),(ms(Se.enableUrl)||ms(Se.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[ms(Se.enableUrl)&&e.jsx("a",{href:ms(Se.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 ↗"}),ms(Se.indexingApiUrl)&&e.jsx("a",{href:ms(Se.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:()=>Mt(null),children:"×"})]})}),ie&&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:[ie,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>H(null),children:"×"})]}),ot&&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:[ot,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>yt(null),children:"×"})]}),C?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[at?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:at.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Last updated ",_t(at.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ie(Xi),children:"Disconnect"})]}):e.jsxs(me,{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(oe,{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(k,{type:"button",variant:"outline",size:"sm",disabled:se,onClick:Ie(Za),children:se?"Opening…":"Connect Google Search Console"}):e.jsx(k,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ut,{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."})]})]})]}),(at||Hi)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(me,{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.jsx("h3",{children:"Search performance"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"segmented",role:"group","aria-label":"Performance time period",children:Xd.map(m=>e.jsx("button",{type:"button","aria-pressed":j===m,className:`segmented-option ${j===m?"segmented-option-active":""}`,onClick:()=>{D(m),ne(0),ye.setPage(1)},children:m==="all"?"All":m},m))}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:ge,onClick:()=>{ne(0),ye.setPage(1),Gs(0),Bn()},children:ge?"Loading…":"Apply filters"})]})]}),c&&c.daily.length>0&&(()=>{const m=c.daily,T=Math.max(...m.map(ze=>ze.impressions),1),{clicks:ae,impressions:ue,ctr:$e}=c.totals,qe=($e*100).toFixed(1),_e=700,Xe=220,Pe={top:12,bottom:36,left:48,right:12},mt=_e-Pe.left-Pe.right,Tt=Xe-Pe.top-Pe.bottom,cs=mt/m.length,Ns=Math.max(Math.min(cs*.35,24),4),Bs=Math.max(Ns*.15,1),tl=ze=>{if(ze<=0)return 1;const Bt=Math.pow(10,Math.floor(Math.log10(ze))),Rt=ze/Bt,Jt=Rt<=1.5?1.5:Rt<=3?3:Rt<=5?5:10;return Math.ceil(Jt*Bt)},xn=4,pn=Math.ceil(tl(T)/xn)*xn,sl=Array.from({length:xn+1},(ze,Bt)=>pn/xn*Bt),nl=ze=>ze>=1e3?`${(ze/1e3).toFixed(ze>=1e4?0:1)}k`:String(ze);return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Clicks ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:ae.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-chart-series-2"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Impressions ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:ue.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[qe,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${_e} / ${Xe}`},children:e.jsxs("svg",{viewBox:`0 0 ${_e} ${Xe}`,className:"h-full w-full",children:[sl.map((ze,Bt)=>{const Rt=Pe.top+Tt-ze/pn*Tt;return e.jsxs("g",{children:[e.jsx("line",{x1:Pe.left,y1:Rt,x2:_e-Pe.right,y2:Rt,stroke:gt.gridLine,strokeWidth:"1"}),e.jsx("text",{x:Pe.left-6,y:Rt+3.5,textAnchor:"end",fill:gt.text,fontSize:"10",fontFamily:"inherit",children:nl(ze)})]},`t-${Bt}`)}),m.map((ze,Bt)=>{const Rt=Pe.left+cs*Bt+cs/2,Jt=ze.impressions/pn*Tt,gn=ze.clicks/pn*Tt;return e.jsxs("g",{children:[e.jsx("title",{children:`${ze.date}
2
+ Clicks: ${ze.clicks}
3
+ Impressions: ${ze.impressions}
4
+ CTR: ${(ze.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:Rt-Ns-Bs/2,y:Pe.top+Tt-Jt,width:Ns,height:Math.max(Jt,1),rx:2,fill:pt[1],opacity:.85}),e.jsx("rect",{x:Rt+Bs/2,y:Pe.top+Tt-gn,width:Ns,height:Math.max(gn,1),rx:2,fill:Qt.positiveDeep,opacity:.85})]},ze.date)}),(()=>{const ze=Math.min(m.length,7);return Array.from({length:ze},(Bt,Rt)=>{const Jt=m.length===1?0:Math.round(Rt/(ze-1)*(m.length-1)),gn=Pe.left+cs*Jt+cs/2;return e.jsx("text",{x:gn,y:Xe-8,textAnchor:"middle",fill:gt.textDim,fontSize:"10",fontFamily:"inherit",children:m[Jt].date.slice(5)},`xl-${Jt}`)})})()]})})]})})(),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:S.startDate,onChange:m=>V(T=>({...T,startDate:m.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:S.endDate,onChange:m=>V(T=>({...T,endDate:m.target.value}))}),e.jsx(As,{value:S.query,onChange:m=>V(T=>({...T,query:m})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(As,{value:S.page,onChange:m=>V(T=>({...T,page:m})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Query and page filters match case-insensitive substrings. Click Apply filters to run. Filtering and sorting examine up to ",yn.toLocaleString()," matching rows while the table stays at ",Et," rows per page."]}),h.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(m=>e.jsx("th",{className:"text-right","aria-sort":st?.key===m?st.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:()=>{ye.setPage(1),kt(T=>T?.key===m?T.dir==="desc"?{key:m,dir:"asc"}:null:{key:m,dir:"desc"})},children:[Cl[m],st?.key===m?st.dir==="desc"?" ↓":" ↑":""]})},m))]})}),e.jsx("tbody",{children:Pt.map((m,T)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:m.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:m.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Xs,{value:m.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:m.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:m.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(m.ctr)?m.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:m.position.toFixed(1)})]},`${m.date}:${m.query}:${m.page}:${T}`))})]})}),e.jsx(fs,{page:G?ye.page:Math.floor(pe/Et)+1,pageSize:Et,visibleRows:Pt.length,totalRows:G?ce:void 0,hasNextPage:G?void 0:X,disabled:ge,itemLabel:G?"matches":"rows",onPageChange:m=>{if(G){ye.setPage(m);return}const T=(m-1)*Et;ne(T),Gs(T)}}),G&&ce>=yn?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",yn.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(me,{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.jsx("h3",{children:"Index coverage"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[J&&J.notIndexed.length>0&&e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:Y,onClick:()=>{Wi()},children:Y?"Requesting…":`Request indexing (${J.notIndexed.length})`}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:xe,onClick:()=>{Qa(!0)},children:xe?"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 m=J.summary.indexed+J.summary.notIndexed,T=m>0?J.summary.indexed/m:0,ae=m>0?J.summary.notIndexed/m:0,ue=54,$e=2*Math.PI*ue,qe=$e*(1-T),_e=$e*ae,Xe=$e*T;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:ue,fill:"none",stroke:gt.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ue,fill:"none",stroke:Qt.positiveDeep,strokeWidth:"14",strokeDasharray:$e,strokeDashoffset:qe,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:ue,fill:"none",stroke:gt.textFaint,strokeWidth:"14",strokeDasharray:`${_e} ${$e-_e}`,strokeDashoffset:-Xe,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:[(T*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(m=>{const T=m==="indexed"?J.indexed.length:m==="notIndexed"?J.notIndexed.length:J.deindexed.length,ae=m==="indexed"?"Indexed":m==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":Ke===m,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${Ke===m?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{Wt(m),is(null)},children:[ae," (",T,")"]},m)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Ke==="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:ys.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:m.url}),e.jsx("td",{className:"text-secondary",children:m.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:m.crawlTime?m.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:m.isMobileFriendly===!0?"Yes":m.isMobileFriendly===!1?"No":"—"})]},m.id))})]}),Ke==="notIndexed"&&!jt&&(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(m=>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:()=>is(m.reason),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),is(m.reason))},tabIndex:0,role:"button","aria-label":`View ${m.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:m.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:m.count})]},m.reason))})]}),Ke==="notIndexed"&&!jt&&(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:On.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:m.url}),e.jsx("td",{className:"text-secondary",children:m.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:m.coverageState??"Unknown"})]},m.id))})]}),Ke==="notIndexed"&&jt&&(()=>{const m=(J.reasonGroups??[]).find(T=>T.reason===jt);return m?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:()=>is(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:m.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[m.count," affected page",m.count!==1?"s":""]})]}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:Y,onClick:()=>{Ha(m.urls.map(T=>T.url))},children:Y?"Requesting…":`Request indexing (${m.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:I.map(T=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:T.url}),e.jsx("td",{className:"text-secondary",children:T.crawlTime?T.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:Y,onClick:()=>{Ha([T.url])},title:"Request indexing",children:"Index"})})]},T.id))})]})]}):null})(),Ke==="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:Fn.map((m,T)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:m.url}),e.jsx("td",{className:"text-secondary",children:m.previousState}),e.jsx("td",{className:"text-secondary",children:m.currentState}),e.jsx("td",{className:"text-secondary",children:m.transitionDate.split("T")[0]})]},`${m.url}-${T}`))})]}),(Ke==="indexed"&&J.indexed.length===0||Ke==="notIndexed"&&!jt&&J.notIndexed.length===0||Ke==="deindexed"&&J.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(fs,{page:mn,pageSize:Xt,visibleRows:Math.min(Xt,Us.length-ut),totalRows:Us.length,onPageChange:un,itemLabel:"URLs"})]}),e.jsx("p",{className:"mt-3 text-xs text-muted",children:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."}),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":de,onClick:()=>ve(m=>!m),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:de?"Hide snapshots":At.length>0?`View ${At.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.",ls&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ls.indexed>=0?"+":"",ls.indexed.toLocaleString()," indexed, ",ls.notIndexed>=0?"+":"",ls.notIndexed.toLocaleString()," not indexed."]})]}),de&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:At.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:At.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:m.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:m.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:m.notIndexed.toLocaleString()})]},m.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:xe?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(me,{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.jsx("h3",{children:"Sitemap operations"})]}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:O||!at?.propertyId,onClick:()=>{zn()},children:O?"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:lt,onChange:m=>Ge(m.target.value),onKeyDown:m=>m.key==="Enter"&&void vs([lt.trim()])}),e.jsx(k,{type:"button",size:"sm",disabled:!os||Je||!lt.trim(),onClick:()=>{vs([lt.trim()])},children:Je?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(k,{type:"button",size:"sm",variant:"outline",disabled:!os||Je||_n.length===0,onClick:()=>{vs(_n)},children:Je?"Resubmitting…":Qi}),e.jsx(k,{type:"button",size:"sm",variant:"outline",disabled:!os||Je||!fe?.length,onClick:()=>{Ji()},children:"Resubmit all files"}),Ue&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ue.indexes," index",Ue.indexes===1?"":"es",", ",Ue.files," file",Ue.files===1?"":"s"]}),Re&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Re.completed,"/",Re.total]})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"Google is asked to refetch these sitemaps. Indexing is not guaranteed."}),!os&&at&&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:Ie(Za),children:"Reconnect"})]}),fe&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:fe.length>0?e.jsxs(e.Fragment,{children:[e.jsx(As,{value:wt,onChange:m=>{St(m),nt.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:nt.rows.flatMap(m=>{const T=gr(m),ae=fr(m),ue=br(m),$e=qt[m.path]??[],qe=ke.has(m.path),_e=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Xs,{value:m.path})}),e.jsx("td",{className:"text-secondary",children:m.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":qe,"aria-label":`${qe?"Collapse":"Expand"} files in ${m.path}`,onClick:()=>{Yi(m.path)},children:dt.has(m.path)?"Loading…":`${qe?"▾":"▸"} Index${qt[m.path]?` (${$e.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ue}),e.jsx("td",{className:"text-secondary",children:m.lastSubmitted?m.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:m.lastDownloaded?m.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:T.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ae||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!os||Je,onClick:()=>{vs([m.path])},children:m.lastSubmitted?"Resubmit to Google":"Submit to Google"}),at?.sitemapUrl===m.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:Ot,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Wa(m.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Gn.isPending,onClick:()=>{Ya(m.path)},children:"Inspect URLs"})]})})]},m.path),Xe=m.isSitemapsIndex&&qe?$e.map(Pe=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Xs,{value:Pe.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:br(Pe)}),e.jsx("td",{className:"text-secondary",children:Pe.lastSubmitted?Pe.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:Pe.lastDownloaded?Pe.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:gr(Pe).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:fr(Pe)||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!os||Je,onClick:()=>{vs([Pe.path])},children:"Resubmit"}),at?.sitemapUrl===Pe.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:Ot,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Wa(Pe.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Gn.isPending,onClick:()=>{Ya(Pe.path)},children:"Inspect URLs"})]})})]},`${m.path}:${Pe.path}`)):[];return[_e,...Xe]})})]}),e.jsx(fs,{page:nt.page,pageSize:Et,visibleRows:nt.rows.length,totalRows:nt.totalRows,onPageChange:nt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(me,{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:g,onChange:m=>v(m.target.value),onKeyDown:m=>m.key==="Enter"&&void er()}),e.jsx(k,{type:"button",size:"sm",disabled:et||!at?.propertyId||!g.trim(),onClick:Ie(er),children:et?"Inspecting…":"Inspect URL"})]}),L&&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:L.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:L.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:tr(L.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:_t(L.crawlTime)})]})]})]}),e.jsxs(me,{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(k,{type:"button",variant:"outline",size:"sm",disabled:je,onClick:()=>{hn(!0)},children:je?"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:re,onChange:m=>le(m.target.value)}),e.jsx(k,{type:"button",size:"sm",variant:"outline",disabled:je,onClick:()=>{hn(!0)},children:"Apply filter"})]}),N.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:N.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:m.url}),e.jsx("td",{className:"text-neutral",children:m.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:m.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:m.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:tr(m.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:_t(m.inspectedAt)})]},m.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(me,{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"})]})}),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:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:b.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:m.url}),e.jsx("td",{className:"text-secondary",children:m.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:m.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:_t(m.transitionDate)})]},`${m.url}:${m.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),at&&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:()=>Ce(m=>!m),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 ${F?"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"})]})}),F&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(me,{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.jsx("h3",{children:"Pick the Search Console property"})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:q,disabled:z||u.length===0,onChange:m=>$(m.target.value),children:u.length===0?e.jsx("option",{value:"",children:z?"Loading properties…":"No properties available"}):u.map(m=>e.jsxs("option",{value:m.siteUrl,children:[m.siteUrl," · ",m.permissionLevel]},m.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(k,{type:"button",size:"sm",variant:"outline",disabled:z,onClick:()=>{Ka(at,!0)},children:z?"Refreshing…":"Refresh properties"}),e.jsx(k,{type:"button",size:"sm",disabled:!q||Oe,onClick:Ie(Zi),children:Oe?"Saving…":"Save property"})]}),e.jsx("p",{className:"text-xs text-muted",children:"The selected property is used for future syncs and URL inspections for this project."})]})]}),e.jsxs(me,{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:w,onChange:m=>ee(m.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:W,onChange:m=>A(m.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(k,{type:"button",size:"sm",disabled:Un.isPending||!at.propertyId,onClick:Ie(el),children:Un.isPending?"Queueing…":"Queue sync"}),!at.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const tu=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function su({projectName:t,projectId:s}){const n=as(),[a,r]=l.useState(null),[i,o]=l.useState(null),[u,d]=l.useState(!1),h=Le(Ra({client:Q,path:{name:t}})),x=h.data?.find(M=>M.connectionType==="gbp"),c=!!x,y=a?{locationName:a}:void 0,N=Le({...Fl({client:Q,path:{name:t}}),enabled:c}),f=Le({..._l({client:Q,path:{name:t},query:y}),enabled:c}),b=Le({...Ul({client:Q,path:{name:t},query:y}),enabled:c}),p=Le({...Gl({client:Q,path:{name:t},query:y}),enabled:c}),L=Le({...Bl({client:Q,path:{name:t},query:y}),enabled:c}),E=Le({...zl({client:Q,path:{name:t},query:y}),enabled:c}),q=Le({queryKey:["gbp-section-insights",t],queryFn:()=>Vl(t),enabled:c});function $(){it(n,"gbp")}const g=tn({...Ql(),onSuccess:M=>{Kl({id:M.runId,projectId:s,kind:bs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Ne({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=l.useSyncExternalStore(ei,$n,$n),w=Object.values(v.runs).some(M=>M.kind===bs["gbp-sync"]&&M.projectId===s),ee=g.isPending||w,W=tn({...Hl(),onSuccess:()=>$()});if(l.useEffect(()=>{if(!a||!N.data)return;const M=N.data.locations.filter(z=>z.selected);(M.length<=1||!M.some(z=>z.locationName===a))&&r(null)},[a,N.data]),l.useEffect(()=>{if(!i||!N.data)return;(a?[a]:N.data.locations.filter(z=>z.selected).map(z=>z.locationName)).includes(i)||o(null)},[i,N.data,a]),h.isLoading)return null;if(!x){const M=[{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(me,{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:M.map((z,we)=>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:we+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 A=f.data,j=N.data?.locations??[],D=j.filter(M=>M.selected),S=b.data?.keywords??[],V=p.data?.lodging??[],pe=L.data?.placeActions??[],ne=E.data?.places??[],X=j.length>0?j[0].accountName:x.domain,te=a?j.find(M=>M.locationName===a)?.displayName??null:null,ce=a?j.filter(M=>M.locationName===a):D,B=new Set(ce.map(M=>M.locationName)),G=V.filter(M=>B.has(M.locationName)),P=pe.filter(M=>B.has(M.locationName)),re=ne.filter(M=>B.has(M.locationName)),le=new Set(D.map(M=>M.locationName)),C=a?S:S.filter(M=>le.has(M.locationName)),U=!a&&D.length>1,se=(q.data??[]).filter(M=>!M.dismissed&&tu.has(M.type)&&(!te||M.query===te||M.query===a||M.title.startsWith(te)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(me,{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(oe,{tone:"positive",children:"Connected"}),!Z()&&e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:ee,onClick:()=>g.mutate({client:Q,path:{name:t},body:{}}),children:ee?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[X?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:X})," · "]}):null,N.data?`${N.data.totalSelected} of ${N.data.totalDiscovered} locations tracked`:"Loading locations…"]}),D.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:M=>r(M.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"}),D.map(M=>e.jsx("option",{value:M.locationName,children:M.displayName},M.id))]})]}),D.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:[se.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),se.map(M=>e.jsx("div",{className:["insight-card",pu(M.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:[M.title,M.recommendation?.reason&&e.jsx(Ze,{text:M.recommendation.reason})]})},M.id))]}),A&&e.jsx(ju,{performance:A.performance,freshness:A.freshness,timeseries:A.timeseries}),A?.profileCompleteness&&e.jsx(nu,{summary:A.profileCompleteness}),ce.length>0&&e.jsx(au,{locations:ce,lodging:G,places:re,placeActions:P,expandedLocation:i,onToggleExpanded:M=>{o(z=>z===M?null:M)}}),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"}),b.data&&b.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[b.data.thresholdedPct,"% privacy-thresholded"]})]}),C.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"}),U&&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:C.slice(0,25).map(M=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:M.keyword}),U&&e.jsx("td",{className:"text-muted",children:j.find(z=>z.locationName===M.locationName)?.displayName??M.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:M.valueCount!==null?M.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",M.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[M.periodStart,"–",M.periodEnd]})]},`${M.locationName}:${M.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>d(M=>!M),"aria-expanded":u,children:[e.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"})," Manage locations (",j.length,")"]}),u&&e.jsx("div",{className:"mt-3",children:j.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"}),!Z()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:j.map(M=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:M.displayName}),e.jsx("td",{className:"text-muted",children:M.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(oe,{tone:M.selected?"positive":"neutral",children:M.selected?"Tracked":"Not tracked"})}),!Z()&&e.jsx("td",{className:"text-right",children:e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:W.isPending,onClick:()=>W.mutate({client:Q,path:{name:t,locationName:M.locationName},body:{selected:!M.selected}}),children:M.selected?"Untrack":"Track"})})]},M.id))})]})})]})]})})}function nu({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Ks(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Ks(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Ks(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Ks(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Ks(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 ${xu(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function au({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:i}){const o=new Map(s.map(h=>[h.locationName,h])),u=new Map(n.map(h=>[h.locationName,h])),d=new Map;for(const h of a){const x=d.get(h.locationName)??[];x.push(h),d.set(h.locationName,x)}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:Z()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const x=o.get(h.locationName)??null,c=u.get(h.locationName)??null,y=d.get(h.locationName)??[],N=r===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(oe,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(oe,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Ai(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(iu,{location:h})}),e.jsx("td",{children:e.jsx(lu,{lodging:x})}),e.jsx("td",{children:e.jsx(cu,{place:c,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(uu,{actions:y})}),e.jsx("td",{className:"text-right",children:e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:()=>i(h.locationName),children:N?"Hide":"Details"})})]}),N&&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(hu,{location:h,lodging:x,place:c,placeActions:y})})})]},h.id)})})]})})]})}function ru(t){return[{label:"Description",tone:hs(t.description)?"positive":"neutral",value:hs(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:hs(t.primaryPhone)?"positive":"neutral",value:hs(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:hs(t.websiteUri)?"positive":"neutral",value:hs(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 iu({location:t}){const s=ru(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(oe,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function lu({lodging:t}){return e.jsx(Da,{...ou(t)})}function ou(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 cu({place:t,mapsUri:s}){return e.jsx(Da,{...du(t,s)})}function du(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 uu({actions:t}){return e.jsx(Da,{...mu(t)})}function mu(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 Da({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(oe,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function hu({location:t,lodging:s,place:n,placeActions:a}){const r=s?fu(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Jn,{title:"Owner profile · Business Information",children:[e.jsx(ht,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(ht,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(ht,{label:"Description",value:hs(t.description)?t.description:"Not returned"}),e.jsx(ht,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(ht,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(ht,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(ht,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(ht,{label:"Open status",value:Ai(t.openStatus)}),e.jsx(ht,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Jn,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(ht,{label:"Last checked",value:jr(s.syncedAt)}),e.jsx(ht,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(ht,{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(Jn,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(ht,{label:"Places tier",value:n.tier}),e.jsx(ht,{label:"Last checked",value:jr(n.syncedAt)}),e.jsx(ht,{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(i=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Mn(i.placeActionType),i.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Mn(i.providerType),i.uri?` · ${gu(i.uri)}`:""]})]},i.placeActionLinkName))})})]})]})}function Jn({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 ht({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 Ks(t,s,n){return t===s?"positive":t===0?n:"caution"}function xu(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function pu(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function hs(t){return typeof t=="string"&&t.trim().length>0}function Ai(t){return t?Mn(t):"Not returned"}function Mn(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function gu(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function jr(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function fu(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&bu(n)).map(([s])=>Mn(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function bu(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function ju({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Wl.filter(f=>(a[f]??0)>0),i=Yl.filter(f=>(a[f]??0)>0),o=Object.keys(a).filter(f=>(a[f]??0)>0&&Jl(f)==="other").sort((f,b)=>(a[b]??0)-(a[f]??0)),u=Object.keys(a).filter(f=>(a[f]??0)===0).sort(),d=n.map(f=>{const b={date:f.date};for(const[p,L]of Object.entries(f.metrics))b[p]=L;return b}),h=n.find(f=>f.pending)?.date,x=n.length>0?n[n.length-1].date:void 0,c=d.length>0,y=s.dataThroughDate?`Data through ${Ln(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,N=[...r,...o];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),y&&e.jsx("span",{className:"text-[11px] text-muted",children:y})]}),!c||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(yr,{data:d,metrics:r,kind:"line",firstPending:h,lastDate:x}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:N.map(f=>e.jsxs("span",{className:"text-sm text-secondary",children:[In(f)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[f]??0).toLocaleString()})]},f))})]})]}),c&&i.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(yr,{data:d,metrics:i,kind:"area",firstPending:h,lastDate:x})]}),u.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",u.map(f=>In(f)).join(", ")]})]})}function yr({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ma,{stroke:Ia,vertical:!1}),e.jsx(Es,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:Ht},tickFormatter:fa,minTickGap:24}),e.jsx(qs,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Os,{...gs,labelFormatter:Ln,formatter:(i,o)=>[typeof i=="number"?i.toLocaleString():String(i??0),In(String(o??""))]}),e.jsx(mi,{wrapperStyle:{fontSize:11,color:gt.text},formatter:i=>In(i)}),a&&r&&e.jsx(ed,{x1:a,x2:r,fill:gt.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:gt.textDim,fontSize:10}}),s.map((i,o)=>n==="line"?e.jsx(Ta,{type:"monotone",dataKey:i,stroke:pt[o%pt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},i):e.jsx(ks,{type:"monotone",dataKey:i,stackId:"reach",stroke:pt[o%pt.length],fill:pt[o%pt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},i))]})})})}function yu(t){return La(Gt(String(t)))}function vu(t){return ns(Gt(String(t)))}function Xn({children:t,label:s="More info",placement:n="top",className:a}){const r=l.useId(),[i,o]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":i?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:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(sd,{className:"h-3.5 w-3.5","aria-hidden":!0})}),i&&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 vn=Et;function ws(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Zn(t){return t.toLocaleString()}function Nu(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function wu(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 Su(t){const s=t.filter(n=>n.kind===bs["backlink-extract"]&&!ti(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Cu(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),i=a%60;return i===0?`${r}m`:`${r}m ${i}s`}function ku({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[i,o]=l.useState([]),[u,d]=l.useState(null),[h,x]=l.useState(null),[c,y]=l.useState(null),[N,f]=l.useState(Date.now()),[b,p]=l.useState(0),[L,E]=l.useState(!0),[q,$]=l.useState(!1),[g,v]=l.useState(null),w=l.useCallback(async()=>{E(!0),v(null);try{const[X,te,ce,B,G]=await Promise.all([Xl().catch(()=>null),Zl(t,{excludeCrawlers:!0}).catch(()=>null),eo(t,{limit:vn,offset:b,excludeCrawlers:!0}).catch(re=>{if(re instanceof Ls&&re.code==="NOT_FOUND")return null;throw re}),to(t).catch(()=>[]),so(t).catch(()=>[])]);d(X),n(te),r(ce),o(B);const P=Su(G);x(P)}catch(X){v(X instanceof Error?X.message:"Failed to load backlinks")}finally{E(!1)}},[t,b]);l.useEffect(()=>{w()},[w]),l.useEffect(()=>{if(!h)return;const X=h.id;let te=!1;const ce=async()=>{try{const G=await si(X);if(te)return;ti(G.status)?(x(null),y(G),await w()):x(P=>P?.id===G.id?{...P,...G}:P)}catch{}},B=window.setInterval(()=>{ce()},3e3);return()=>{te=!0,window.clearInterval(B)}},[h,w]),l.useEffect(()=>{if(!h)return;const X=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(X)},[h]),l.useEffect(()=>{if(!c||c.status==="failed")return;const X=window.setTimeout(()=>y(null),1e4);return()=>window.clearTimeout(X)},[c]);async function ee(){$(!0),v(null);try{const X=await ro(t);x(X)}catch(X){X instanceof Ls&&X.code==="MISSING_DEPENDENCY"?v("DuckDB is not installed. Visit the Backlinks admin page to install it."):v(X instanceof Error?X.message:"Failed to trigger extract")}finally{$(!1)}}const W=l.useMemo(()=>i.slice().sort((X,te)=>X.queriedAt.localeCompare(te.queriedAt)).map(X=>({date:X.queriedAt,linkingDomains:X.totalLinkingDomains})),[i]),A=a?.rows??[],j=a?.total??0,D=s?.excludedLinkingDomains??0,S=Math.floor(b/vn)+1;return l.useEffect(()=>{b>0&&b>=j&&p(0)},[b,j]),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"})]})}),g&&e.jsx(me,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:g})}),h&&e.jsx(me,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ga,{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(oe,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Cu(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",N]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),c&&!h&&e.jsx(me,{className:`surface-card p-4 mb-4 ${c.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[c.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(xi,{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 ${c.status==="failed"?"text-negative":"text-positive"}`,children:c.status==="failed"?"Extract failed":"Extract complete"}),c.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:no(c.error)}):c.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),V()]});function V(){return L?e.jsx(me,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):pe()}function pe(){const X=s!==null&&s.totalLinkingDomains>0,te=c?.status==="failed",ce=s!==null&&s.totalLinkingDomains===0&&!te,B=u?.status==="ready",G=u?.status==="failed",P=u&&(u.status==="downloading"||u.status==="querying"||u.status==="queued");return X?ne(e.jsxs(e.Fragment,{children:[!Z()&&e.jsxs(e.Fragment,{children:[e.jsxs(k,{type:"button",variant:"outline",size:"sm",disabled:q||h!==null,onClick:Ie(ee),children:[e.jsx(hi,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsx(Xn,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!Z()&&e.jsx(k,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Open admin"})})]})):e.jsx(me,{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(ao,{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."}),!Z()&&e.jsx("div",{className:"mt-4",children:e.jsx(k,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/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."]}),!Z()&&e.jsx("div",{className:"mt-4",children:e.jsx(k,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"View sync status"})})})]}),G&&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."}),!Z()&&e.jsx("div",{className:"mt-4",children:e.jsx(k,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})})})]}),B&&!P&&!ce&&!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."]}),!Z()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(k,{type:"button",size:"sm",disabled:q||h!==null,onClick:Ie(ee),children:[e.jsx(Ms,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Run extract"]}),e.jsx(Xn,{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."}),!Z()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(k,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})})})]}),ce&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!Z()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(k,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(k,{type:"button",variant:"outline",size:"sm",disabled:q||h!==null,onClick:Ie(ee),children:[e.jsx(Ms,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsxs(Xn,{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 ne(X){if(!s)return null;const te="Linking hosts",ce="linking hosts",B="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Zn(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",ce]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Zn(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",ce," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Nu(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",ce," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",B," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",wu(s.queriedAt),D>0&&e.jsxs(e.Fragment,{children:[" · ",D," excluded domain",D===1?"":"s"]})]}),W.length>=2&&e.jsxs(me,{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(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:W,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:pt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:pt[0],stopOpacity:0})]})}),e.jsx(Es,{dataKey:"date",tick:Lt,stroke:Ht,tickFormatter:yu}),e.jsx(qs,{tick:Lt,stroke:Ht,allowDecimals:!1}),e.jsx(Os,{contentStyle:gs.contentStyle,labelStyle:gs.labelStyle,itemStyle:gs.itemStyle,labelFormatter:vu}),e.jsx(ks,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:pt[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(me,{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:[A.map(G=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:G.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Zn(G.numHosts)})]},G.linkingDomain)),A.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:D>0&&j===0?`Every referring domain in this ${B} was a crawler/proxy host (${D} hidden).`:`No referring domains in this ${B}.`})})]})]})}),e.jsx(fs,{page:S,pageSize:vn,visibleRows:A.length,totalRows:j,onPageChange:G=>p((G-1)*vn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:X})]})}}function Pu({projectName:t}){const s=Le({...io({client:Q,path:{name:t}}),staleTime:ni}),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:a instanceof Error?a.message:String(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:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:r,providersMentioning:i,providersConfigured:o}=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 ",o," 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 ",i," of ",o," 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(Au,{data:n}),e.jsx(Ru,{data:n}),n.competitorGaps.length>0&&e.jsx(Mu,{data:n})]})}function Au({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:i}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Nn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Nn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Nn,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(Nn,{label:"Invisible",value:`${i} / ${s}`,helper:"No engine cites or mentions",tone:i>0?"negative":"neutral"})]})}function Nn({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 Ru({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($u,{}),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(Is,{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(i=>i.provider===a);return e.jsx("td",{className:"text-center",children:r==null?e.jsx(dd,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Iu,{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 $u(){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(Ps,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ps,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ps,{active:!1,tone:"cited"}),e.jsx(Ps,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Iu({provider:t}){const s=Lu(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Ps,{active:t.cited,tone:"cited"}),e.jsx(Ps,{active:t.mentioned,tone:"mentioned"})]})}function Lu(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 Ps({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 Mu({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(Is,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const on="__cited__",cn="__mentioned__",It="__mentionShare__";function Ri(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Gt(n),end:Gt(a),sweepCount:s.sweepCount??1}}function Tn(t){const s=Ri(t);if(!s)return"Sweep date unavailable";const n=ns(s.start),a=ns(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Tu(t){const s=Ri(t);return s?La(s.start):""}function _s(t){return t.trim().toLowerCase()}function va(t){return Math.round(t*1e3)/10}function Na(t){return t.byProvider??{}}function Du(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?on:cn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(c=>({date:c.startDate,[d]:va(c[h])})),series:[d],hasData:a,singleBucket:r}}const i=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(d=>Object.keys(Na(d))))].sort();return{rows:t.buckets.map(d=>{const h={date:d.startDate},x=Na(d);for(const c of o){const y=x[c];h[c]=y?va(y[i]):null}return h}),series:o,hasData:a,singleBucket:r}}function $i(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Eu(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function qu(t){return t.servedModelAttribution??{}}function Ou(t){return t.modelServiceMismatch??{}}function Fu(t){return t.modelPointerChanges??{}}function _u(t){return t.length>0?t.join(", "):null}function vr(t,s){const n=_s(s);return Object.entries(t).find(([a])=>_s(a)===n)?.[1]}function zt(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 Uu(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!vr(Na(a),s))continue;const r=$i(a);return r?vr(r,s)??null:null}return null}function Gu(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const i=s.get(r.bucketStartDate)??[];i.push({provider:n,event:r}),s.set(r.bucketStartDate,i)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,i)=>r.provider.localeCompare(i.provider)||r.event.observedAt.localeCompare(i.event.observedAt))}))}function Bu(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const i=r.events.filter(o=>!o.fromPreWindowAnchor);for(const o of r.events)o.fromPreWindowAnchor&&n.push({provider:a,event:o});i.length>0&&(s[a]={...r,events:i})}return{buckets:Gu(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function zu(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 Vu(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 Ku(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[It]:r?.rate==null?null:va(r.rate)}}),n=s.map(a=>a[It]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[It],hasData:n.length>0,singleBucket:n.length===1}}function Qu(t,s,n){return s==="mentionShare"?Ku(t):Du(t,s,n)}function Nr(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 wr(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Sr(t){return t>0?`+${t}`:`${t}`}function Hu(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Sr(n.delta)} on ${wr(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Sr(s.delta)} on ${wr(s.date)})`}const Wu=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Yu=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Ju=[{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:"Of all answer-text brand mentions for you and tracked competitors, the share that were you."}],Ea=pt[2],Xu="var(--chart-tooltip-bg)",Zu={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Kt(t){const s=_s(t);return Zu[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ts(t){return Math.round(t*10)/10}function em(t){return t===on||t===cn||t===It}function Ii(t){return t===on?"Cited":t===cn?"Mentioned":t===It?"Mention share":Kt(t)}function Ws(t,s){return t===on?Qt.positive:t===cn?pt[1]:t===It?Ea:Yc(_s(t),s)}function tm(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function sm(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
5
+ `)}function Rn(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function an(t){return t==="cited"?"citationRate":"mentionRate"}function Li(t,s){return s==="cited"?t.cited:t.mentionedCount}function Mi(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 Ti(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function wa(t){const s=$i(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>_s(a).localeCompare(_s(r))).map(([a,r])=>`${Kt(a)}: ${zt(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function nm(t){return t.some(({event:s})=>s.to.status==="mixed")?Qt.caution:t.some(({event:s})=>s.to.status==="unknown")?Qt.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?pt[4]:Qt.positive}function am(t,s,n){const a=Ti(t,s);return a?Tn(a):ns(Gt(n))}function rm({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:i,mismatch:o,buckets:u}){const d=l.useId(),h=Object.entries(i).sort(([c],[y])=>c.localeCompare(y)),x=t.buckets.length>0||t.beforeWindow.length>0;return e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":d,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:d,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),s?x?e.jsxs(e.Fragment,{children:[t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:c,events:y})=>y.map(({provider:N,event:f})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:am(u,c,f.observedAt)}),e.jsxs("span",{children:[Kt(N),": ",zt(f.from)," → ",zt(f.to)]})]},`${N}-${f.observedAt}-${f.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:c,event:y})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",ns(Gt(y.observedAt))]}),e.jsxs("span",{children:[Kt(c),": ",zt(y.from)," → ",zt(y.to),y.anchorObservedAt?` (last seen ${zt(y.from)} on ${ns(Gt(y.anchorObservedAt))})`:""]})]},`before-${c}-${y.observedAt}`))})]}),a.map(c=>e.jsxs("p",{className:"trend-model-evidence-note",children:[Kt(c.provider),": showing the most recent ",c.shown," of ",c.total," changes."]},`truncated-${c.provider}`)),r.map(c=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",Kt(c)," change."]},`incomplete-${c}`))]}):e.jsx("p",{className:"trend-model-evidence-empty",children:"No model evidence changes in this window."}):e.jsx("p",{className:"trend-model-evidence-empty",children:"Attribution unavailable from this API version."}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:h.map(([c,y])=>{const N=_u(y.latestServedModelIds),f=o[c];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:ns(Gt(y.latestObservation.observedAt))}),e.jsxs("span",{children:[Kt(c),": ",N??zt(y.latestObservation.state),f?` — not the ${zt(f.configured)} you selected`:""]})]},`served-${c}`)})})]})]})}function Cr(t){return t===null?"no data":`${t}%`}function ea(t){return t==null?"undefined":`${ts(t*100)}%`}function im({active:t,label:s,payload:n,metric:a,mode:r,buckets:i}){if(!t)return null;const o=Ti(i,s);if(!o)return null;if(a==="mentionShare"){const d=o.mentionShare.projectMentionSnapshots,h=o.mentionShare.competitorMentionSnapshots,x=d+h,c=o.mentionShare.rate==null?null:ts(o.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Tn(o)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:Ea},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:"Mention share"}),e.jsx("span",{className:"trend-tooltip-value",children:Cr(c)})]}),x>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",d," / ",x," brand mentions. Competitors ",h,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:wa(o)})]})}const u=r==="byProvider"?(n??[]).filter(d=>d.dataKey!==void 0):[{dataKey:a==="cited"?on:cn,value:ts(o[an(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Tn(o)}),u.map((d,h)=>{const x=String(d.dataKey??d.name??""),c=r==="byProvider"?Mi(o,x,a):null,y=c?.count??Li(o,a),N=c?.total??o.total,f=typeof d.value=="number"?d.value:ts(c?c.rate*100:o[an(a)]*100),b=d.color??Ws(x,h);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:b},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Ii(x)}),e.jsx("span",{className:"trend-tooltip-value",children:Cr(f)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[y," / ",N," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${x}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:wa(o)})]})}function lm({buckets:t,metric:s,mode:n,series:a}){return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[Rn(s)," 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(r=>{let i;if(s==="mentionShare"){const o=r.mentionShare.projectMentionSnapshots,u=r.mentionShare.competitorMentionSnapshots,d=o+u;i=d>0?`${ea(r.mentionShare.rate)} mention share, ${o} of ${d} brand mentions were you`:"mention share undefined, no project or competitor brand mentions"}else n==="byProvider"?i=a.map(o=>{const u=Mi(r,o,s);return u?`${Kt(o)} ${ea(u.rate)} ${Rn(s).toLowerCase()}, ${u.count} of ${u.total} snapshots`:`${Kt(o)} no data`}).join("; "):i=`${ea(r[an(s)])} ${Rn(s).toLowerCase()}, ${Li(r,s)} of ${r.total} snapshots`;return i+=`; ${wa(r)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Tn(r)}),e.jsx("td",{children:i})]},r.startDate)})})]})}function ta({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const i=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(o=>{const u=s===o.value,d=o.description?`${i}-${o.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":u,"aria-describedby":d,className:`segmented-option ${u?"segmented-option-active":""}`,onClick:()=>n(o.value),children:o.label}),o.description&&e.jsx("span",{id:d,className:"sr-only",children:o.description})]},o.value)})})}function om({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[i,o]=l.useState("mentioned"),[u,d]=l.useState("byProvider"),h=l.useMemo(()=>sm(s),[s]),x=Le({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>lo(t,a),staleTime:ni}),c=x.data??null,y=x.error,N=i==="mentionShare"?"overall":u,f=l.useMemo(()=>c?Qu(c,i,N):null,[c,i,N]),b=c?Eu(c):null,p=l.useMemo(()=>Bu(b??{}),[b]),L=l.useMemo(()=>zu(b??{}),[b]),E=l.useMemo(()=>Vu(b??{}),[b]),q=l.useMemo(()=>Object.entries(b??{}).filter(([,B])=>B.anchorUnavailable).map(([B])=>B).sort(),[b]),$=l.useMemo(()=>c?qu(c):{},[c]),g=l.useMemo(()=>c?Ou(c):{},[c]),v=l.useMemo(()=>c?oo(Fu(c)):null,[c]),w=i!=="mentionShare"&&N==="byProvider",ee=Rn(i),W=i==="cited"?Qt.positive:i==="mentionShare"?Ea:pt[1],A=w?gt.textDim:W,j=c?.buckets??[],D=l.useMemo(()=>{const B=new Map(j.map(G=>[G.startDate,Tu(G)]));return G=>B.get(String(G))??""},[j]),S=i==="mentionShare"?f?Nr(f.rows,It):null:j.length>0?ts(j[j.length-1][an(i)]*100):null,V=i==="mentionShare"?f?tm(f.rows,It):null:j.length>0?ts(j[0][an(i)]*100):null,pe=i==="mentionShare"?f?.rows.filter(B=>typeof B[It]=="number").length??0:j.length,ne=S!==null&&V!==null&&pe>1?ts(S-V):null,X=s.length,te=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 query-provider snapshot rates; Mention share uses project plus competitor brand mentions."})]})]}),S!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:A},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:ee}),w&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[S,"%"]}),ne!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${ne>0?"text-positive-400":ne<0?"text-negative-400":"text-muted"}`,children:[ne>0?"+":"",ne.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(ta,{options:Ju,value:i,onChange:o,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),i!=="mentionShare"&&e.jsx(ta,{options:Yu,value:u,onChange:d,ariaLabel:"Series"}),e.jsx(ta,{options:Wu,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]}),v?.kind==="no-known-change"&&e.jsxs("p",{className:"mt-3 text-[11px] leading-snug text-muted",children:[v.text,e.jsx(Ze,{text:v.detail})]})]});let ce;if(y)ce=e.jsx("p",{className:"text-sm text-negative-400",children:y instanceof Error?y.message:String(y)});else if(x.isLoading&&!c)ce=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(i==="mentionShare"&&X===0)ce=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!c||!f)ce=null;else{const{rows:B,series:G,hasData:P,singleBucket:re}=f,le=Hu(c.queryChanges);if(!P)ce=e.jsx("p",{className:"text-sm text-secondary",children:i==="mentionShare"?"No answer-text brand mentions for you or tracked competitors in this window yet.":"Run a sweep to start tracking citations and mentions over time."});else if(w&&G.length===0)ce=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 C=`${ee} rate across ${B.length} ${B.length===1?"sweep":"sweeps"}. Latest ${S}%${ne!==null?`, ${ne>=0?"up":"down"} ${Math.abs(ne).toFixed(1)} points over the period`:""}.`;ce=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:C}),e.jsx(lm,{buckets:j,metric:i,mode:N,series:G}),w&&G.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:G.map((U,se)=>{const M=Nr(B,U),z=Uu(j,U),we=b===null?"Attribution unavailable":z?zt(z):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:Ws(U,se)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:Ii(U)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),we]})]}),M!==null&&e.jsxs("span",{className:"trend-legend-value",children:[M,"%"]})]},U)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${ee} trend chart over ${B.length} ${B.length===1?"bucket":"buckets"}`,children:e.jsx(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:B,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ma,{stroke:Ia,vertical:!1}),e.jsx(Es,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:Ht},tickFormatter:D,minTickGap:24}),e.jsx(qs,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:U=>`${U}%`,tick:Lt,tickLine:!1,axisLine:!1,width:40}),e.jsx(Os,{cursor:{stroke:Ht,strokeWidth:1},content:e.jsx(im,{metric:i,mode:N,buckets:j})}),p.buckets.map(({bucketStartDate:U,events:se})=>e.jsx(td,{x:U,stroke:nm(se),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${U}`)),G.map((U,se)=>e.jsx(Ta,{type:"monotone",dataKey:U,name:U,stroke:Ws(U,se),strokeDasharray:U===It?"5 4":void 0,strokeWidth:em(U)?2.5:2,dot:U===It?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:Ws(U,se),strokeWidth:1.5}:{r:2.5,fill:Ws(U,se),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Xu},connectNulls:U!==It,isAnimationActive:!1},U))]})})}),e.jsx(rm,{partition:p,available:b!==null,counts:L,truncated:E,incompleteHistory:q,served:$,mismatch:g,buckets:j}),re&&e.jsx("p",{className:"visibility-trend-note",children:i==="mentionShare"?"Only one competitive mention-share point so far. The trend line fills in after another sweep with brand mentions.":"Only one sweep so far. The trend line fills in after the next run."}),le&&e.jsx("p",{className:"visibility-trend-note",children:le})]})}}return e.jsxs("section",{className:"visibility-trend",children:[te,ce]})}const kr=new Set([Js.queued,Js.running]);function cm({projectName:t}){const s=as(),[n,a]=l.useState(""),[r,i]=l.useState(""),[o,u]=l.useState(""),[d,h]=l.useState("__default__"),[x,c]=l.useState(null),y=Le({...co({client:Q,path:{name:t}}),staleTime:6e4}),N=Le({...ai({client:Q}),staleTime:6e4}),f=Le({...uo({client:Q,path:{name:t},query:{limit:20}}),refetchInterval:A=>A.state.data?.runs.some(j=>kr.has(j.status))?3e3:!1}),b=f.data?.runs??[];l.useEffect(()=>{!x&&b[0]&&c(b[0].id)},[b,x]);const p=b.find(A=>A.id===x)??null,L=Le({...mo({client:Q,path:{name:t,runId:x??""}}),enabled:!!x,refetchInterval:p&&kr.has(p.status)?3e3:!1}),E=L.data??null,q=l.useMemo(()=>mm(n),[n]),$=y.data?.locations??[],g=l.useMemo(()=>{const A=new Map((N.data?.providerCatalog??[]).map(j=>[j.name,j]));return(N.data?.providers??[]).filter(j=>j.configured&&A.get(j.name)?.mode==="api").map(j=>({...j,catalog:A.get(j.name)}))},[N.data]),v=!N.isLoading&&g.length===0,w=g.find(A=>A.name===r)??null;l.useEffect(()=>{r&&!w&&(i(""),u(""))},[r,w]);const ee=tn({...ho(),onSuccess:async A=>{c(A.id),a(""),u(""),await gm(s),Ne({title:"Research batch saved",detail:`${A.totalQueries} quer${A.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${A.id}`,dedupeMode:"replace"})},onError:A=>{Ne({title:"Could not start research",detail:A instanceof Error?A.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function W(){if(q.length===0||q.length>50||v||ee.isPending||Z())return;const A=d==="__default__"?void 0:d==="__none__"?null:$.find(j=>j.label===d)??void 0;ee.mutate({client:Q,path:{name:t},body:{queries:q,...r?{provider:r}:{},...r&&o.trim()?{model:o.trim()}:{},...A!==void 0?{location:A}:{}}})}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(me,{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 questions 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
6
+ e.g. What is the best way to choose an AEO platform?`,value:n,onChange:A=>a(A.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${q.length>50?"text-negative":"text-faint"}`,children:[q.length," ",q.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:A=>{i(A.target.value),u("")},children:[e.jsx("option",{value:"",children:"Project default"}),g.map(A=>e.jsx("option",{value:A.name,children:A.displayName??A.name},A.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:d,onChange:A=>h(A.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),$.map(A=>e.jsx("option",{value:A.label,children:A.label},A.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:w?`Default: ${w.model??w.defaultModel??w.catalog.defaultModel}`:"Choose a provider to select an exact model",value:o,disabled:!w,onChange:A=>u(A.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(w?.catalog.knownModels??[]).map(A=>e.jsx("option",{value:A.id,children:A.displayName},A.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!Z()&&e.jsxs(k,{type:"button",size:"sm",disabled:q.length===0||q.length>50||v||ee.isPending,onClick:W,children:[e.jsx(Ms,{size:14}),ee.isPending?"Starting research…":`Run ${q.length||""} research ${q.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(me,{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"})]}),f.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),b.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:"No research batches yet. Add one or more questions 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:b.map(A=>e.jsxs("tr",{className:x===A.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:()=>c(A.id),children:hm(A.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:A.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:A.requestedModel??A.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:A.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[A.completedQueries+A.failedQueries,"/",A.totalQueries]}),e.jsx("td",{children:e.jsx(oe,{tone:Di(A.status),children:A.status})})]},A.id))})]})})]})]}),e.jsx(dm,{detail:E,isLoading:L.isFetching})]})}function dm({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(i=>i.id===n)??t?.queries[0]??null;return e.jsxs(me,{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 ${xm(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(oe,{tone:Di(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(i=>e.jsxs("tr",{className:r?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(oe,{tone:pm(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(oe,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===ps.failed?"negative":"caution",children:i.answerMentioned===null?i.status===ps.failed?"Unavailable":"Pending":i.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(oe,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===ps.failed?"negative":"caution",children:i.citationState===null?i.status===ps.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(um,{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 um({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===ps.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=ms(n.uri),i=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:i}):e.jsx("span",{className:"truncate text-secondary",children:i}),r&&e.jsx(nd,{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 mm(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 hm(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 xm(t){return t.length>8?t.slice(0,8):t}function Di(t){return t===Js.completed?"positive":t===Js.partial?"caution":t===Js.failed?"negative":"neutral"}function pm(t){return t===ps.completed?"positive":t===ps.failed?"negative":"neutral"}async function gm(t){await it(t,"researchRuns")}const Sa=new Set(["queued","seeding","probing"]);function fm({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(bm,{projectName:t}):e.jsx(cm,{projectName:t})})]})}function bm({projectName:t}){const s=as(),[n,a]=l.useState(null),[r,i]=l.useState(""),[o,u]=l.useState("100"),d=Le({...xo({client:Q,path:{name:t},query:{limit:"10"}}),refetchInterval:g=>g.state.data?.some(w=>Sa.has(w.status))?3e3:!1}),h=d.data??[];l.useEffect(()=>{!n&&h[0]&&a(h[0].id)},[n,h]);const x=h.find(g=>g.id===n)??null,c=Le({...po({client:Q,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:x&&Sa.has(x.status)?3e3:!1}),y=c.data??null,N=Le({...go({client:Q,path:{name:t,id:n??""}}),enabled:!!(n&&x?.status==="completed")}),f=tn({mutationFn:()=>{const g={},v=r.trim();v&&(g.icpDescription=v);const w=Number.parseInt(o,10);return Number.isFinite(w)&&w>0&&(g.maxProbes=w),fo(t,g)},onSuccess:async g=>{a(g.sessionId),i(""),await Ar(s,t,g.sessionId),Ne({title:"Discovery started",detail:`Run ${sa(g.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${g.sessionId}`,dedupeMode:"replace"})},onError:g=>{Ne({title:"Discovery failed to start",detail:g instanceof Error?g.message:"Could not start discovery.",tone:"negative"})}}),b=tn({mutationFn:g=>{if(!n)throw new Error("Select a completed discovery session first.");return bo(t,n,g)},onSuccess:async g=>{await Ar(s,t,g.sessionId),s.invalidateQueries({queryKey:ri({client:Q})}),s.invalidateQueries({predicate:v=>Array.isArray(v.queryKey)&&v.queryKey[0]==="projects"&&v.queryKey.length>1}),Ne({title:"Queries added",detail:Nm(g),tone:"positive",dedupeKey:`discovery:promote:${g.sessionId}`,dedupeMode:"replace"})},onError:g=>{Ne({title:"Could not add queries",detail:g instanceof Error?g.message:"Could not add queries from this run.",tone:"negative"})}}),p=y??x,L=N.data??null,E=(L?.queriesByBucket.cited.length??0)+(L?.queriesByBucket.aspirational.length??0),q=l.useMemo(()=>(y?.probes??[]).slice(0,30),[y?.probes]);async function $(){try{const g=await d.refetch();if(g.error)throw g.error;const v=g.data?.length??0;Ne({title:"Discovery sessions refreshed",detail:`${v} recent session${v===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(g){Ne({title:"Discovery refresh failed",detail:g instanceof Error?g.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:Z()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(k,{type:"button",variant:"outline",size:"sm",disabled:d.isFetching,onClick:()=>{$()},children:[e.jsx(sn,{className:`size-3.5 ${d.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(me,{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(oe,{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:g=>i(g.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:o,onChange:g=>u(g.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."})]}),!Z()&&e.jsxs(k,{type:"button",size:"sm",disabled:f.isPending,onClick:()=>f.mutate(),children:[e.jsx(Ms,{size:14}),f.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(me,{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"})]}),d.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),h.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:h.map(g=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===g.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(g.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:sa(g.id)}),e.jsx(oe,{tone:Pr(g.status),children:g.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",g.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",g.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",g.wastedCount??0]})]})]},g.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(me,{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:p?sa(p.id):"No run selected"})]}),p&&e.jsx(oe,{tone:Pr(p.status),children:p.status})]}),p?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Zt,{label:"Questions tested",value:p.probeCount??0}),e.jsx(Zt,{label:"Cited queries",value:p.citedCount??0,tone:"positive"}),e.jsx(Zt,{label:"Worth tracking",value:p.aspirationalCount??0,tone:"caution"}),e.jsx(Zt,{label:"Skip",value:p.wastedCount??0,tone:"negative"})]}),p.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:p.error}),p.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:p.warning}),p.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:p.icpDescription})]}),p.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:p.competitorMap.slice(0,8).map(g=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[g.domain," ",e.jsx("span",{className:"text-muted",children:g.hits})]},g.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),p?.status==="completed"&&e.jsxs(me,{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"})]}),!Z()&&e.jsxs(k,{type:"button",size:"sm",disabled:b.isPending||E===0,onClick:()=>b.mutate(void 0),children:[e.jsx(xi,{size:14}),b.isPending?"Adding…":"Add recommended queries"]})]}),N.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):L?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Zt,{label:"Queries to add",value:E,tone:"positive"}),e.jsx(Zt,{label:"Cited queries",value:L.queriesByBucket.cited.length,tone:"positive"}),e.jsx(Zt,{label:"Worth tracking",value:L.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(Zt,{label:"Skip",value:L.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."}),L.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:L.suggestedCompetitors.map(g=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[g.domain," ",e.jsx("span",{className:"text-muted",children:g.hits})]},g.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(me,{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"})]}),c.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),q.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:q.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:g.query}),e.jsx("td",{children:e.jsx(oe,{tone:jm(g.bucket),children:vm(g.bucket)})}),e.jsx("td",{className:"text-secondary",children:g.citedDomains.length>0?g.citedDomains.slice(0,3).join(", "):"-"})]},g.id))})]})})]})]})]})]})}function Zt({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 Pr(t){return t==="completed"?"positive":t==="failed"?"negative":Sa.has(t)?"caution":"neutral"}function jm(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const ym={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function vm(t){return t?ym[t]:"Not classified"}function sa(t){return t.length>8?t.slice(0,8):t}function Nm(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 Ar(t,s,n){await Promise.all([it(t,"discovery"),t.invalidateQueries({queryKey:jo({client:Q})})])}const wm=100,na=12,Sm=[];function Cm(t){return yi(t.url)}function aa(t){return t>=70?"positive":t>=40?"caution":"negative"}function ra(t){return t>=70?"text-positive-400":t>=40?"text-caution-400":"text-negative-400"}function km(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function wn(t){return t>=70?"Pass":t>=40?"Partial":"Fail"}function Pm(t){return La(Gt(String(t)))}function Am(t){return ns(Gt(String(t)))}function Rm({projectName:t,projectId:s}){const[n,a]=l.useState(!1),[r,i]=l.useState(null),[o,u]=l.useState(null),[d,h]=l.useState(!1),x=l.useRef(null),c=Le(yo({client:Q,path:{name:t},...o?{query:{runId:o}}:{}})),y=Le(vo({client:Q,path:{name:t},query:{limit:30}})),N=Le(No({client:Q,path:{name:t},query:{limit:wm,sort:"score-asc",...o?{runId:o}:{}}})),f=Le({...ii({client:Q,path:{name:t},query:{kind:bs["site-audit"],limit:10}}),refetchOnWindowFocus:"always",refetchInterval:C=>C.state.data?.some(se=>se.status==="queued"||se.status==="running")?3e3:1e4}),b=wo(),p=l.useSyncExternalStore(ei,$n,$n),L=Object.values(p.runs).find(C=>C.kind===bs["site-audit"]&&C.projectId===s),E=f.data??[],q=E.find(C=>C.status==="queued"||C.status==="running"),$=E.at(-1),g=b.isPending||!!L||!!q,v=b.isPending?"starting":q?.status??L?.lastAnnouncedStatus,w=l.useCallback(async()=>{const C=await Promise.all([c.refetch(),y.refetch(),N.refetch()]),U=C.find(se=>se.error);if(U?.error)throw U.error;return C[0]},[N.refetch,c.refetch,y.refetch]);l.useEffect(()=>{o||!$||$.status!=="completed"&&$.status!=="partial"||c.data?.runId===$.id||x.current===$.id||(x.current=$.id,w().catch(C=>{Ne({title:"Technical AEO auto-refresh failed",detail:C instanceof Error?C.message:"Could not load the completed audit.",tone:"negative",dedupeKey:`technical-aeo:auto-refresh:${t}`,dedupeMode:"replace"})}))},[$?.id,$?.status,t,w,c.data?.runId,o]);const ee=async()=>{h(!0);try{const C=await w();Ne({title:"Technical AEO refreshed",detail:g?"The audit is still running. This view will refresh again when it finishes.":C.data?.hasData?`Latest score is ${C.data.aggregateScore}/100 from ${C.data.pagesAudited} audited page${C.data.pagesAudited===1?"":"s"}.`:"No audit data yet. Run an audit to crawl the sitemap.",tone:C.data?.hasData?"positive":"caution",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}catch(C){Ne({title:"Technical AEO refresh failed",detail:C instanceof Error?C.message:"Could not reload technical audit data.",tone:"negative",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}finally{h(!1)}},W=()=>b.mutate({projectName:t,projectId:s}),A=v==="running"?"Audit running":v==="queued"?"Audit queued":"Starting audit",j=c.data,D=N.data?.pages??Sm,S=(j?.pagesErrored??0)>0,V=n&&S,pe=l.useMemo(()=>V?D.filter(C=>C.status==="error"):D,[D,V]),ne=nn({rows:pe,getSearchText:Cm}),X=j?j.pagesAudited>D.length:!1;if(l.useEffect(()=>{a(!1),i(null)},[o]),c.isLoading)return e.jsx("p",{className:"supporting-copy mt-6",children:"Loading technical audit…"});if(!j||!j.hasData)return e.jsxs(me,{className:"surface-card mt-6 p-8 text-center",children:[e.jsx(md,{className:"mx-auto mb-3 h-8 w-8 text-muted","aria-hidden":"true"}),e.jsx("h2",{className:"text-base font-semibold text-heading",children:"No technical audit yet"}),e.jsx("p",{className:"supporting-copy mx-auto mt-2 max-w-md",children:"A technical AEO audit crawls your sitemap and scores every page for structured data, AI-readable content, crawler access, freshness, and more, then rolls it up into one site score."}),!Z()&&e.jsx("div",{className:"mt-5 flex items-center justify-center gap-3",children:e.jsxs(k,{type:"button",onClick:W,disabled:g,children:[g?e.jsx(ga,{className:"mr-1.5 h-4 w-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Ms,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),g?A:"Run first audit"]})}),g?e.jsx("p",{className:"mt-3 text-xs text-muted",role:"status","aria-live":"polite",children:"The dashboard will refresh automatically when the audit finishes."}):null]});const te=j.deltaScore==null?null:`${j.deltaScore>=0?"+":""}${j.deltaScore} vs previous`,ce=j.trend==="up"?"positive":j.trend==="down"?"negative":"neutral",B=y.data?.points??[],G=B.map(C=>({runId:C.runId,date:C.auditedAt,score:C.aggregateScore})),P=o!==null,re=D.filter(C=>C.status==="success");function le(C){const U=[];for(const se of re){const M=se.factors.find(z=>z.id===C);M&&M.score<70&&U.push({url:se.url,score:M.score})}return U.sort((se,M)=>se.score-M.score)}return e.jsxs("div",{className:"mt-6",children:[e.jsxs("section",{className:"surface-card flex flex-wrap items-start justify-between gap-6 rounded-lg border border-default bg-surface p-6",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:P?"Technical AEO history":"Technical AEO"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-baseline gap-3",children:[e.jsx("span",{className:`text-4xl font-semibold tabular-nums ${ra(j.aggregateScore)}`,children:j.aggregateScore}),e.jsx("span",{className:"text-lg text-muted",children:"/ 100"}),e.jsx(oe,{tone:aa(j.aggregateScore),children:wn(j.aggregateScore)}),te?e.jsx(oe,{tone:ce,children:te}):null,g?e.jsx(oe,{tone:"neutral",children:A}):null]}),e.jsxs("p",{className:"supporting-copy mt-2 tabular-nums",children:[j.pagesDiscovered," URL",j.pagesDiscovered===1?"":"s"," in sitemap · ",j.pagesAudited," audited · ",j.pagesSkipped," skipped · ",j.pagesErrored," errored"]}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-xs text-muted",children:[e.jsx("span",{className:"text-faint",children:"Sitemap:"}),e.jsx("a",{href:j.sitemapUrl??"#",target:"_blank",rel:"noreferrer",className:"max-w-[22rem] truncate text-secondary underline decoration-mono-700 underline-offset-2 hover:text-strong",children:j.sitemapUrl}),e.jsx(Ze,{text:"Every audit re-reads this sitemap, so pages you add or remove are picked up on the next run. Discovered/audited counts and the score reflect the sitemap at the time of the latest run. Override it with `canonry technical-aeo run <project> --sitemap-url <url>`."})]}),j.auditedAt?e.jsxs("p",{className:"mt-0.5 text-xs text-faint",children:["Audited ",new Date(j.auditedAt).toLocaleString()]}):null,g?e.jsx("p",{className:"mt-1 text-xs text-muted",role:"status","aria-live":"polite",children:"Results refresh automatically when this audit finishes."}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[B.length>1?e.jsxs("select",{"aria-label":"View a Technical AEO audit",value:o??"",onChange:C=>u(C.target.value||null),className:"min-h-11 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:[e.jsx("option",{value:"",children:"Latest audit"}),[...B].reverse().slice(1).map(C=>e.jsxs("option",{value:C.runId,children:[new Date(C.auditedAt).toLocaleDateString()," · ",C.aggregateScore,"/100"]},C.runId))]}):null,e.jsxs(k,{type:"button",variant:"outline",size:"sm",onClick:()=>{ee()},disabled:d,children:[e.jsx(sn,{className:`mr-1.5 h-4 w-4 ${d?"motion-safe:animate-spin":""}`,"aria-hidden":"true"}),d?"Refreshing…":"Refresh"]}),!Z()&&e.jsxs(k,{type:"button",size:"sm",onClick:W,disabled:g,children:[g?e.jsx(ga,{className:"mr-1.5 h-4 w-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Ms,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),g?A:"Re-run audit"]})]})]}),G.length>=2?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h2",{children:"Site score over time"})]}),e.jsxs("div",{className:"mt-3 h-56",children:[e.jsxs("p",{className:"sr-only",children:["Technical AEO scores range from ",Math.min(...G.map(C=>C.score))," to ",Math.max(...G.map(C=>C.score))," across ",G.length," audits. Use the audit selector to inspect a previous scorecard."]}),e.jsx("div",{className:"h-full","aria-hidden":"true",children:e.jsx(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:G,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ma,{stroke:Ia,vertical:!1}),e.jsx(Es,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:Ht},tickFormatter:Pm,minTickGap:24}),e.jsx(qs,{domain:[0,100],ticks:[0,25,50,75,100],tick:Lt,tickLine:!1,axisLine:!1,width:32}),e.jsx(Os,{...gs,cursor:{stroke:Ht,strokeWidth:1},labelFormatter:Am,formatter:C=>[`${C}/100`,"Site score"]}),e.jsx(Ta,{type:"monotone",dataKey:"score",name:"score",stroke:Qt.positive,strokeWidth:2.5,dot:{r:2.5,fill:Qt.positive,strokeWidth:0},isAnimationActive:!1})]})})})]})]}):null,e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Scorecard"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Ranking factors",e.jsx(Ze,{text:"Each factor is scored 0–100 per page (via the aeo-audit engine), then averaged across all successfully-audited pages. Pass ≥70, partial 40–69, fail <40. Expand a row to see which pages fall short and how to fix it."})]})]}),e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Factor"}),e.jsx("th",{className:"text-right",children:"Weight"}),e.jsx("th",{className:"text-right",children:"Avg"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Pass / Partial / Fail"})]})}),e.jsx("tbody",{children:j.factors.map(C=>{const U=r===C.id,se=j.crossCuttingIssues.find(we=>we.factorId===C.id),M=U?le(C.id):[],z=C.pagesPartial+C.pagesFailing;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:U?"bg-surface":void 0,children:[e.jsx("td",{children:e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-left font-medium text-strong hover:text-primary","aria-expanded":U,onClick:()=>i(U?null:C.id),children:[U?e.jsx($a,{className:"h-3.5 w-3.5 shrink-0 text-muted","aria-hidden":"true"}):e.jsx(Aa,{className:"h-3.5 w-3.5 shrink-0 text-muted","aria-hidden":"true"}),C.name]})}),e.jsxs("td",{className:"text-right tabular-nums text-muted",children:[C.weight,"%"]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:C.avgScore}),e.jsx("td",{children:e.jsx(oe,{tone:km(C.status),children:wn(C.avgScore)})}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[e.jsx("span",{className:"text-positive-400",children:C.pagesPassing})," / ",e.jsx("span",{className:"text-caution-400",children:C.pagesPartial})," / ",e.jsx("span",{className:"text-negative-400",children:C.pagesFailing})]})]}),U?e.jsx("tr",{className:"bg-surface",children:e.jsx("td",{colSpan:5,className:"px-4 pb-4 pt-0",children:e.jsxs("div",{className:"space-y-4 border-l border-base pl-4",children:[se&&se.topRecommendations.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-1.5 text-muted",children:"How to fix"}),e.jsx("ul",{className:"space-y-1",children:se.topRecommendations.map((we,Oe)=>e.jsxs("li",{className:"flex gap-2 text-sm text-neutral",children:[e.jsx("span",{className:"select-none text-faint",children:"→"}),e.jsx("span",{children:we})]},Oe))})]}):z===0?e.jsx("p",{className:"text-sm text-muted",children:"Every audited page passes this factor."}):null,z>0?e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft mb-1.5 text-muted",children:["Pages below pass (",z,")"]}),e.jsx("ul",{className:"space-y-1",children:M.slice(0,na).map(we=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`w-8 shrink-0 text-right tabular-nums ${ra(we.score)}`,children:we.score}),e.jsx("a",{href:we.url,target:"_blank",rel:"noreferrer",className:"truncate text-neutral hover:text-heading",title:we.url,children:we.url})]},we.url))}),M.length>na?e.jsxs("p",{className:"mt-1 text-xs text-faint",children:["+ ",M.length-na," more below pass"]}):null,X?e.jsxs("p",{className:"mt-1 text-xs text-faint",children:["Showing the worst ",D.length," audited pages."]}):null]}):null]})})}):null]},C.id)})})]})})]}),j.crossCuttingIssues.length>0?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Opportunities"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Prioritized fixes",e.jsx(Ze,{text:"Factors scoring below pass across the most pages, ranked by site-wide impact. Fixing one of these typically lifts many pages at once."})]})]}),e.jsx("div",{className:"mt-3 divide-y divide-mono-800/60 overflow-hidden rounded-lg border border-default",children:j.crossCuttingIssues.map(C=>e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:C.factorName}),e.jsx(oe,{tone:aa(C.avgScore),children:wn(C.avgScore)}),e.jsxs("span",{className:"text-xs tabular-nums text-muted",children:["avg ",C.avgScore," · affects ",C.affectedPages," of ",C.totalPages," pages (",C.affectedPct,"%)"]})]}),C.topRecommendations.length>0?e.jsx("ul",{className:"mt-2 space-y-1",children:C.topRecommendations.map((U,se)=>e.jsxs("li",{className:"flex gap-2 text-sm text-secondary",children:[e.jsx("span",{className:"select-none text-faint",children:"→"}),e.jsx("span",{children:U})]},se))}):null]},C.factorId))})]}):null,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:"Pages"}),e.jsx("h2",{children:"Per-page breakdown"})]}),S?e.jsxs("div",{className:"segmented",role:"group","aria-label":"Filter pages",children:[e.jsxs("button",{type:"button",onClick:()=>{a(!1),ne.setPage(1)},"aria-pressed":!V,className:`segmented-option min-h-11 tabular-nums ${V?"":"segmented-option-active"}`,children:["All ",j.pagesAudited]}),e.jsxs("button",{type:"button",onClick:()=>{a(!0),ne.setPage(1)},"aria-pressed":V,className:`segmented-option min-h-11 tabular-nums ${V?"segmented-option-active text-negative":""}`,children:["Errors ",j.pagesErrored]})]}):null]}),D.length>0?e.jsx(As,{value:ne.query,onChange:ne.setQuery,label:"Filter audited page URLs",placeholder:"Filter page URL or query parameters",className:"mt-3 max-w-md"}):null,ne.totalRows===0?e.jsx("p",{className:"supporting-copy mt-3",children:ne.hasQuery?"No pages match this filter.":"No pages recorded."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right",children:"Score"}),e.jsx("th",{children:"Status"}),e.jsx("th",{className:"w-full",children:"URL"})]})}),e.jsx("tbody",{children:ne.rows.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-right tabular-nums",children:C.status==="error"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-negative-400",children:[e.jsx(So,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"err"]}):e.jsx("span",{className:ra(C.overallScore),children:C.overallScore})}),e.jsx("td",{children:C.status==="error"?e.jsx(oe,{tone:"negative",children:"Error"}):e.jsx(oe,{tone:aa(C.overallScore),children:wn(C.overallScore)})}),e.jsx("td",{className:"w-full max-w-0",children:e.jsx("a",{href:C.url,target:"_blank",rel:"noreferrer",className:"block truncate text-neutral hover:text-heading",title:C.status==="error"?C.error??C.url:C.url,children:e.jsx(Xs,{value:C.url,headLength:54,tailLength:20,title:C.status==="error"?C.error??C.url:C.url})})})]},C.url))})]})}),e.jsx(fs,{page:ne.page,pageSize:ne.pageSize,visibleRows:ne.rows.length,totalRows:ne.totalRows,onPageChange:ne.setPage,itemLabel:ne.hasQuery?"matches":"rows"}),X?e.jsxs("p",{className:"mt-2 text-xs text-faint",children:["Showing the worst ",D.length," of ",j.pagesAudited," audited pages."]}):null]})]})]})}function Rr(t){return`${(t*100).toFixed(1)}%`}function $m({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[i,o]=l.useState(null),u=Le({...Co({client:Q,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=Le({...ii({client:Q,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(d.data??[]).filter(p=>(p.status==="completed"||p.status==="partial")&&p.trigger!=="probe").reverse(),x=i??h[0]?.id??"",c=a??h.find(p=>p.id!==x)?.id??"",y=!!(c&&x&&c!==x),N=Le({...ko({client:Q,path:{name:t},query:{run1:c,run2:x}}),enabled:s==="compare"&&y}),f=u.data??[],b=N.data?.diff.filter(p=>p.changed||p.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(([p,L])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===p,className:`filter-chip ${s===p?"filter-chip-active":""}`,onClick:()=>n(p),children:L},p))}),s==="changes"?e.jsx(rd,{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&&f.length===0?e.jsxs(me,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:"Complete an answer visibility sweep to create the first snapshot."})]}):null,f.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:f.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(p.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[p.mentionedPairs,"/",p.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Rr(p.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[p.citedPairs,"/",p.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Rr(p.overallCitedRate)})]},p.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:c,onChange:p=>r(p.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(p=>e.jsx("option",{value:p.id,children:new Date(p.createdAt).toLocaleString()},p.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:x,onChange:p=>o(p.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(p=>e.jsx("option",{value:p.id,children:new Date(p.createdAt).toLocaleString()},p.id))})]})]}),d.isLoading||N.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!d.isLoading&&h.length<2?e.jsxs(me,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:"Run another answer visibility sweep before comparing historical evidence."})]}):null,N.data&&b.length===0?e.jsxs(me,{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,b.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:b.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:p.query??"Archived query"}),e.jsx("td",{children:e.jsxs(oe,{tone:p.changed?"caution":"neutral",children:[p.run1State??"none"," → ",p.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(oe,{tone:p.visibilityChanged?"caution":"neutral",children:[p.run1MentionState??"none"," → ",p.run2MentionState??"none"]})})]},p.queryId??p.query??"unknown"))})]})}):null]}):null]})}const ia=20,Vt=50,Im=50,Lm=50;function qa(t){return t==="viewer"}function Oa(t){return t?.status==="unavailable"}function Ei(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function qi(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 Sn(t,s,n){if(t.kind==="all")return s.map(i=>i.id);if(t.kind==="specific")return s.filter(i=>t.propertyIds.includes(i.id)).map(i=>i.id);const a=new Set(t.groupIds),r=new Set(n.filter(i=>a.has(i.id)).flatMap(i=>i.propertyIds));return s.filter(i=>r.has(i.id)).map(i=>i.id)}function Mm(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(i=>i.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function la(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 $r(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Ir(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 Cn(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 Ca(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function oa(t){return Ca(t)?"Unavailable tracked question":t.text?.trim()||"Unavailable tracked question"}function ka({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[i,o]=l.useState(""),[u,d]=l.useState(!1),h=i.trim().toLocaleLowerCase(),x=h?t.filter(f=>f.label.toLocaleLowerCase().includes(h)):t,c=u?x:x.slice(0,Im),y=c.length<x.length;function N(){const f=new Set([...s,...c.map(b=>b.id)]);n(t.filter(b=>f.has(b.id)).map(b=>b.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:i,onChange:f=>o(f.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:c.length===0,onClick:N,children:"Select all shown"}),e.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),x.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 ",c.length," of ",x.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:c.map(f=>{const b=s.includes(f.id);return e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-sm text-primary",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{"aria-label":`Select ${f.label}`,checked:b,type:"checkbox",onChange:p=>n(Ei(s,f.id,p.currentTarget.checked))}),e.jsx("span",{children:f.label})]}),f.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[f.urlCount," URLs"]})]},f.id)})}),y?e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function Fa(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(oe,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function _a({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(oe,{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 Tm({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[i,o]=l.useState(null),u=t.preview,d=u?.counts.needsAttention??0,h=u?.rows.filter(w=>w.status==="matched")??[],x=u?.rows??[],c=x.filter(w=>w.status!=="matched"),y=Math.max(1,Math.ceil(x.length/Vt)),N=Math.min(s,y-1),f=x.slice(N*Vt,(N+1)*Vt),b=Math.max(1,Math.ceil(c.length/Vt)),p=Math.min(a,b-1),L=c.slice(p*Vt,(p+1)*Vt),E=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,q=h.length>0&&!t.isApplying,$=u!==null&&i===u.previewChecksum,g=c.length>0&&p===b-1;l.useEffect(()=>{n(0),r(0),o(null)},[u?.previewChecksum]);async function v(w){if(w)try{t.onCsvChange(await w.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:w=>{v(w.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:w=>t.onCsvChange(w.currentTarget.value),placeholder:`property,group,url
7
+ 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(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!E,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",d>0?` · ${d} need${d===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(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:w.label}),e.jsx("td",{className:"text-secondary",children:w.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:w.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[w.addedTargetKeys.length,w.unchangedTargetKeys.length>0?` · ${w.unchangedTargetKeys.length} already members`:""]})]},w.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:f.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:w.dataRow}),e.jsx("td",{className:"text-heading",children:w.property}),e.jsx("td",{className:"text-secondary",children:w.group}),e.jsxs("td",{children:[e.jsx(oe,{tone:$r(w.status),children:Ir(w.status)}),Cn(w)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Cn(w)}):null]})]},w.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",N+1," of ",y," · ",u.rows.length," rows"]}),e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:N===0,onClick:()=>n(w=>Math.max(0,w-1)),children:"Previous 50 rows"}),e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:N===y-1,onClick:()=>n(w=>Math.min(y-1,w+1)),children:"Next 50 rows"})]})]}):null,d>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",d," row",d===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:L.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:w.dataRow}),e.jsx("td",{className:"text-heading",children:w.property}),e.jsx("td",{className:"text-secondary",children:w.group}),e.jsxs("td",{children:[e.jsx(oe,{tone:$r(w.status),children:Ir(w.status)}),Cn(w)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Cn(w)}):null]})]},w.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 ",p+1," of ",b]}),e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===0,onClick:()=>r(w=>Math.max(0,w-1)),children:"Previous 50 exceptions"}),e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===b-1,onClick:()=>r(w=>Math.min(b-1,w+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:$,disabled:t.isApplying||!g,onChange:w=>o(w.currentTarget.checked?u.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",d," row",d===1?"":"s"," will be skipped."]}),e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!q||!$,onClick:()=>{t.onApply(h.map(w=>w.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(k,{type:"button",className:"mt-3 min-h-11",disabled:!q,onClick:()=>{t.onApply(h.map(w=>w.dataRow))},children:t.isApplying?"Creating groups…":`Create ${u.counts.groupsReady} group${u.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const Dm="—";function Em({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:i=!1,isBusy:o=!1,canContinue:u=!0,onSelectedQueryIdsChange:d,onApplySelectedQueries:h,onClearQueryAssignments:x,onRemoveQuery:c,onCreateQueries:y,onCreateAndPairQuestions:N,isCreatingQueries:f=!1,createQueriesError:b=null,onManageProjectQueries:p,groups:L,audience:E,onAudienceChange:q,assignmentImpact:$=null,isPreviewingAssignmentImpact:g=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:w,assignmentNotice:ee=null,onReplaceAssignments:W,isReplacingAssignments:A=!1,onBack:j,onContinue:D}){const[S,V]=l.useState(""),[pe,ne]=l.useState(!1),[X,te]=l.useState(!1),[ce,B]=l.useState(""),[G,P]=l.useState(""),[re,le]=l.useState(null);if(Oa(s))return e.jsx("section",{"aria-label":"Questions",children:e.jsx(_a,{message:s.message})});const C=qa(t),U=E,se=q,M=Sn(U,n,L),z=M.length,we=z>0&&r.length>0&&!i&&!o&&!g&&$!==null&&v===null,Oe=x??c,K=S.trim().toLocaleLowerCase(),ge=K?a.filter(_=>oa(_).toLocaleLowerCase().includes(K)):a,Te=ge.filter(_=>(_.propertyIds?.length??0)===0),je=X?Te:ge,Be=pe?je:je.slice(0,Lm),et=Be.filter(_=>!Ca(_)),Me=[...new Set(ce.split(`
8
+ `).map(_=>_.trim()).filter(Boolean))],J=[...G.matchAll(/\{([a-z][\w-]*)\}/gi)].map(_=>_[1]),De=n.filter(_=>M.includes(_.id)),xe=J.length===0||G.trim()===""?[]:De.map(_=>({propertyId:_.id,text:J.reduce((fe,Ee)=>fe.replaceAll(`{${Ee}}`,_.label),G.trim())})),Qe=[...new Set(xe.map(_=>_.text))];function O(){const _=new Set([...r,...et.map(fe=>fe.id)]);d(a.filter(fe=>_.has(fe.id)).map(fe=>fe.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:"Questions"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose questions, then apply them to Properties."})]})}),C?e.jsx(Fa,{}):null,C?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:U.kind==="all"?"all":U.kind==="specific"?"specific":`group:${U.groupIds[0]??""}`,onChange:_=>{const fe=_.currentTarget.value;fe==="all"?se({kind:"all"}):fe==="specific"?se({kind:"specific",propertyIds:[]}):fe.startsWith("group:")&&se({kind:"groups",groupIds:[fe.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]}),L.length>0?e.jsx("optgroup",{label:"Groups",children:L.map(_=>{const fe=Sn({kind:"groups",groupIds:[_.id]},n,L).length;return e.jsx("option",{value:`group:${_.id}`,disabled:fe===0,children:la(_,n)},_.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),U.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:U.groupIds.map(_=>{const fe=L.find(Ee=>Ee.id===_);return fe?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:[la(fe,n),e.jsx("button",{type:"button","aria-label":`Remove ${fe.name}`,className:"-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>{const Ee=U.groupIds.filter(Ue=>Ue!==fe.id);se(Ee.length>0?{kind:"groups",groupIds:Ee}:{kind:"all"})},children:"×"})]},fe.id):null})}),L.some(_=>!U.groupIds.includes(_.id)&&Sn({kind:"groups",groupIds:[_.id]},n,L).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:_=>{_.currentTarget.value&&se({kind:"groups",groupIds:[...U.groupIds,_.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"}),L.filter(_=>!U.groupIds.includes(_.id)).map(_=>{const fe=Sn({kind:"groups",groupIds:[_.id]},n,L).length;return e.jsx("option",{value:_.id,disabled:fe===0,children:la(_,n)},_.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,U.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(ka,{legend:"Specific Properties",properties:n,selectedPropertyIds:U.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:_=>{se({kind:"specific",propertyIds:_})}})}):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 questions."})]}),C||!y?null:e.jsxs("details",{open:a.length===0,className:"border-y border-default py-4",children:[e.jsx("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:"Add questions"}),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 questions you want to track":"Add more questions"}),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 questions, one per line",className:"w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:4,value:ce,onChange:_=>B(_.currentTarget.value),placeholder:`best apartments in dallas
9
+ luxury apartments atlanta
10
+ pet friendly apartments austin`}),b?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:b}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Me.length===0||f||o,onClick:()=>{Promise.resolve(y(Me)).then(()=>B(""),()=>{})},children:f?"Adding…":`Add ${Me.length||""} question${Me.length===1?"":"s"}`.replace(" "," ")}),p?e.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:o,onClick:p,children:"Manage project questions"}):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 question 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 question per selected Property."]}),e.jsx("input",{"aria-label":"Question 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:G,onChange:_=>P(_.target.value),placeholder:"apartments near {property}"}),G.trim()===""?null:J.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 question."]}):De.length===0?e.jsx("p",{className:"mt-2 text-sm text-caution",children:"Select at least one Property to write questions 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:[Qe.length," question",Qe.length===1?"":"s",", one per selected Property:"]}),e.jsx("ul",{className:"mt-1 mb-0 list-none space-y-0.5 p-0",children:Qe.slice(0,3).map(_=>e.jsx("li",{className:"text-sm text-strong",children:_},_))}),Qe.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",Qe.length-3," more"]}):null]}),e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:xe.length===0||f||o||!N,onClick:()=>{N&&Promise.resolve(N(xe)).then(()=>P(""),()=>{})},children:f?"Adding…":`Add ${xe.length||""} question${xe.length===1?"":"s"}`.replace(" "," ")}),xe.length>0?e.jsxs("p",{className:"mt-2 mb-0 text-sm text-secondary",children:["Each question is measured on the one Property it names, so this adds"," ",xe.length," assignment",xe.length===1?"":"s","."]}):null]})]})]}),C?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(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:et.length===0,onClick:O,children:"Select all shown questions"}),e.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>d([]),children:"Clear question selection"}),e.jsx(k,{type:"button",size:"sm",className:"min-h-11",disabled:!we,onClick:()=>{h({queryIds:r,propertyIds:M,...U.kind==="groups"?{groupIds:U.groupIds}:{}})},children:i?"Assigning questions…":`Assign ${r.length||""} question${r.length===1?"":"s"} to ${Mm(U,L,z)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[g?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,$?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," question",r.length===1?"":"s"," → ",$.assignmentCount," Property assignment",$.assignmentCount===1?"":"s"," · ",$.addedAssignments," new, ",$.alreadyPresentAssignments," already assigned"," · ",$.fullRunProviderCalls," provider request",$.fullRunProviderCalls===1?"":"s"," per full run"," · ",$.addedProviderCalls," new",U.kind==="groups"?` · ${$.resolvedPropertyCount} unique ${$.resolvedPropertyCount===1?"Property":"Properties"}${$.overlapCount>0?`, ${$.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}),w?e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:w,children:"Retry impact"}):null,j?e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:j,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," question",r.length===1?"":"s"," × ",z," Properties = ",r.length*z," assignments"]})]}),ee?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:ee}):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 questions"}),e.jsx("input",{type:"search",value:S,onChange:_=>{V(_.currentTarget.value),ne(!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:"Question 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 ",Be.length," of ",je.length," questions,"," ",ge.length-Te.length," of ",ge.length," applied"]}),C||Te.length===0?null:e.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{te(_=>!_),ne(!1)},children:X?"Show all questions":`Show the ${Te.length} not applied`})]})]}):null,Be.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:[C?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select question"})}),e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Properties"}),C?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear question assignments"})})]})}),e.jsx("tbody",{children:Be.map(_=>{const fe=Ca(_),Ee=oa(_),Ue=r.includes(_.id),Ve=(_.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[C?null:fe?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 question ${Ee}`,checked:Ue,type:"checkbox",onChange:Nt=>d(Ei(r,_.id,Nt.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:Ee})}),e.jsx("td",{className:"text-secondary",children:qi(_.propertyIds??[],n)}),C?null:e.jsx("td",{className:"text-right",children:Ve?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[W?e.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:o||A,onClick:()=>le({queryId:_.id,propertyIds:[..._.propertyIds??[]]}),"aria-label":`Replace question assignments for ${Ee}`,children:"Replace assignments"}):null,e.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:o,onClick:()=>{Oe(_.id)},"aria-label":`Clear question assignments for ${Ee}`,children:"Clear assignments"})]}):null})]},_.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No questions match this search."}):null,C||!re?null:(()=>{const _=a.find(Ue=>Ue.id===re.queryId),fe=_?oa(_):"this question",Ee=re.propertyIds.filter(Ue=>n.some(Ve=>Ve.id===Ue));return e.jsxs("section",{"aria-labelledby":"advanced-measurement-replace-assignments-title",className:"border-y border-default py-4",children:[e.jsx("h4",{id:"advanced-measurement-replace-assignments-title",className:"text-sm font-medium text-heading",children:"Replace assigned Properties"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:["This replaces every Property assigned to “",fe,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(ka,{legend:"Properties for this question",properties:n,selectedPropertyIds:Ee,onSelectedPropertyIdsChange:Ue=>le(Ve=>Ve&&{...Ve,propertyIds:[...Ue]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:A||o,onClick:()=>le(null),children:"Keep current assignments"}),e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ee.length===0||A||o||!W,onClick:()=>{W&&Promise.resolve(W({queryId:re.queryId,propertyIds:Ee}))},children:A?"Replacing assignments…":`Replace with ${Ee.length} ${Ee.length===1?"Property":"Properties"}`})]})]})})(),Be.length<je.length?e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>ne(!0),children:"Show all questions"}):null,C?null:e.jsxs(e.Fragment,{children:[u?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one question to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${j?"justify-between":"justify-end"}`,children:[j?e.jsx(k,{type:"button",variant:"outline",className:"min-h-11",disabled:o,onClick:j,children:"Back"}):null,e.jsx(k,{type:"button",variant:we?"outline":"default",className:"min-h-11",disabled:!u||o,onClick:D,children:"Continue"})]})]})]})}function qm({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:i=!1,onGroupDraftChange:o,onSaveGroup:u,onEditGroup:d,onRemoveGroup:h,onClearGroupDraft:x,membershipImport:c,onBack:y,onContinue:N}){if(Oa(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(_a,{message:s.message})});const f=qa(t),b=r.name.trim().length>0&&r.propertyIds.length>0&&!i,p=n.filter($=>r.propertyIds.includes($.id)).length,L=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,E=!f&&(d!==void 0||h!==void 0);function q(){if(x){x();return}o({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 questions by market and compare competitors."})]})}),f?e.jsx(Fa,{}):null,f||!c?null:e.jsx(Tm,{value:c}),f?null:e.jsxs("div",{className:"space-y-4 border-y border-default py-4",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Group name"}),e.jsx("input",{"aria-label":"Group name",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.name,onChange:$=>o({...r,name:$.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:[p," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(ka,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:$=>o({...r,propertyIds:$})})})]}),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:$=>o({...r,competitorDomains:$.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!b,onClick:()=>{u(r)},children:i?"Saving group…":"Save group"}),e.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!L,onClick:q,children:"Clear form"}),e.jsx("p",{className:"text-sm text-secondary",children:"Competitor domains are used only in this group's competitor report. Membership changes affect future assignments only."})]}),L?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"}),E?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map($=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:$.name}),e.jsx("td",{className:"text-secondary",children:qi($.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:$.competitors.length>0?$.competitors.join(", "):"None"}),E?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[d?e.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${$.name}`,onClick:()=>d($),children:"Edit"}):null,h?e.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${$.name}`,onClick:()=>{h($.id)},children:"Remove"}):null]})}):null]},$.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,f?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${y?"justify-between":"justify-end"}`,children:[y?e.jsx(k,{type:"button",variant:"outline",className:"min-h-11",onClick:y,children:"Back"}):null,e.jsx(k,{type:"button",className:"min-h-11",disabled:L,onClick:N,children:a.length===0&&!L?"Continue without groups":"Continue"})]})]})}function Om({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:i,onReviewChanges:o,isReviewing:u=!1,canReviewChanges:d=!0,reviewedChanges:h,reviewChangesError:x,canPublish:c,isPublishing:y=!1,onPublish:N}){const[f,b]=l.useState(ia),[p,L]=l.useState(ia),[E,q]=l.useState(ia);if(Oa(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(_a,{message:s.message})});const $=qa(t),g=r?.items??[],v=r?.coverageItems??[],w=g.slice(0,f),ee=v.slice(0,p),W=a.slice(0,E),A=o!==void 0,j=h!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),$?e.jsx(Fa,{}):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,")"]}),g.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:w.map(D=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:D.url}),e.jsx("p",{className:"mt-1 text-secondary",children:D.reason})]},`${D.url}-${D.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 ",w.length," of ",g.length]}),w.length<g.length?e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>b(D=>D+Vt),children:"Show next 50 URLs"}):null]})]}):null,$?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,")"]}),ee.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[ee.map(D=>e.jsxs("section",{"aria-label":`${D.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:D.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:D.savedUrls.map(S=>e.jsx("li",{className:"break-all text-secondary",children:S},S))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),D.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:D.currentSitemapUrls.map(S=>e.jsx("li",{className:"break-all text-secondary",children:S},S))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},D.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",ee.length," of ",v.length]}),ee.length<v.length?e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>L(D=>D+Vt),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(k,{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:"Questions"}),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??Dm})]})})]})}),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," question",n.queries===1?"":"s"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a question aimed at a market is measured on every Property in it."]}):null,h?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:h.title}),h.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:h.items.map((D,S)=>e.jsx("li",{children:D},`${D}-${S}`))}):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:W.map(D=>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:D.title}),D.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:D.detail}):null]}),e.jsx(oe,{tone:D.tone??"caution",children:"Needs attention"})]},D.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",W.length," of ",a.length]}),W.length<a.length?e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>q(D=>D+Vt),children:"Show next 50 exceptions"}):null]})]})]}),$?null:e.jsxs(e.Fragment,{children:[A&&x?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:x}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${i?"justify-between":"justify-end"}`,children:[i?e.jsx(k,{type:"button",variant:"outline",className:"min-h-11",onClick:i,children:"Back"}):null,o!==void 0&&!j?e.jsx(k,{type:"button",className:"min-h-11",disabled:u||!d,onClick:()=>{o()},children:u?"Reviewing changes…":"Review changes"}):e.jsx(k,{type:"button",className:"min-h-11",disabled:!c||y,onClick:()=>{N()},children:y?"Publishing setup…":"Publish setup"})]})]})]})}const Fm={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function _m(t){return t.trim().toLocaleLowerCase()}function Um(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function Gm({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 Bm({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const i=!t||r==="reviewing",o=i||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function u(d,h){n({...s,[d]:h})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":r==="reviewing",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-import-heading",className:"text-lg font-semibold text-heading",children:"Import Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review sitemap entries before choosing the Properties to measure."})]}),t?null:e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm text-secondary",children:[e.jsx(oe,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:d=>{d.preventDefault(),!o&&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:i,onChange:d=>u("sitemapUrl",d.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:i,onChange:d=>u("examplePropertyUrl",d.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:i,onChange:d=>u("preferredHost",d.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:i,onChange:d=>u("propertyPathPattern",d.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:i,onChange:d=>u("additionalHost",d.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:i,onChange:d=>u("additionalPathPattern",d.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:i,onChange:d=>u("excludedPaths",d.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(k,{type:"submit",disabled:o,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function zm({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:i,onSelectedPropertyIdsChange:o,onContinue:u,isContinuing:d=!1,onRetryProperties:h,onReturnToImport:x,maxVisibleProperties:c,onShowAllProperties:y}){const N=_m(a),f=s.filter(W=>Um(W,N)),b=Math.max(1,c??f.length),p=f.slice(0,b),L=new Set(i),E=s.filter(W=>L.has(W.id)).map(W=>W.id),q=p.length<f.length;function $(W){const A=new Set(W);o(s.filter(j=>A.has(j.id)).map(j=>j.id))}function g(W,A){if(!t||d)return;const j=new Set(E);A?j.add(W):j.delete(W),$(j)}function v(){!t||d||$([...E,...p.map(W=>W.id)])}function w(){!t||d||o([])}function ee(){!t||d||E.length===0||u(E)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||d,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:x,children:"Review sitemap"})]}):null,n==="ready"&&s.length>0?e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:a,disabled:d,onChange:W=>r(W.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(k,{type:"button",variant:"outline",size:"sm",disabled:d,onClick:v,children:"Select all shown"}),e.jsx(k,{type:"button",variant:"ghost",size:"sm",disabled:d||E.length===0,onClick:w,children:"Clear selection"})]}):null]}),f.length===0?e.jsxs("div",{className:"mt-4 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties match this search."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Clear the search or review the sitemap again."}),e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:x,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 ",p.length," of ",f.length," Properties"]}),e.jsxs("p",{children:[E.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:p.map(W=>{const A=Fm[W.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:W.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(Gm,{property:W})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(oe,{tone:A.tone,children:A.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 ${W.name}`,checked:E.includes(W.id),disabled:d,onChange:j=>g(W.id,j.target.checked),className:"size-6 accent-accent"})})}):null]},W.id)})})]})}),q&&y?e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:d,onClick:y,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(k,{type:"button",variant:"ghost",disabled:d,onClick:x,children:"Back"}),e.jsx(k,{type:"button",disabled:d||E.length===0,onClick:ee,children:d?"Saving Properties…":"Continue"})]}):null]}):null]})}function Vm(t){return t.activeStep==="import"?e.jsx(Bm,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(zm,{...t})}const Km=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Questions"},{id:"review",label:"Review and publish"}];function Qm({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:i}){const o=l.useRef(null),u=l.useRef(null),d=l.useRef(null),h=l.useRef(null),x=l.useRef(!1),[c,y]=l.useState(!1);return l.useEffect(()=>{s||y(!1)},[s]),l.useEffect(()=>{const N=x.current;x.current=c,c?d.current?.focus():N&&h.current?.focus()},[c]),l.useEffect(()=>{const N=o.current;if(o.current=t,N===null||N===t)return;const f=u.current?.querySelector('h1, h2, h3, [role="heading"]');f&&(f.tabIndex=-1,f.focus())},[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 w-full sm:flex-1",children:[e.jsx("h2",{children:"Advanced measurement setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties and questions 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(oe,{tone:"caution",children:"Unpublished changes"}),n&&a?c?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(k,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>y(!1),children:"Keep editing"}),e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(k,{ref:h,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>y(!0),children:"Discard changes"}):null]}):null]}),e.jsx("div",{role:"group","aria-label":"Advanced measurement setup progress",className:"overflow-x-auto border-b border-default",children:e.jsx("ol",{className:"flex min-w-max gap-6",children:Km.map(N=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===N.id?"step":void 0,onClick:()=>r(N.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===N.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:N.label}):e.jsx("span",{"aria-current":t===N.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===N.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:N.label})},N.id))})}),e.jsx("div",{ref:u,children:i})]})}function Hm(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Vm,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(Em,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(qm,{...t.groups,access:s}):"review"in t?e.jsx(Om,{...t.review,access:s}):null}function kn(t){return e.jsx(Qm,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Hm(t)})}function Oi(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function xt(t){return{"If-Match":t,"Idempotency-Key":Oi()}}function ds(t){return t instanceof Ls&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function $t(t,s){return t instanceof Ls?s:(t instanceof Error?t.message.trim():"")||s}function Wm(t){const s="Could not calculate assignment impact.";if(!(t instanceof Ls)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const Ym={loadSetup:t=>We(()=>Ho({client:Q,path:{name:t}})),loadDraft:t=>We(()=>Qo({client:Q,path:{name:t}})),createDraft:(t,s)=>We(()=>Ko({client:Q,path:{name:t},headers:{"Idempotency-Key":Oi()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>We(()=>Vo({client:Q,path:{name:t},headers:xt(s),body:n})),applySitemapSelection:(t,s,n,a)=>We(()=>zo({client:Q,path:{name:t},headers:xt(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>We(()=>Bo({client:Q,path:{name:t},body:s})),applyAssignments:(t,s,n)=>We(()=>Go({client:Q,path:{name:t},headers:xt(s),body:n})),replaceAssignments:(t,s,n)=>We(()=>Uo({client:Q,path:{name:t},headers:xt(s),body:n})),applyPairedAssignments:(t,s,n)=>We(()=>_o({client:Q,path:{name:t},headers:xt(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>We(()=>Fo({client:Q,path:{name:t},headers:xt(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>We(()=>Oo({client:Q,path:{name:t},headers:xt(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>We(()=>qo({client:Q,path:{name:t},headers:xt(s),body:{target:n}})),upsertGroup:(t,s,n)=>We(()=>Eo({client:Q,path:{name:t},headers:xt(s),body:{group:n}})),removeGroup:(t,s,n)=>We(()=>Do({client:Q,path:{name:t},headers:xt(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>We(()=>To({client:Q,path:{name:t},headers:xt(s),body:n})),removeCompetitor:(t,s,n,a)=>We(()=>Mo({client:Q,path:{name:t},headers:xt(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>We(()=>Lo({client:Q,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>We(()=>Io({client:Q,path:{name:t},headers:xt(s),body:n})),compilePreview:t=>We(()=>$o({client:Q,path:{name:t}})),diffPreview:t=>We(()=>Ro({client:Q,path:{name:t}})),publish:(t,s,n)=>We(()=>Ao({client:Q,path:{name:t},headers:xt(s),body:n})),discard:(t,s)=>We(()=>Po({client:Q,path:{name:t},headers:xt(s)}))},Lr={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},Qs={name:"",propertyIds:[],competitorDomains:""},Mr=50;function Ys(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Jm(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 Tr(t){const s=t.propertyPathPattern.trim();if(s){const r=(s.startsWith("/")?s:`/${s}`).split("/").slice(1);if(r.filter(o=>o==="*"||o==="{slug}").length!==1||r.some(o=>o.includes("*")&&o!=="*"))throw new Error("Property URL pattern must contain exactly one * or {slug} segment.");return`/${r.map(o=>o==="*"?"{slug}":o).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 Xm(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const o=r.split("/").filter(Boolean).at(-1)??r,u=o.startsWith("*"),d=o.endsWith("*"),h=o.slice(u?1:0,d?-1:void 0).trim();if(!h)throw new Error("Ignored URL patterns must include text besides *.");const x=u&&d?"contains":u?"suffix":d?"prefix":"exact",c=`${x}:${h}`;n.has(c)||(n.add(c),s.push({kind:x,value:h}))}return s}function Zm(t){const s=Jm(t.sitemapUrl),n=t.examplePropertyUrl.trim()?Ys(t.examplePropertyUrl):null,a=Ys(t.preferredHost)??n??Ys(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=Ys(t.additionalHost),i=t.additionalHost.trim().length>0,o=t.additionalPathPattern.trim().length>0;if(i!==o||i&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const u=Xm(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:Tr(t)},...r?{aliases:[{host:r,pathTemplate:Tr({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...u.length>0?{excludedSlugPatterns:u}:{}}}}function eh(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 th(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 Dr(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function sh(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function ca(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function Pa(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function Er(t){return Ys(t)}function Fi(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 _i(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 Ui(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Gi(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function nh(t,s){const n=Fi(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="urlMatchers"&&typeof r=="number"){const i=n.urlMatchers[r];return i?`${n.label} — ${i}`:n.label}if(a==="aliases"&&typeof r=="number"){const i=n.aliases[r];return i?`${n.label} — ${i}`:n.label}return n.label}function ah(t,s){const n=_i(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="competitors"&&typeof r=="number"){const i=n.competitors.at(r)?.domain;return i?`${n.label} — ${i}`:n.label}if(a==="targetKeys"&&typeof r=="number"){const i=Gi(t.authoring,n.targetKeys[r]);return`${n.label} — ${i}`}return n.label}function rh(t,s){const n=Ui(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable question";return`${Gi(t.authoring,n.targetKey)} — ${a}`}function ih(t,s){return s.path[0]==="identities"?"Project domain":nh(t,s)??ah(t,s)??rh(t,s)}function qr(t,s,n){const a=Ui(t.authoring,s.path);if(!a)return;const r={...t.authoring?.defaultContext,...a.contextOverride},i=s.path.at(-1);if(n==="models"&&typeof i=="string")return r.models?.[i];if(n==="locations"&&typeof i=="number")return r.locations?.[i]}function lh(t,s){const n=ih(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,qr(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 question.",tone:"negative",affected:[n,qr(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 question",detail:"Assign each question to a Property only once.",tone:"negative",affected:n};case"assignment-unknown-target":return{title:"Fix a question assignment",detail:"This question 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 question 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 question",detail:"This assignment refers to a tracked question that is no longer available. Remove it or add the question back to the project.",tone:"negative",affected:n};case"assignment-unclassified":return{title:"Classify a question",detail:"Choose Branded or Non-brand for this question before publishing.",tone:"negative",affected:n};case"query-limit-exceeded":return{title:"Reduce questions",detail:"This setup exceeds the distinct-question publishing limit. Remove some question assignments, then review again.",tone:"negative"};case"target-without-assignments":return{title:"Assign questions",detail:"Assign at least one question 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, questions, 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 Pn(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function Bi(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 oh(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${Pn(n,"question assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${Pn(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${Pn(n,"Property","Properties")} need${n===1?"s":""} questions.`;default:return n>1?`${s} ${Pn(n,"item")} need review.`:s}})()}${Bi(a)}`}function ch(t,s){const n=new Map;for(const a of t){const r=lh(a,s),i=[a.ruleId,a.severity,r.title,r.detail].join("\0"),o=n.get(i)??{ruleId:a.ruleId,severity:a.severity,meaning:r,paths:new Set,affected:new Set};o.paths.add(JSON.stringify(a.path)),r.affected&&o.affected.add(r.affected),n.set(i,o)}return[...n.values()].map((a,r)=>({id:`${a.ruleId}-${a.severity}-${r}`,title:a.meaning.title,detail:oh(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function da(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function ua(t,s,n){const a=Fi(n,t.path),r=_i(n,t.path),i=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,o=i?n?.targets.find(x=>x.stableKey===i):void 0,u=a?.label??r?.label,d=Bi(u?[u]:[]),h={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...h,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${d}`};case"excluded-target-has-assignments":return{...h,title:"Review excluded Property questions",detail:`An excluded Property still has assigned questions. Include it or remove those questions before publishing.${d}`};case"group-unknown-target":return{...h,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${d}`};case"measurement.discovery.proposed_new_target":{const x=da(a)??"the proposed Property";return{...h,title:"Review a new Property",detail:`Review ${x}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const x=da(a)??"the proposed Property",c=o?.label??"an existing Property";return{...h,title:"Review a moved Property",detail:`Review ${x}. It may be the same Property as ${c}.`}}case"measurement.discovery.rebind_ambiguous":{const x=da(a)??"the proposed Property",c=o?.label??"an existing Property";return{...h,title:"Choose an existing Property",detail:`Review ${x}. It may match ${c}; choose the correct Property.`}}default:return{...h,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function dh(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,i=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),i>0&&n.push(`${i} question assignment ${i===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 Ft(t){return[...new Set(t)]}function ss(t){return Ft(t).sort()}function uh(t,s,n){return t.kind==="groups"?{groupKeys:ss(t.groupIds),queryIds:ss(n)}:{targetKeys:ss(t.kind==="all"?s:t.propertyIds),queryIds:ss(n)}}function mh(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 Or(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function hh(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(Or).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(Or).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:Pa(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function xh({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:i,canEdit:o=!0,onCreateQueries:u,onManageProjectQueries:d,onPublished:h,service:x=Ym}){const[c,y]=l.useState(null),[N,f]=l.useState(null),[b,p]=l.useState("import"),[L,E]=l.useState(!0),[q,$]=l.useState(null),[g,v]=l.useState(null),[w,ee]=l.useState([]),[W,A]=l.useState({...Lr}),[j,D]=l.useState("idle"),[S,V]=l.useState(""),[pe,ne]=l.useState(Mr),[X,te]=l.useState([]),[ce,B]=l.useState([]),[G,P]=l.useState({kind:"all"}),[re,le]=l.useState(null),[C,U]=l.useState(null),[se,M]=l.useState(!1),[z,we]=l.useState(null),[Oe,K]=l.useState(0),[ge,Te]=l.useState(null),[je,Be]=l.useState({...Qs}),[et,Me]=l.useState(null),[J,De]=l.useState(""),[xe,Qe]=l.useState(null),[O,_]=l.useState(!1),[fe,Ee]=l.useState(!1),[Ue,Ve]=l.useState(null),[Nt,bt]=l.useState(null),[ke,Fe]=l.useState(null),[qt,tt]=l.useState(null),[dt,Ye]=l.useState(null),wt=l.useRef(0),St=l.useRef(0),Re=N?.draft??null,Ae=N?.etag??null,lt=l.useMemo(()=>!o&&i?{baseActiveRevision:i.revision,authoring:hh(i)}:null,[o,i]),Ge=Re??lt;async function Ot(I){const Y=++wt.current;E(!0),$(null);try{let[he,ie]=await Promise.all([x.loadSetup(t),x.loadDraft(t)]);if(!ie.draft&&I&&o&&(await x.createDraft(t,he.activeRevision),[he,ie]=await Promise.all([x.loadSetup(t),x.loadDraft(t)])),Y!==wt.current)return;y(he),f(ie),p(eh(ie.draft));const H=ca(ie.draft);te(H)}catch(he){if(Y!==wt.current)return;$($t(he,"Could not load advanced measurement setup."))}finally{Y===wt.current&&E(!1)}}l.useEffect(()=>(Ot(!0),()=>{wt.current+=1}),[t,o,x]),l.useEffect(()=>{!L&&!Re&&lt&&p("properties")},[Re,L,lt]);async function Ct(){const I=await x.loadDraft(t);return f(I),I}async function Je(I){Ye(null);try{const[Y,he]=await Promise.all([x.loadSetup(t),x.loadDraft(t)]);y(Y),f(he);const ie=ca(he.draft);te(ie),p(H=>th(he.draft,H)),v(I)}catch(Y){v($t(Y,I))}}async function He(I,Y,he,ie={}){const{preserveBusyAction:H=!1}=ie;if(!o||!Ae||ke&&!H)return null;H||Fe(I),v(null),Ye(null);try{const Se=await Y(Ae),Mt=await Ct();return ee((Se.warnings??[]).map((ot,yt)=>ua(ot,yt,Mt.draft?.authoring))),Mt}catch(Se){return ds(Se)?await Je("This setup changed in another session. The latest draft is loaded; review your changes again."):v($t(Se,he)),null}finally{H||Fe(null)}}const F=l.useMemo(()=>(Ge?.authoring.targets??[]).map(I=>{const Y=Dr(I);return{id:I.stableKey,name:I.label,url:Y[0]??"No URL",urls:Y,state:sh(I.status)}}),[Ge]),Ce=l.useMemo(()=>Ge?.authoring.targets.filter(I=>I.status==="included")??[],[Ge]),de=l.useMemo(()=>Ce.map(I=>({id:I.stableKey,label:I.label,urlCount:Dr(I).length})),[Ce]),ve=Ge?.authoring.assignments.length??0,Ke=l.useMemo(()=>{if(!Ge)return[];const I=new Set(s.map(ie=>ie.id)),Y=s.map(ie=>({id:ie.id,text:ie.query,source:"saved-project-queries",propertyIds:Ft(Ge.authoring.assignments.filter(H=>H.queryId===ie.id).map(H=>H.targetKey))})),he=Ft(Ge.authoring.assignments.map(ie=>ie.queryId).filter(ie=>!I.has(ie))).map(ie=>({id:ie,source:"unavailable-tracked-query",state:"missing",propertyIds:Ft(Ge.authoring.assignments.filter(H=>H.queryId===ie).map(H=>H.targetKey))}));return[...Y,...he]},[s,Ge]),Wt=l.useMemo(()=>(Ge?.authoring.groups??[]).map(I=>({id:I.stableKey,name:I.label,propertyIds:I.targetKeys,competitors:I.competitors.map(Y=>Y.domain)})),[Ge]),st=l.useMemo(()=>{if(ce.length===0)return null;const I=uh(G,de.map(he=>he.id),ce);return(I.groupKeys?.length??I.targetKeys?.length??0)>0?I:null},[G,de,ce]),kt=st?JSON.stringify(st):"";l.useEffect(()=>{const I=st,Y=++St.current;if(!o||!Re||!Ae||!I){le(null),U(null),we(null),M(!1);return}le(null),U(null),we(null),M(!0);const he=window.setTimeout(()=>{x.previewAssignments(t,I).then(ie=>{if(Y===St.current){if(ie.draftEtag!==Ae){le(null),U(null),we("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}le(ie),U(kt)}}).catch(ie=>{Y===St.current&&(le(null),U(null),we(Wm(ie)))}).finally(()=>{Y===St.current&&M(!1)})},250);return()=>{window.clearTimeout(he),St.current+=1}},[st,kt,Oe,o,Re,Ae,t,x]);const rs=l.useMemo(()=>[...ve===0?[{id:"no-query-assignments",title:"Assign at least one question",detail:"Apply a tracked question to at least one Property before publishing.",tone:"negative"}]:[],...Ge?.authoring.assignments.some(I=>I.queryClass==="unclassified")&&!(lt&&i?.plan.schemaVersion===1)?[{id:"unclassified-query-assignments",title:"Remove an unavailable question",detail:"One or more saved assignments no longer have a tracked question. Clear them before publishing.",tone:"negative"}]:[],...w],[ve,lt,i,w,Ge]),R=n?{status:"unavailable",message:"Tracked questions are loading."}:a?{status:"unavailable",message:"Tracked questions could not be loaded. Retry before assigning Properties."}:{status:"available"};async function be(I){let Y;try{Y=Zm(I)}catch(ie){v($t(ie,"Check the sitemap details and try again."));return}A(I),D("reviewing");const he=await He("import",ie=>x.importSitemap(t,ie,Y),"Could not review this sitemap.");if(he?.draft){const ie=he.draft.authoring.targets.filter(Se=>Se.status==="proposed").map(Se=>Se.stableKey),H=he.draft.authoring.targets.filter(Se=>Se.status==="included").map(Se=>Se.stableKey);te([...H,...ie]),V(""),ne(Mr),p("properties"),D("idle")}else D("error")}async function ye(I){if(!u||I.length===0||ke)return[];Fe("create-queries"),tt(null);try{return await u(I)}catch(Y){throw tt(ir(Y)),Y}finally{Fe(null)}}async function Pt(I){if(!Re||!Ae||ke)return;const Y=new Set(I),ie=Re.authoring.targets.filter(Se=>Se.status==="proposed"&&Se.discoveryIdentity).map(Se=>({discoveryIdentity:Se.discoveryIdentity,action:Y.has(Se.stableKey)?"create":"ignore"})),H=ie.length>0||Re.authoring.targets.some(Se=>Se.status!=="proposed"&&Se.status==="included"!==Y.has(Se.stableKey));Fe("properties"),v(null),Ye(null);try{if(!H){te([...Y]),P({kind:"all"}),p("groups");return}await x.applySitemapSelection(t,Ae,ie,[...Y]);const Se=await Ct(),Mt=ca(Se.draft);te(Mt),P({kind:"all"}),p("groups")}catch(Se){ds(Se)?await Je("This setup changed in another session. The latest Properties are loaded."):v($t(Se,"Could not save the selected Properties."))}finally{Fe(null)}}async function nt(I){const Y=I.groupIds&&I.groupIds.length>0?{groupKeys:ss(I.groupIds),queryIds:ss(I.queryIds)}:{targetKeys:ss(I.propertyIds),queryIds:ss(I.queryIds)};if(!re||C!==JSON.stringify(Y)||!Ae||re.draftEtag!==Ae){v("Review the latest assignment impact before assigning questions.");return}await He("assignments",ie=>x.applyAssignments(t,ie,Y),"Could not apply these questions.")&&(B([]),Te(`${re.assignments.added} new assignment${re.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function At(I){if(I.propertyIds.length===0)return;await He("replace-assignments",he=>x.replaceAssignments(t,he,{targetKeys:Ft(I.propertyIds),queryIds:[I.queryId]}),"Could not replace this question assignment.")&&(B(he=>he.filter(ie=>ie!==I.queryId)),Te("Question assignments replaced."))}async function dn(I,Y=!1){if(I.length===0)return;if(!await He("paired-assignments",ie=>x.applyPairedAssignments(t,ie,[...I]),"Could not assign these questions.",{preserveBusyAction:Y}))throw new Error("Could not assign these questions.")}async function jt(I){if(!(!o||!u||I.length===0||ke)){Fe("create-and-pair-questions"),tt(null);try{let Y;try{Y=await u(Ft(I.map(H=>H.text)))}catch(H){throw tt(ir(H)),H}const he=new Map(Y.map(H=>[H.query,H.id])),ie=I.map(H=>({targetKey:H.propertyId,queryId:he.get(H.text)})).filter(H=>H.queryId!==void 0);if(ie.length!==I.length){const H=new Error("The created questions could not be matched to their Properties.");throw tt("The questions were added, but could not be paired with every Property. Try again to pair them."),H}try{await dn(ie,!0)}catch(H){throw tt("The questions were added, but could not be assigned to their Properties. Try again to pair them."),H}}finally{Fe(null)}}}async function is(I){if(!Re)return;const Y=Ft(Re.authoring.assignments.filter(ie=>ie.queryId===I).map(ie=>ie.targetKey));if(Y.length===0)return;await He(`remove-${I}`,ie=>x.removeAssignment(t,ie,Y,I),"Could not clear this question assignment.")&&B(ie=>ie.filter(H=>H!==I))}async function En(I){if(!Re||!Ae||ke)return;const Y=I.name.trim();if(!Y)return;const he=et??Pa(Y,"group"),ie=Re.authoring.groups.find(ot=>ot.stableKey===he);if(ie&&et===null){v(`A group named "${ie.label}" already exists. Edit it or choose a different name.`);return}const H=I.competitorDomains.split(/[\s,]+/).map(ot=>ot.trim()).filter(Boolean),Se=H.find(ot=>Er(ot)===null);if(Se){v(`"${Se}" is not a valid competitor domain.`);return}const Mt=Ft(H.map(ot=>Er(ot)));Fe("group"),v(null),Ye(null);try{const ot=await x.upsertGroup(t,Ae,{stableKey:he,label:Y,targetKeys:Ft(I.propertyIds),competitors:Mt.map(Yt=>ie?.competitors.find(at=>at.domain===Yt)??{stableKey:Pa(Yt,"competitor"),label:Yt,domain:Yt,aliases:[]})}),yt=await Ct();ee(ot.warnings.map((Yt,at)=>ua(Yt,at,yt.draft?.authoring))),Be({...Qs}),Me(null)}catch(ot){ds(ot)?await Je("This setup changed in another session. The latest groups are loaded."):v($t(ot,"Could not save this group."))}finally{Fe(null)}}function un(I){const Y=Re?.authoring.groups.find(he=>he.stableKey===I);Y&&(Me(I),Be({name:Y.label,propertyIds:[...Y.targetKeys],competitorDomains:Y.competitors.map(he=>he.domain).join(", ")}))}async function ls(I){await He("remove-group",he=>x.removeGroup(t,he,I),"Could not remove this group.")&&(P(he=>he.kind==="groups"&&he.groupIds.includes(I)?{kind:"all"}:he),et===I&&(Me(null),Be({...Qs})))}function js(I){De(I),Qe(null),Ve(null),bt(null)}async function Us(){if(!(!o||!J.trim()||O||fe)){_(!0),Ve(null),bt(null);try{Qe(await x.previewGroupMembership(t,{csv:J}))}catch(I){Qe(null),Ve($t(I,"Could not review this CSV."))}finally{_(!1)}}}async function qn(I){if(!(!o||!Ae||!xe||I.length===0||ke)){if(xe.draftEtag!==Ae){Ve("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}Ee(!0),Fe("group-import"),Ve(null),bt(null),Ye(null);try{const Y=await x.applyGroupMembership(t,Ae,{csv:J,sourceChecksum:xe.sourceChecksum,previewChecksum:xe.previewChecksum,acceptedRows:Ft(I.map(String)).map(Number)}),he=await Ct();ee(Y.warnings.map((ie,H)=>ua(ie,H,he.draft?.authoring))),De(""),Qe(null),bt(`${Y.addedMemberships} membership${Y.addedMemberships===1?"":"s"} added${Y.unchangedMemberships>0?`; ${Y.unchangedMemberships} already present`:""}.`)}catch(Y){ds(Y)?(await Je("This setup changed in another session. The latest draft is loaded; review the CSV again."),Ve("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Ve($t(Y,"Could not apply this CSV."))}finally{Fe(null),Ee(!1)}}}async function mn(){if(!(!Re||!Ae||ke||ve===0)){Fe("review"),v(null),Ye(null);try{const[I,Y]=await Promise.all([x.compilePreview(t),x.diffPreview(t)]),he=[...I.checks,...Y.checks],ie=he.some(H=>H.ruleId==="active-revision-schema-v1");if(ee(ch(he.filter(H=>H.ruleId!=="active-revision-schema-v1"),{authoring:Ge?.authoring,queries:s})),!I.ok||!Y.ok)return;if(Y.diff.activeRevision!==Re.baseActiveRevision){await Je("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(I.compiledChecksum!==Y.compiledChecksum){v("The setup changed while it was being reviewed. Review the latest changes again.");return}Ye({etag:Ae,baseActiveRevision:Re.baseActiveRevision,compiledChecksum:I.compiledChecksum,changes:dh(Y.diff,ie),providerCalls:I.plan.executionNodes.reduce((H,Se)=>H+Se.expectedSnapshots,0)})}catch(I){v($t(I,"Could not review this setup."))}finally{Fe(null)}}}async function ut(){if(!(!Re||!Ae||!dt||ke)){if(Ae!==dt.etag||Re.baseActiveRevision!==dt.baseActiveRevision){Ye(null),v("The setup changed after review. Review the latest changes before publishing.");return}Fe("publish"),v(null);try{await x.publish(t,Ae,{expectedActiveRevision:dt.baseActiveRevision,expectedCompiledChecksum:dt.compiledChecksum}),f({draft:null,etag:null}),Ye(null),h?.()}catch(I){ds(I)?await Je("The setup changed before it could be published. Review the latest draft and publish again."):v($t(I,"Could not publish this setup."))}finally{Fe(null)}}}async function ys(){if(!(!Ae||ke)){Fe("discard"),v(null);try{await x.discard(t,Ae),f({draft:null,etag:null}),Ye(null),h?.()}catch(I){ds(I)?await Je("This setup changed in another session. The latest draft is loaded."):v($t(I,"Could not discard these changes."))}finally{Fe(null)}}}async function On(){if(!(!Re||!Ae||!c||ke)){Fe("restart"),v(null),Ye(null);try{await x.discard(t,Ae),await x.createDraft(t,c.activeRevision),A({...Lr}),V(""),te([]),B([]),P({kind:"all"}),le(null),we(null),Te(null),Be({...Qs}),Me(null),De(""),Qe(null),Ve(null),bt(null),await Ot(!1)}catch(I){ds(I)?await Je("The setup changed again. Reloaded the latest draft and published setup."):v($t(I,"Could not restart this setup."))}finally{Fe(null)}}}if(L)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-loading-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-loading-title",children:"Advanced measurement setup"})}),e.jsx("div",{className:"h-28 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement setup"})]});if(q)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-error-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-error-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:q}),e.jsx(k,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Ot(!0)},children:"Try again"})]})]});if(!Ge||o&&!Ae)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:o?"Start setup from the project Overview.":"No advanced setup is available to review."})]});if(o&&Re&&c&&Re.baseActiveRevision!==c.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(k,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:ke==="restart",onClick:()=>{On()},children:ke==="restart"?"Restarting…":"Discard draft and restart"})]}),g?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:g}):null]});const Fn=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(k,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:r,children:"Retry questions"})}):null;return e.jsxs("div",{className:"space-y-4",children:[c?.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,g?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:g}):null,Fn,b==="import"||b==="properties"?e.jsx(kn,{currentStep:b,hasDraft:Re!==null,canEdit:o,onStepChange:o?void 0:p,onDiscard:()=>{ys()},importProperties:{importDraft:W,onImportDraftChange:I=>{A(I),D("idle"),v(null)},onReviewSitemap:I=>{be(I)},reviewState:j,properties:F,propertiesState:"ready",propertiesSearch:S,onPropertiesSearchChange:V,maxVisibleProperties:pe,onShowAllProperties:()=>ne(F.length),selectedPropertyIds:X,onSelectedPropertyIdsChange:I=>te([...I]),onContinue:I=>{Pt(I)},isContinuing:ke==="properties",onRetryProperties:()=>{Ct()},onReturnToImport:()=>p("import")}}):b==="queries"?e.jsx(kn,{currentStep:"queries",hasDraft:Re!==null,canEdit:o,onStepChange:o?void 0:p,onDiscard:()=>{ys()},onManageProjectQueries:d,queries:{onCreateQueries:u?I=>ye(I):void 0,isCreatingQueries:ke==="create-queries"||ke==="create-and-pair-questions",isBusy:ke!==null,createQueriesError:qt,availability:R,properties:de,queries:Ke,selectedQueryIds:ce,isApplying:ke==="assignments"||ke==="paired-assignments",onSelectedQueryIdsChange:I=>B([...I]),onApplySelectedQueries:I=>nt(I),groups:Wt,audience:G,onAudienceChange:I=>{P(I),Te(null)},assignmentImpact:re&&C===kt?mh(re):null,isPreviewingAssignmentImpact:se,assignmentImpactError:z,onRetryAssignmentImpact:()=>K(I=>I+1),assignmentNotice:ge,onReplaceAssignments:At,isReplacingAssignments:ke==="replace-assignments",onCreateAndPairQuestions:o&&u?jt:void 0,onClearQueryAssignments:is,onRemoveQuery:is,canContinue:ve>0,onBack:()=>p("groups"),onContinue:()=>p("review")}}):b==="groups"?e.jsx(kn,{currentStep:"groups",hasDraft:Re!==null,canEdit:o,onStepChange:o?void 0:p,onDiscard:()=>{ys()},groups:{properties:de,groups:Wt,groupDraft:je,isSaving:ke==="group",onGroupDraftChange:Be,onSaveGroup:En,onEditGroup:I=>un(I.id),onRemoveGroup:ls,onClearGroupDraft:()=>{Me(null),Be({...Qs})},membershipImport:{csv:J,preview:xe,isReviewing:O,isApplying:fe,error:Ue,notice:Nt,onCsvChange:js,onReview:Us,onApply:qn},onBack:()=>{p("properties")},onContinue:()=>p("queries")}}):e.jsx(kn,{currentStep:"review",hasDraft:Re!==null,canEdit:o,onStepChange:o?void 0:p,onDiscard:()=>{ys()},review:{counts:{properties:Ce.length,queries:new Set(Ge.authoring.assignments.map(I=>I.queryId)).size,groups:Ge.authoring.groups.length,assignments:Ge.authoring.assignments.length,providerCalls:dt?.providerCalls},flaggedExceptions:rs,reviewedChanges:dt?.changes,isReviewing:ke==="review",canReviewChanges:ve>0&&!ke,onReviewChanges:mn,onBack:()=>p("queries"),canPublish:dt!==null&&!ke,isPublishing:ke==="publish",onPublish:ut}})]})}const us="__all_properties__",ph=50,zi=50,gh=20,fh=50,bh=250,jh={"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"},Vi={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."},yh={numerator:null,denominator:null,reason:"plan_v1"};function Zs(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 vh(t){return Zs(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function Ki(t){if(Zs(t))return"";const s=t.reason??"unavailable";return Vi[s]??s}function Nh(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function wh(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function Sh(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function Cs({metric:t,compact:s=!1}){const n=s?Zs(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Zs(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",...Zs(t)?{}:{title:Ki(t)},children:e.jsx("span",{className:n,children:vh(t)})})}function Ua({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(k,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Fr({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,i]=l.useState(zi),o=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:o.map((u,d)=>e.jsx("li",{className:a,children:u},`${u}:${d}`))}),e.jsx(Ua,{shown:o.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>i(Number.MAX_SAFE_INTEGER)})]})]})}function Ch({evidence:t,state:s="ready",onRetry:n}){const[a,r]=l.useState(zi),i=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(k,{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:i.map(o=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(oe,{tone:o.tone,children:jh[o.kind]}),o.historical?e.jsx(oe,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:o.query}),o.provider||o.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[o.provider,o.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:o.url})]},o.id))})]})}),e.jsx(Ua,{shown:i.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function kh({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Fr,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Fr,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(Ch,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function Ph({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(Cs,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function Ah({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:i=!1,isViewLoading:o=!1,isLoadingMore:u=!1,isLoadMoreError:d=!1,viewSearch:h,onViewChange:x,onLoadMore:c,onPropertyExpand:y,onRetryEvidence:N,renderPropertyLink:f}){const b=t.currentView!=null,p=t.classReporting==="available"&&(b||t.classScopes!=null),[L,E]=l.useState(t.currentView?.queryClass??"non-brand"),[q,$]=l.useState(t.currentView?.scope.key??us),[g,v]=l.useState(h??""),[w,ee]=l.useState(ph),[W,A]=l.useState(gh),[j,D]=l.useState(new Set),S=l.useRef(h??""),V=p&&!b&&L!=="all"?L==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,pe=b?{aggregate:t.currentView.aggregate,groups:[]}:V,ne=l.useCallback(K=>{if(!b||!x)return;const ge=K.scope??(q===us?"all":"group"),Te=K.search??g;S.current=Te,x({scope:ge,...ge==="group"?{groupKey:K.groupKey??q}:{},queryClass:K.queryClass??L,...Te?{search:Te}:{}})},[x,g,L,q,b]);l.useEffect(()=>{!t.currentView||o||(E(t.currentView.queryClass),$(t.currentView.scope.key??us))},[o,t.currentView]),l.useEffect(()=>{h!==void 0&&(S.current=h,v(h))},[h]),l.useEffect(()=>{if(!b||!x||g===S.current)return;const K=window.setTimeout(()=>ne({search:g}),bh);return()=>window.clearTimeout(K)},[x,ne,g,b]),l.useEffect(()=>{const K=t.availableGroups??pe.groups;q===us||K.some(ge=>ge.id===q)||$(us)},[t.availableGroups,pe,q]);const X=b?void 0:pe.groups.find(K=>K.id===q),te=X?.aggregate??pe.aggregate,ce=K=>p?K:yh,B=g.trim().toLocaleLowerCase(),G=l.useMemo(()=>!b&&B?te.properties.filter(K=>K.name.toLocaleLowerCase().includes(B)):te.properties,[te.properties,B,b]),P=b?G:G.slice(0,w),re=(b?t.currentView?.scope.kind==="group":X!=null)&&L==="non-brand"&&p&&(b||X.confirmedCompetitorCount>0)&&(te.shareOfVoice?.length??0)>0,le=p?te.unavailablePropertyCount??0:0,C=t.flaggedResults.reduce((K,ge)=>K+(ge.count??1),0),U=t.flaggedResultsTotal??C,se=[ce(te.metrics.propertiesMentioned),ce(te.metrics.mentionCoverage),ce(te.metrics.citationCoverage)].map(Ki).find(Boolean),M=p?t.nextActionText??se??(le>0?`${le} ${le===1?"property is":"properties are"} unavailable.`:U>0?`${U} flagged ${U===1?"result needs":"results need"} review.`:"No action needed."):Vi.plan_v1,z=Nh(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots),we=wh(t.latestMeasurement.date);function Oe(K){const ge=!j.has(K);D(Te=>{const je=new Set(Te);return je.has(K)?je.delete(K):je.add(K),je}),ge&&y?.(K)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":o,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:o?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(oe,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(oe,{tone:"caution",children:"Includes historical data"}):null,z?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:z}):null,we?e.jsx("span",{className:"text-sm text-secondary",children:we}):null,e.jsx("span",{className:"text-sm text-secondary",children:M}),s&&p&&n?e.jsx(k,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!p?e.jsx(k,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||i,children:i?"Opening setup…":"Republish setup"}):null]})})}),o?e.jsx("div",{className:"h-20 animate-pulse rounded-md bg-surface-subtle","aria-label":"Updating measurement results"}):e.jsxs("dl",{className:"grid gap-4 border-y border-default py-4 md:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm text-secondary",children:"Properties mentioned"}),e.jsx("dd",{className:"mt-1",children:e.jsx(Cs,{metric:ce(te.metrics.propertiesMentioned)})})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm text-secondary",children:"Mention coverage"}),e.jsx("dd",{className:"mt-1",children:e.jsx(Cs,{metric:ce(te.metrics.mentionCoverage)})})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm text-secondary",children:"Citation coverage"}),e.jsx("dd",{className:"mt-1",children:e.jsx(Cs,{metric:ce(te.metrics.citationCoverage)})})]})]}),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",{htmlFor:"advanced-measurement-group",className:"block text-sm font-medium text-heading",children:"Group"}),e.jsxs("select",{id:"advanced-measurement-group",value:q,onChange:K=>{const ge=K.target.value;$(ge),ne(ge===us?{scope:"all"}:{scope:"group",groupKey:ge})},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:[e.jsx("option",{value:us,children:"All properties"}),(t.availableGroups??pe.groups).map(K=>e.jsx("option",{value:K.id,children:K.label},K.id))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-class",className:"block text-sm font-medium text-heading",children:"Question type"}),e.jsxs("select",{id:"advanced-measurement-class",disabled:!p,value:L,onChange:K=>{const ge=K.target.value;E(ge),ne({queryClass:ge})},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:[e.jsx("option",{value:"all",children:"All questions"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"branded",children:"Branded"})]})]}),e.jsxs("div",{className:"min-w-52 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:g,onChange:K=>v(K.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"})]})]}),!o&&re?e.jsx(Ph,{values:te.shareOfVoice??[]}):null,o?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.jsx("h2",{id:"advanced-measurement-properties-title",className:"text-base font-semibold text-heading",children:"Properties"}),e.jsxs("span",{className:"text-sm text-secondary",children:[t.currentView?.propertyTotal??G.length," ",(t.currentView?.propertyTotal??G.length)===1?"property":"properties"]})]}),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:[e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Mention"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[P.map(K=>{const ge=j.has(K.id);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:Te=>{Sh(Te.target)||Oe(K.id)},children:[e.jsx("td",{className:"font-medium text-heading",children:f?f({id:K.id,name:K.name}):K.name}),e.jsx("td",{className:"text-secondary",children:e.jsx(Cs,{metric:K.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Cs,{metric:K.citationCoverage,compact:!0})}),e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(oe,{tone:K.status.tone,children:K.status.label}),K.historical?e.jsx(oe,{tone:"caution",children:"Historical"}):null]})}),e.jsx("td",{className:"text-right",children:e.jsx(k,{size:"sm",variant:"ghost","aria-expanded":ge,onClick:()=>Oe(K.id),children:ge?`Hide details for ${K.name}`:`Show details for ${K.name}`})})]},K.id),ge?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"bg-surface-subtle px-4",children:e.jsx(kh,{property:K,onRetryEvidence:N})})},`${K.id}:details`):null]},K.id)}),P.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"py-8 text-center text-sm text-secondary",children:"No properties match this search."})}):null]})]})}),b&&t.currentView.nextCursor&&c?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",P.length," of ",t.currentView.propertyTotal]}),d?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(k,{size:"sm",variant:"outline",disabled:u,onClick:()=>c(t.currentView.nextCursor),children:u?"Loading…":d?"Retry loading more properties":"Show 50 more"})]}):b?P.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",P.length," of ",t.currentView.propertyTotal]}):null:e.jsx(Ua,{shown:P.length,total:G.length,itemLabel:"properties",onShowAll:()=>ee(Number.MAX_SAFE_INTEGER)})]}),!o&&!B&&U>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 (",U,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,W).map(K=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(oe,{tone:K.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:K.property}),e.jsx("span",{className:"text-secondary",children:K.summary})]},K.id))}),W<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,W).reduce((K,ge)=>K+(ge.count??1),0)," of ",U," flagged results"]}),e.jsx(k,{size:"sm",variant:"outline",onClick:()=>A(K=>Math.min(t.flaggedResults.length,K+fh)),children:"Show 50 more"})]}):C<U?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",C," of ",U," flagged results"]}),b&&t.currentView.nextCursor&&c?e.jsx(k,{size:"sm",variant:"outline",disabled:u,onClick:()=>c(t.currentView.nextCursor),children:u?"Loading…":d?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function _r(t){return t.setupAction==="continue"?"Continue advanced setup":t.setupAction==="edit"?"Edit setup":t.setupAction==="republish"?"Republish setup":"Set up advanced measurement"}function Ur(t){return t.setupAction==="continue"?"Setup is unfinished. Pick up where you left off.":t.setupAction==="edit"?"Change which Properties and questions are measured.":t.setupAction==="republish"?"Unpublished changes are waiting to go live.":"Measure each Property on its own questions, not just the project as a whole."}function Rh({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:i,onRunMeasurement:o,onRetryReport:u,onViewChange:d,onLoadMore:h,onPropertyExpand:x,onRetryEvidence:c,renderPropertyLink:y,isRunningMeasurement:N,isOpeningSetup:f,isViewLoading:b,isLoadingMore:p,isLoadMoreError:L,viewSearch:E}){return t.surface==="simple-overview"?e.jsxs(e.Fragment,{children:[s&&i?e.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-3",children:[e.jsx(k,{type:"button",variant:"outline",disabled:f,onClick:i,children:f?"Opening setup…":_r(t)}),e.jsx("p",{className:"supporting-copy m-0",children:Ur(t)})]}):null,n]}):e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&i?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(k,{type:"button",size:"sm",disabled:f,onClick:i,children:f?"Opening setup…":_r(t)}),e.jsx("p",{className:"supporting-copy m-0",children:Ur(t)})]}):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(k,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:u,children:"Retry report"}):null]}):a?e.jsx(Ah,{report:a,canEdit:s,onRunMeasurement:o,onRepublishSetup:i,onViewChange:d,onLoadMore:h,onPropertyExpand:x,onRetryEvidence:c,renderPropertyLink:y,isRunningMeasurement:N,isRepublishingSetup:f,isViewLoading:b,isLoadingMore:p,isLoadMoreError:L,viewSearch:E}):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."})]})}function $h(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:"edit"}}const Ss={numerator:null,denominator:null,reason:"plan_v1"};function Ih(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Gr(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function Lh(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function Mh(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Th(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 Dh(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function Eh(t){const s=new Map;for(const n of t){const a=Dh(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function qh(t,s){if(t.plan.schemaVersion!==1)throw new Error("Version-one report adapter received a different setup version.");const n=t.plan,a=new Map(n.targets.map(f=>[f.stableKey,f])),r=new Map(n.querySnapshots.map(f=>[f.queryId,f.queryText])),i=new Map;for(const f of n.targetQuerySelections){const b=i.get(f.targetKey)??[];b.push(...f.queryIds.map(p=>r.get(p)).filter(p=>!!p)),i.set(f.targetKey,[...new Set(b)])}const o=Eh(s.evidence),u=n.executionNodes.reduce((f,b)=>f+b.expectedSnapshots,0),d=s.run?.status==="completed"&&u>0,h=d?u:0,x=d?u:0,c=s.targets.map(f=>{const b=a.get(f.id),p=o.get(f.id)??[],L=p.map($=>({id:`${$.observationId}:${$.usageEdgeId}:${$.sourceUrl}`,kind:Lh($.classification),query:$.queryText,url:$.sourceUrl,tone:Mh($.classification),historical:$.historical||$.bridged})),E=p.some($=>$.historical||$.bridged),q=s.run?f.completeness.complete?b?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${f.completeness.executed} of ${f.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:f.id,name:f.label,mentionCoverage:Gr(f.mentionCoverage),citationCoverage:Gr(f.citationCoverage),status:q,assignedQueries:i.get(f.id)??[],urls:b?.urls.map(Ih)??[],evidence:L,historical:E}}),y=new Map(c.map(f=>[f.id,f])),N=new Map(n.groups.map(f=>[f.stableKey,f]));return{classReporting:"plan-v1",latestMeasurement:{status:s.run?.status==="completed"?{label:"Complete",tone:"positive"}:s.run?.status==="partial"?{label:"Partial result",tone:"caution"}:{label:"Not measured",tone:"neutral"},completedSlots:h,totalSlots:x,date:Th(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Ss,mentionCoverage:Ss,citationCoverage:Ss},properties:c},groups:s.groups.map(f=>({id:f.id,label:f.label,confirmedCompetitorCount:N.get(f.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Ss,mentionCoverage:Ss,citationCoverage:Ss},properties:f.targetIds.map(b=>y.get(b)).filter(b=>!!b)}}))},flaggedResults:[]}}const Oh={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function rt(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 Fh(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 _h(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function Uh({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[i,o]=l.useState(Wo),u=Le({...Yo({client:Q,path:{name:t},query:{period:i}}),placeholderData:Wr});async function d(){n(!0),r(null);try{await Xo(t,"client",i)}catch(x){const c=x instanceof Ls||x instanceof Error?x.message:"Download failed";r(c)}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 x=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:x})})}const h=u.data;return h?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:h.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[h.meta.project.canonicalDomain," · ",h.meta.project.country," / ",h.meta.project.language.toUpperCase(),h.meta.location?` · Location: ${_h(h.meta.location)}`:" · No location set"," · ","Last ",h.meta.periodDays," days"," · ","Generated ",Fh(h.meta.generatedAt)]}),a&&e.jsx("p",{className:"mt-2 text-xs text-negative-400",children:a})]}),e.jsxs("div",{className:"page-header-right flex flex-col items-end gap-2",children:[e.jsx(Gh,{period:i,onChange:o}),e.jsxs(k,{variant:"secondary",size:"sm",onClick:Ie(d),disabled:s,children:[e.jsx(hi,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(Wh,{report:h}),e.jsx(tx,{report:h,audience:"client"}),e.jsx(Vh,{report:h}),e.jsx(Xh,{report:h,audience:"client",projectName:t}),e.jsx(Zh,{report:h})]}):null}function Gh({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:Jo.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 Br="AI Visibility — Server-Side",zr="AI engine attention",Bh=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,zh="Live telemetry from your server logs.";function Vh({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(rn,{eyebrow:zr,title:Br,subtitle:zh}),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:fd(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,r=`vs prior ${a} days`,i=Hn(n,"requests",r),o=`${rt(s.verifiedCrawlerHits.current)} verified · ${rt(s.unverifiedCrawlerHits.current)} unverified${i?` · ${i}`:""}`,u=Hn(s.aiUserFetchHits,"requests",r),h=[Hn(s.referralArrivals,"sessions",r),s.referralArrivalsClassSummary].filter(Boolean).join(" · "),x=s.byOperator.filter(c=>c.verifiedHits>0||c.unverifiedHits>0||c.userFetchHits>0||c.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(rn,{eyebrow:zr,title:Br,subtitle:Bh(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(xa,{label:"AI bot requests observed",value:rt(n.current),subtitle:o}),e.jsx(xa,{label:"AI user-fetch requests",value:rt(s.aiUserFetchHits.current),subtitle:u||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(xa,{label:"AI referral sessions",value:rt(s.referralArrivals.current),subtitle:h})]}),x.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:x.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:c.operator}),e.jsx("td",{children:rt(c.verifiedHits+c.unverifiedHits)}),e.jsx("td",{children:rt(c.userFetchHits)}),e.jsx("td",{children:rt(c.referralArrivals)})]},c.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 Kh(t,s){return t.audience==="both"||t.audience===s}const Qh={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Dn(t){return Qh[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Hh(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 Wh({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,r=a>0?`${s.mentionRate}%`:"—",i=a>0?`When customers asked AI ${a} ${a===1?"question":"questions"} 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 questions about your business.",o=Hh(t.whatsChanged.mentionRate),u=n.providers.length>0?n.providers.map(Dn).join(", "):`${rt(s.queryCount)} ${s.queryCount===1?"question":"questions"} 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:i}),o&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${o.tone==="positive"?"text-positive-400":o.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:o.arrow}),o.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(ma,{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(ma,{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(ma,{label:"AI tools tested",value:rt(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 questions we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["These are the ",n.queries.length," ",n.queries.length===1?"question we asked":"questions we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((d,h)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-bg/40 px-3 py-2 text-sm text-strong",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-muted",children:String(h+1).padStart(2,"0")}),e.jsxs("span",{children:['"',d,'"']})]},h))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"How often each AI tool mentions you"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Higher is better. Each bar shows the share of customer questions where the AI named you in the answer."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(d=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:Dn(d.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-positive-500/70",style:{width:`${Math.max(d.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[d.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",d.mentionedCount,"/",d.totalCount,")"]})]})]},d.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((d,h)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:d},h))})]})}function ma({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 Yh(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function Jh(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function Xh({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(c=>Kh(c,s)),r=Nd(t,a),i=s==="client",o=Zo(),[u,d]=l.useState(new Set),h=u.size>0?r.filter(c=>!c.targetRef||!u.has(c.targetRef)):r,x=c=>{if(!c.targetRef)return;const y=c.targetRef;d(N=>new Set(N).add(y)),o.mutate({projectName:n,body:{targetRef:y}},{onSuccess:()=>{Ne({tone:"positive",title:`Dismissed "${c.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:N=>{Ne({tone:"negative",title:`Couldn't dismiss "${c.title}"`,detail:String(N)}),d(f=>{const b=new Set(f);return b.delete(y),b})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(rn,{eyebrow:i?"Action plan":"Agency actions",title:i?"What to do next":"Agency Action Plan",subtitle:i?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),h.length===0?e.jsx(za,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:h.map((c,y)=>{const N=c.evidence.length>0?c.evidence:c.why,f=c.why.length>0||c.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-default bg-surface p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-mono-800/80 text-sm font-semibold text-heading",title:"Priority — 1 will move the needle fastest",children:y+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(oe,{tone:tc(c),children:i?Yh(c.horizon):ec(c.horizon)}),!i&&e.jsx(oe,{tone:"neutral",children:sc(c.category)}),e.jsx(oe,{tone:"neutral",children:i?Jh(c.confidence):`${nc(c.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:c.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:c.action}),e.jsx(sx,{items:N,limit:3,className:"mt-3"}),f&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:i?"See the data behind this":"Evidence details"}),c.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:i?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:c.why.map((b,p)=>e.jsx("li",{children:b},p))})]}),c.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:i?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:c.evidence.map((b,p)=>e.jsx("li",{children:b},p))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:i?"What success looks like:":"Win condition:"})," ",c.successMetric]}),c.targetRef&&!Z()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>x(c),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"})})]},`${c.priority}-${c.title}`)})})]})}function Vr({label:t,value:s,displayValue:n,max:a,barClass:r}){const i=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:`${i}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function Zh({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=wd(t).slice(0,5),i=s.length>0?Math.max(...s.map(d=>d.count)):0,o=n?Math.max(...n.topQueries.slice(0,5).map(d=>d.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(rn,{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 questions about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(d=>e.jsx(Vr,{label:d.domain+(d.isCompetitor?" (competitor)":""),value:d.count,displayValue:`${rt(d.count)}×`,max:i,barClass:"bg-mono-400/70"},d.domain))})]}),a&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${a.indexedPct>=90?"text-positive-400":a.indexedPct>=70?"text-caution-400":"text-negative-400"}`,children:[a.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[rt(a.indexed)," of ",rt(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:rt(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:rt(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:rt(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(d=>e.jsx(Vr,{label:d.query,value:d.impressions,displayValue:`${rt(d.impressions)} ${d.impressions===1?"search":"searches"}`,max:o,barClass:"bg-info-500/70"},d.query))})]}),r.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Customer questions where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:r.map((d,h)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:d.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[ac(d.action),d.winnabilityClass==="ceded"&&e.jsx(oe,{tone:"caution",children:"Ceded surface"})]})]},h))})]})]}):e.jsx(za,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function Ga(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function Ba(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=Ga(s.direction),i=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",o=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:bd(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 ${i}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:Ba(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:o})]})}function Kr({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=Ga(s.direction),i=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",o=jd(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 ${i}`,children:[rt(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:Ba(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:o})]})}function ex({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 i=r.deltaAbs>0?"+":"",o=Ga(r.direction),u=o==="positive"?"text-positive-400":o==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?Dn(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:u,children:[i,r.deltaAbs.toFixed(1),"% ",Ba(r.direction)]})]},r.provider)})})]})})]})}function Qr({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 question":"Query"}),e.jsx("th",{children:r?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(i=>e.jsxs("tr",{children:[!r&&e.jsxs("td",{children:[e.jsx(oe,{tone:Oh[i.severity],children:rc(i.severity)}),i.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",i.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[i.title,r&&i.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",i.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:i.query}),e.jsx("td",{className:"text-xs text-secondary",children:r?Dn(i.provider):i.provider})]},i.id))})]})})]})}function tx({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,i=e.jsx(rn,{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:[i,e.jsx(za,{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:[i,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?"Questions AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(Kr,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(Kr,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(ex,{movements:n.providerMovements,audience:s}),e.jsx(Qr,{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(Qr,{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 xa({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 rn({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 sx({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((i,o)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:i},o)),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 za({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function nx({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[i,o]=l.useState(!1),[u,d]=l.useState(null),[h,x]=l.useState(t.displayName),[c,y]=l.useState(t.canonicalDomain),[N,f]=l.useState(t.country),[b,p]=l.useState(t.language),[L,E]=l.useState(t.ownedDomains??[]),[q,$]=l.useState(""),[g,v]=l.useState(t.aliases??[]),[w,ee]=l.useState(""),[W,A]=l.useState(null),[j,D]=l.useState(!1),[S,V]=l.useState(!1),[pe,ne]=l.useState(""),[X,te]=l.useState(""),[ce,B]=l.useState(""),[G,P]=l.useState(""),[re,le]=l.useState(""),[C,U]=l.useState(null),[se,M]=l.useState(null);l.useEffect(()=>{a||(x(t.displayName),y(t.canonicalDomain),f(t.country),p(t.language),E(t.ownedDomains??[]),v(t.aliases??[]))},[t,a]);function z(){r(!1),d(null),x(t.displayName),y(t.canonicalDomain),f(t.country),p(t.language),E(t.ownedDomains??[]),v(t.aliases??[]),$(""),ee("")}function we(){const O=q.trim();O&&(L.includes(O)||E([...L,O]),$(""))}function Oe(O){E(L.filter(_=>_!==O))}function K(){const O=w.trim();if(!O)return;const _=O.toLowerCase();g.some(fe=>fe.toLowerCase()===_)||v([...g,O]),ee("")}function ge(O){v(g.filter(_=>_!==O))}async function Te(){if(!(!h.trim()||!c.trim()||!N.trim()||!b.trim())){o(!0),d(null);try{await s(t.name,{displayName:h.trim(),canonicalDomain:c.trim(),ownedDomains:L,aliases:g,country:N.trim(),language:b.trim()}),r(!1),Ne({title:"Project settings saved",detail:`${h.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(O){d(O instanceof Error?O.message:"Failed to save")}finally{o(!1)}}}async function je(){const O=pe.trim(),_=X.trim(),fe=ce.trim(),Ee=G.trim();if(!(!O||!_||!fe||!Ee)){D(!0),A(null);try{const Ue={label:O,city:_,region:fe,country:Ee};re.trim()&&(Ue.timezone=re.trim()),await oc(t.name,Ue),n(),ne(""),te(""),B(""),P(""),le(""),V(!1),Ne({title:"Location added",detail:`${O} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${O}`,dedupeMode:"drop"})}catch(Ue){A(Ue instanceof Error?Ue.message:"Failed to add location")}finally{D(!1)}}}async function Be(O){D(!0),A(null);try{await lc(t.name,O),n(),Ne({title:"Location removed",detail:`${O} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${O}`,dedupeMode:"drop"})}catch(_){A(_ instanceof Error?_.message:"Failed to remove location")}finally{D(!1)}}async function et(O){D(!0),A(null);try{await ic(t.name,O),n(),Ne({title:"Default location updated",detail:`${O} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(_){A(_ instanceof Error?_.message:"Failed to set default location")}finally{D(!1)}}async function Me(O){U(O),M(null);try{await cc(t.name,O),Ne({title:`${O.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(_){M(_ instanceof Error?_.message:"Could not download tracking results.")}finally{U(null)}}const J=h!==t.displayName||c!==t.canonicalDomain||N!==t.country||b!==t.language||JSON.stringify(L)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(g)!==JSON.stringify(t.aliases??[]),De="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",xe="mb-1 block text-sm font-medium text-secondary",Qe=pe.trim()&&X.trim()&&ce.trim()&&G.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"})]}),!Z()&&!a&&e.jsx(k,{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:()=>d(null),children:"×"})]}),!Z()&&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:xe,children:"Display name"}),e.jsx("input",{className:De,type:"text",value:h,onChange:O=>x(O.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:xe,children:"Canonical domain"}),e.jsx("input",{className:De,type:"text",value:c,onChange:O=>y(O.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:xe,children:"Country"}),e.jsx("input",{className:De,type:"text",value:N,onChange:O=>f(O.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:xe,children:"Language"}),e.jsx("input",{className:De,type:"text",value:b,onChange:O=>p(O.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:xe,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:L.map(O=>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:[O,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Oe(O),"aria-label":`Remove ${O}`,children:"×"})]},O))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${De} flex-1`,type:"text",placeholder:"docs.example.com",value:q,onChange:O=>$(O.target.value),onKeyDown:O=>O.key==="Enter"&&(O.preventDefault(),we())}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:!q.trim(),onClick:we,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:xe,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:g.map(O=>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:[O,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>ge(O),"aria-label":`Remove ${O}`,children:"×"})]},O))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${De} flex-1`,type:"text",placeholder:"Facebook",value:w,onChange:O=>ee(O.target.value),onKeyDown:O=>O.key==="Enter"&&(O.preventDefault(),K())}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:!w.trim(),onClick:K,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(k,{type:"button",disabled:i||!J||!h.trim()||!c.trim(),onClick:Ie(Te),children:i?"Saving...":"Save changes"}),e.jsx(k,{type:"button",variant:"outline",disabled:i,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(O=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:O},O))}):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(O=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:O},O))}):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:[W&&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:[W,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>A(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(O=>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 ${O.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[O.label,O.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:O.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:O.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:O.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:O.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!Z()&&O.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:j,onClick:()=>{et(O.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${O.label} as default location`,children:"Set default"}),!Z()&&e.jsx("button",{type:"button",disabled:j,onClick:()=>{Be(O.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${O.label}`,children:"Remove"})]})})]},O.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),Z()?null:S?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:De,type:"text",value:pe,onChange:O=>ne(O.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:De,type:"text",value:X,onChange:O=>te(O.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:De,type:"text",value:ce,onChange:O=>B(O.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:De,type:"text",value:G,onChange:O=>P(O.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:De,type:"text",value:re,onChange:O=>le(O.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(k,{type:"button",size:"sm",disabled:j||!Qe,onClick:Ie(je),children:j?"Adding...":"Add location"}),e.jsx(k,{type:"button",size:"sm",variant:"outline",disabled:j,onClick:()=>{V(!1),A(null)},children:"Cancel"})]})]}):e.jsx(k,{type:"button",size:"sm",variant:"outline",onClick:()=>V(!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(k,{type:"button",variant:"outline",size:"sm",disabled:C!==null,onClick:Ie(()=>Me("csv")),children:C==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:C!==null,onClick:Ie(()=>Me("json")),children:C==="json"?"Preparing JSON...":"Download JSON"})]})]}),se&&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:se})]})]})]})}function Hs(t){return{...t??{}}}function ax(t,s){const n=Object.entries(t).sort(([r],[i])=>r.localeCompare(i)),a=Object.entries(s).sort(([r],[i])=>r.localeCompare(i));return n.length===a.length&&n.every(([r,i],o)=>{const u=a[o];return u?.[0]===r&&u[1]===i})}function rx({project:t,onSave:s}){const n=Le({queryKey:["settings"],queryFn:Xr,staleTime:6e4}),[a,r]=l.useState(t.providers.length===0),[i,o]=l.useState(t.providers),[u,d]=l.useState(()=>Hs(t.providerModels)),[h,x]=l.useState({providers:t.providers,providerModels:Hs(t.providerModels)}),[c,y]=l.useState(!1),[N,f]=l.useState(!1),[b,p]=l.useState(null),[L,E]=l.useState(null),q=l.useRef(null),$=n.data?.providerCatalog??[],g=l.useMemo(()=>new Set((n.data?.providers??[]).filter(S=>S.configured).map(S=>S.name)),[n.data]),v=l.useMemo(()=>{const S=new Map($.map(V=>[V.name,V]));for(const V of Object.keys(u))S.has(V)||S.set(V,{name:V,displayName:V,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...S.values()].sort((V,pe)=>V.displayName.localeCompare(pe.displayName))},[$,u]),w=!ax(u,h.providerModels);l.useEffect(()=>{if(c||N)return;const S={providers:t.providers,providerModels:Hs(t.providerModels)};x(S),r(S.providers.length===0),o(S.providers),d(S.providerModels)},[t]);function ee(){f(!0),r(!1),i.length===0&&o([...g])}function W(S,V,pe=!1){f(!0),d(ne=>{const X={...ne};return V==="__inherit__"?delete X[S]:V==="__custom__"?X[S]=pe?"":X[S]??"":X[S]=V,X}),V==="__custom__"&&queueMicrotask(()=>q.current?.focus())}function A(S,V){f(!0),o(pe=>V?[...new Set([...pe,S])]:pe.filter(ne=>ne!==S))}function j(){f(!1),r(h.providers.length===0),o(h.providers),d(Hs(h.providerModels)),p(null),E(null)}async function D(){if(!(n.isError||n.isLoading||!a&&i.length===0)){y(!0),p(null),E(null);try{const S=Object.fromEntries(Object.entries(u).filter(([pe,ne])=>ne.trim()!==""&&(a||i.includes(pe)))),V={providers:a?[]:i,providerModels:S};await s(V),x({providers:[...V.providers],providerModels:Hs(V.providerModels)}),f(!1),E("Engine settings saved. They apply on the next sweep.")}catch(S){p(S instanceof Error?S.message:String(S))}finally{y(!1)}}}return Z()?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(k,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):$.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(k,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):g.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(Ut,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":c,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:c,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:a,onChange:()=>{f(!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:ee})," Choose engines"]}),!a&&e.jsx("div",{className:"project-engine-list",children:v.map(S=>{const V=i.includes(S.name),pe=g.has(S.name),ne=V&&!pe,X=u[S.name],te=S.knownModels.some(B=>B.id===X),ce=X===void 0?"__inherit__":te?X:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:V,disabled:!pe&&!V,onChange:B=>A(S.name,B.target.checked)})," ",e.jsx("span",{children:S.displayName}),ne&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),V&&(S.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${S.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${S.name}`,value:ce,onChange:B=>W(S.name,B.target.value,te),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",S.defaultModel||"default"]}),S.knownModels.map(B=>e.jsx("option",{value:B.id,children:B.displayName},B.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),ce==="__custom__"&&e.jsx("input",{ref:q,"aria-label":`${S.displayName} custom model ID`,value:X??"",onChange:B=>{f(!0),d(G=>({...G,[S.name]:B.target.value}))},"aria-describedby":`project-model-hint-${S.name}`}),e.jsxs("p",{id:`project-model-hint-${S.name}`,className:"project-engine-help",children:[X?"Project override":"Inherited from instance settings",". ",S.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},S.name)})})]}),!a&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),b&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:b}),L&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:L}),w&&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(k,{type:"button",onClick:()=>{D()},disabled:c||!a&&i.length===0,children:c?"Saving engines…":"Save engines"}),e.jsx(k,{type:"button",variant:"outline",onClick:j,disabled:c,children:"Cancel"})]})]})}const ix=[{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"}],Hr=["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 lx({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[i,o]=l.useState("daily"),[u,d]=l.useState(6),[h,x]=l.useState(""),[c,y]=l.useState("UTC"),[N,f]=l.useState(!1),[b,p]=l.useState(""),[L,E]=l.useState(!1),[q,$]=l.useState(!1),[g,v]=l.useState(null);l.useEffect(()=>{dc(t).then(n).catch(()=>n(null))},[t]);const w=()=>{if(s&&s!=="loading"){const j=mc(s.preset??null,s.cronExpr);o(j.freq),d(j.hour),x(j.customCron);const D=Hr.includes(s.timezone);y(D?s.timezone:"Other"),f(!D),p(D?"":s.timezone)}else o("daily"),d(6),x(""),y("UTC"),f(!1),p("");v(null),r(!0)},ee=async()=>{E(!0),v(null);try{const D={timezone:N?b.trim()||"UTC":c};i==="custom"?D.cron=h.trim():D.preset=xc(i,u);const S=await nr(t,D);n(S),r(!1),Ne({title:"Schedule saved",detail:Kn(S.preset??null,S.cronExpr,S.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(j){v(j instanceof Error?j.message:"Failed to save schedule")}finally{E(!1)}},W=async()=>{if(!(!s||s==="loading")){E(!0),v(null);try{const j={timezone:s.timezone,enabled:!s.enabled};s.preset?j.preset=s.preset:j.cron=s.cronExpr;const D=await nr(t,j);n(D),Ne({title:D.enabled?"Schedule resumed":"Schedule paused",detail:Kn(D.preset??null,D.cronExpr,D.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(j){v(j instanceof Error?j.message:"Failed to update schedule")}finally{E(!1)}}},A=async()=>{$(!0),v(null);try{await hc(t),n(null),r(!1),Ne({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(j){v(j instanceof Error?j.message:"Failed to remove schedule")}finally{$(!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"})]}),!Z()&&s!=="loading"&&!a&&e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:w,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!a&&s===null&&e.jsx(me,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),s!=="loading"&&!a&&s!==null&&e.jsxs(me,{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:[e.jsx("p",{className:"text-sm font-medium text-strong",children:Kn(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(oe,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),!Z()&&e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:L,onClick:Ie(W),children:s.enabled?"Pause":"Resume"}),!Z()&&e.jsx(k,{type:"button",variant:"ghost",size:"sm",disabled:q,onClick:Ie(A),children:q?"Removing...":"Remove"})]})]}),g&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:g})]}),!Z()&&a&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[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:j=>o(j.target.value),children:ix.map(j=>e.jsx("option",{value:j.value,children:j.label},j.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:u,disabled:i==="twice-daily"||i==="custom",onChange:j=>d(parseInt(j.target.value)),children:Array.from({length:24},(j,D)=>e.jsx("option",{value:D,children:uc(D)},D))})]})]}),i==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:h,onChange:j=>x(j.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"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:N?"Other":c,onChange:j=>{j.target.value==="Other"?(f(!0),y("Other")):(f(!1),y(j.target.value))},children:[Hr.map(j=>e.jsx("option",{value:j,children:j},j)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),N&&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:b,onChange:j=>p(j.target.value)})]}),g&&e.jsx("p",{className:"text-negative-400 text-sm",children:g}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),v(null)},children:"Cancel"}),e.jsx(k,{type:"button",size:"sm",disabled:L||i==="custom"&&!h.trim(),onClick:Ie(ee),children:L?"Saving...":"Save schedule"})]})]})]})}const ox=[{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 cx({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[i,o]=l.useState(""),[u,d]=l.useState(["citation.lost","citation.gained"]),[h,x]=l.useState(!1),[c,y]=l.useState(null),[N,f]=l.useState({}),[b,p]=l.useState(new Set);l.useEffect(()=>{pc(t).then(n).catch(()=>n([]))},[t]);const L=g=>{d(v=>v.includes(g)?v.filter(w=>w!==g):[...v,g])},E=async()=>{if(!(!i.trim()||u.length===0)){x(!0),y(null);try{const g=await gc(t,{channel:"webhook",url:i.trim(),events:u});n(v=>v==="loading"?[g]:[...v,g]),o(""),d(["citation.lost","citation.gained"]),r(!1),Ne({title:"Webhook added",detail:`Notifications will be sent to ${g.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(g){y(g instanceof Error?g.message:"Failed to add webhook")}finally{x(!1)}}},q=async g=>{if(!b.has(g)){p(v=>new Set(v).add(g));try{await bc(t,g),n(v=>v==="loading"?v:v.filter(w=>w.id!==g)),Ne({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${g}`,dedupeMode:"drop"})}catch(v){y(v instanceof Error?v.message:"Failed to remove webhook")}finally{p(v=>{const w=new Set(v);return w.delete(g),w})}}},$=async g=>{f(v=>({...v,[g]:{state:"testing"}}));try{const v=await fc(t,g);f(w=>({...w,[g]:{state:v.ok?"ok":"fail",status:v.status}})),v.ok&&Ne({title:"Test notification sent",detail:`Webhook returned status ${v.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${g}`,dedupeMode:"replace"})}catch{f(v=>({...v,[g]:{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"})]}),!Z()&&s!=="loading"&&e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),y(null)},children:a?"Cancel":"+ Add webhook"})]}),!Z()&&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:i,onChange:g=>o(g.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:ox.map(g=>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(g.value),onChange:()=>L(g.value)}),e.jsx("span",{className:"text-sm text-neutral",children:g.label})]},g.value))})]}),c&&e.jsx("p",{className:"text-negative-400 text-sm",children:c}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),y(null)},children:"Cancel"}),e.jsx(k,{type:"button",size:"sm",disabled:h||!i.trim()||u.length===0,onClick:Ie(E),children:h?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(me,{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(g=>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:g.urlHost,children:g.urlDisplay??g.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:g.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(oe,{tone:g.enabled?"positive":"neutral",children:g.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[N[g.id]&&(()=>{const v=N[g.id],w=v.state==="testing"?"Sending…":v.state==="ok"?`Delivered${v.status?` (${v.status})`:""}`:`Failed${v.status?` (${v.status})`:""}`;return e.jsx(oe,{tone:v.state==="ok"?"positive":v.state==="fail"?"negative":"neutral",children:w})})(),!Z()&&e.jsx(k,{variant:"ghost",size:"sm",type:"button",disabled:N[g.id]?.state==="testing",onClick:()=>{$(g.id)},children:"Test"}),!Z()&&e.jsx(k,{variant:"ghost",size:"sm",type:"button",disabled:b.has(g.id),onClick:()=>{q(g.id)},children:b.has(g.id)?"Removing…":"Remove"})]})})]},g.id))})]}),c&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:c})]})]})}function dx(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 ux({projectName:t,refreshNonce:s}){const n=as(),[a,r]=l.useState(null),[i,o]=l.useState([]),[u,d]=l.useState(null),[h,x]=l.useState([]),[c,y]=l.useState([]),[N,f]=l.useState(null),[b,p]=l.useState(""),[L,E]=l.useState(""),[q,$]=l.useState(""),[g,v]=l.useState(!0),[w,ee]=l.useState(!1),[W,A]=l.useState(null),[j,D]=l.useState("performance");l.useEffect(()=>{S()},[t,s]);async function S(){v(!0),A(null);try{const P=await n.fetchQuery({...oi({client:Q,path:{name:t}}),staleTime:ct});if(r(P),P.connected){const[re,le,C,U]=await Promise.all([n.fetchQuery({...ci({client:Q,path:{name:t}}),staleTime:ct}).catch(()=>null),n.fetchQuery({...di({client:Q,path:{name:t}}),staleTime:ct}).catch(()=>[]),n.fetchQuery({...Bc({client:Q,path:{name:t}}),staleTime:ct}).catch(()=>[]),P.siteUrl?Promise.resolve([]):n.fetchQuery({...zc({client:Q,path:{name:t}}),staleTime:ct}).then(se=>se.sites).catch(()=>[])]);d(re),x(le),y(C),o(U)}else d(null),x([]),y([]),o([])}catch(P){A(P instanceof Error?P.message:"Failed to load Bing data")}finally{v(!1)}}async function V(){if(L.trim()){A(null);try{const P=await Vc(t,L.trim());await it(n,"bing"),E(""),P.availableSites.length>0&&o(P.availableSites),await S()}catch(P){A(P instanceof Error?P.message:"Failed to connect")}}}async function pe(){try{await Kc(t),await it(n,"bing"),r(null),o([]),d(null),x([]),y([]),f(null),$(""),A(null)}catch(P){A(P instanceof Error?P.message:"Failed to disconnect")}}async function ne(){if(q)try{await Qc(t,q),await it(n,"bing"),await S()}catch(P){A(P instanceof Error?P.message:"Failed to set site")}}async function X(){if(b.trim())try{const P=await ui(t,b.trim());await it(n,"bing"),f(P),x(re=>[P,...re])}catch(P){A(P instanceof Error?P.message:"Inspection failed")}}async function te(P){ee(!0),A(null);try{const re=await rr(t,{urls:[P]}),{succeeded:le,failed:C,total:U}=re.summary;Ne({title:"Bing submission requested",detail:C===0?`${le} URL submitted to Bing.`:`${le}/${U} submitted successfully, ${C} failed.`,tone:C===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${P}`,dedupeMode:"replace"})}catch(re){const le=re instanceof Error?re.message:"Submission failed";A(le),Ne({title:"Bing submission failed",detail:le,tone:"negative",dedupeKey:`bing:indexing:${t}:${P}`,dedupeMode:"replace"})}finally{ee(!1)}}async function ce(){ee(!0),A(null),Ne({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 rr(t,{allUnindexed:!0}),{succeeded:re,failed:le,total:C}=P.summary;Ne({title:"Bing submissions requested",detail:le===0?`${re}/${C} URL${C!==1?"s":""} submitted to Bing.`:`${re}/${C} submitted successfully, ${le} failed.`,tone:le===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(P){const re=P instanceof Error?P.message:"Batch submission failed";A(re),Ne({title:"Bing submissions failed",detail:re,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{ee(!1)}}if(g)return e.jsx(me,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return Z()?e.jsxs(me,{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(oe,{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(me,{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(oe,{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:L,onChange:P=>E(P.target.value),onKeyDown:P=>{P.key==="Enter"&&V()}}),e.jsx(ft,{size:"sm",disabled:!L.trim(),onClick:Ie(V),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"})]})]}),W&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:W})]});if(!a.siteUrl)return e.jsxs(me,{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(oe,{tone:"positive",children:"Connected"}),!Z()&&e.jsx(ft,{size:"sm",variant:"ghost",onClick:Ie(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?_t(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"}),i.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:q,onChange:P=>$(P.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),i.map(P=>e.jsxs("option",{value:P.url,children:[P.url,P.verified?" (verified)":""]},P.url))]}),!Z()&&e.jsx(ft,{size:"sm",disabled:!q,onClick:Ie(ne),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."})]})]}),W&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:W})]});const B=[{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"}],G=B.find(P=>P.key===j)??B[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(me,{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(oe,{tone:"positive",children:"Connected"}),!Z()&&e.jsx(ft,{size:"sm",variant:"ghost",onClick:Ie(pe),children:"Disconnect"})]})]}),W&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:W}),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?_t(a.updatedAt):"—"})]})]})]})]}),e.jsxs(me,{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:G.eyebrow}),e.jsx("h3",{children:G.title})]}),e.jsx("p",{className:"text-xs text-muted",children:u?.lastInspectedAt?`Last inspected ${_t(u.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:B.map(P=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${j===P.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>D(P.key),children:P.label},P.key))}),j==="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(bn,{label:"Indexed",value:u.summary.indexed,tone:"positive"}),e.jsx(bn,{label:"Not in index",value:u.summary.notIndexed+(u.summary.unknown??0),tone:"negative"}),e.jsx(bn,{label:"Status unknown",value:u.summary.unknown??0,tone:"neutral"}),e.jsx(bn,{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,")"]}),!Z()&&e.jsx(ft,{size:"sm",variant:"ghost",disabled:w,onClick:Ie(ce),children:w?"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"}),!Z()&&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??"—"}),!Z()&&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:w,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,")"]}),!Z()&&e.jsx(ft,{size:"sm",variant:"ghost",disabled:w,onClick:Ie(ce),children:w?"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"}),!Z()&&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?_t(P.lastCrawledDate):"—"}),!Z()&&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:w,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?_t(P.lastCrawledDate):"—"})]},P.id))})]})})]})]}),j==="coverage"&&!u&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),j==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!Z()&&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:b,onChange:P=>p(P.target.value),onKeyDown:P=>{P.key==="Enter"&&X()}}),e.jsx(ft,{size:"sm",disabled:!b.trim(),onClick:Ie(X),children:"Inspect"})]}),N&&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:N.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:N.inIndex?"text-positive-400":"text-negative-400",children:N.inIndex?"Yes":"No"})," · ","HTTP: ",N.httpCode??"—"," · ","Crawled: ",N.lastCrawledDate??"—"]})]}),h.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:h.map(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(oe,{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:_t(P.inspectedAt)})]},P.id))})]})})]}),j==="performance"&&e.jsx("div",{className:"mt-4",children:c.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:fn[xs.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:fn[xs.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:fn[xs.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:fn[xs.Position]})]})}),e.jsx("tbody",{children:c.map((P,re)=>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)})]},re))})]})})})]})]})}function mx({projectName:t}){const s=as(),[n,a]=l.useState("google"),[r,i]=l.useState(!0),[o,u]=l.useState("idle"),[d,h]=l.useState(null),x=l.useRef(null),[c,y]=l.useState(!1),[N,f]=l.useState(null),[b,p]=l.useState(null),[L,E]=l.useState(!1),[q,$]=l.useState(null),[g,v]=l.useState(null),[w,ee]=l.useState(0);async function W(B=!1){B||i(!0),h(null);try{const[G,P,re]=await Promise.all([s.fetchQuery(ai({client:Q})).catch(()=>null),s.fetchQuery({...Ra({client:Q,path:{name:t}}),staleTime:ct}).catch(()=>[]),s.fetchQuery({...oi({client:Q,path:{name:t}}),staleTime:ct}).catch(()=>null)]),le=P.find(se=>se.connectionType==="gsc")??null;y(!!G?.google?.configured),E(!!G?.bing?.configured),f(le),$(re);const[C,U]=await Promise.all([le?s.fetchQuery({...Zr({client:Q,path:{name:t}}),staleTime:ct}).catch(()=>null):Promise.resolve(null),re?.connected?s.fetchQuery({...ci({client:Q,path:{name:t}}),staleTime:ct}).catch(()=>null):Promise.resolve(null)]);p(C),v(U)}catch(G){h(G instanceof Error?G.message:"Failed to load search console overview")}finally{i(!1)}}async function A(){if(o!=="idle")return;x.current?.abort();const B=new AbortController;x.current=B;const G=B.signal;u("syncing"),h(null),Ne({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const P=[];try{async function re(){if(!N)return;const se=await Uc(t);if(!se?.id)return;const M=2e3,we=Date.now()+12e4;for(;Date.now()<we;){if(G.aborted||(await new Promise(K=>setTimeout(K,M)),G.aborted))return;const Oe=await si(se.id).catch(()=>null);if(!Oe)break;if(["completed","failed","cancelled"].includes(Oe.status)){Oe.status!=="completed"&&P.push(`Google sync ${Oe.status}`);break}}}const le=10;async function C(){if(!q?.connected)return;const se=await s.fetchQuery({...di({client:Q,path:{name:t}}),staleTime:0}).catch(()=>[]),M=[...new Set(se.map(z=>z.url))];if(M.length===0){await Gc(t).catch(()=>null);return}for(let z=0;z<M.length;z+=le){if(G.aborted)return;const we=M.slice(z,z+le),K=(await Promise.allSettled(we.map(ge=>ui(t,ge)))).filter(ge=>ge.status==="rejected").length;K>0&&P.push(`${K} Bing inspection(s) failed`)}}const U=await Promise.allSettled([re(),C()]);for(const se of U)se.status==="rejected"&&P.push(se.reason instanceof Error?se.reason.message:"Sync failed");if(G.aborted)return;if(u("reloading"),await Promise.all([it(s,"gsc"),it(s,"bing")]),await W(!0),ee(se=>se+1),P.length>0){const se=`Partial refresh: ${P.join("; ")}`;h(se),Ne({title:"Search coverage partially refreshed",detail:se,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else Ne({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(re){if(!G.aborted){const le=re instanceof Error?re.message:"Refresh failed";h(le),Ne({title:"Search coverage refresh failed",detail:le,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{G.aborted||u("idle")}}l.useEffect(()=>(W(),()=>{x.current?.abort()}),[t]);const j=N?"positive":c?"caution":"negative",D=N?"Connected":c?"Ready to connect":"Needs setup",S=b?`${b.summary.percentage}% indexed`:N?"Awaiting coverage":"No coverage data",V=b?`${b.summary.notIndexed} not indexed${b.summary.deindexed>0?` · ${b.summary.deindexed} deindexed`:""}`:N?"Run sitemap inspection to populate coverage":c?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",pe=q?.connected?"positive":L?"caution":"negative",ne=q?.connected?"Connected":L?"Ready to connect":"Needs setup",X=g?`${g.summary.percentage}% indexed`:q?.connected?"Awaiting coverage":"No coverage data",te=g?g.summary.notIndexed+(g.summary.unknown??0):0,ce=g?`${te} not in index`:q?.connected?"Inspect URLs to populate coverage":L?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(me,{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:"Search engines"}),e.jsx("h2",{children:"Coverage and performance"})]}),!Z()&&e.jsxs(ft,{type:"button",variant:"outline",size:"sm",disabled:r||o!=="idle",onClick:()=>{A()},children:[e.jsx(sn,{className:`h-3.5 w-3.5 ${o!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":o==="syncing"?"Refreshing Google & Bing…":o==="reloading"?"Reloading workspaces…":"Refresh all"]})]}),d&&e.jsx("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:d}),e.jsx("div",{className:"mt-4 divide-y divide-default border-y border-default",children:[["Google Search Console",r?"Loading…":D,r?"neutral":j,r?"Loading overview…":V,S],["Bing Webmaster Tools",r?"Loading…":ne,r?"neutral":pe,r?"Loading overview…":ce,X]].map(([B,G,P,re,le])=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:B}),e.jsx("span",{className:"ml-2 text-secondary",children:re})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"tabular-nums text-secondary",children:le}),e.jsx(oe,{tone:P,children:G})]})]},B))})]}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([B,G])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===B,className:`project-subnav-link ${n===B?"project-subnav-link-active":""}`,onClick:()=>a(B),children:G},B))}),n==="google"&&e.jsx(eu,{projectName:t,refreshNonce:w}),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(ux,{projectName:t,refreshNonce:w})]})]})}function en({label:t,summary:s,displayValue:n,tooltip:a}){const r=s.value.trim()!==""&&Number.isFinite(Number(s.value)),i=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 ${Tc[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:`${i}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function hx({model:t,sweepRunning:s}){const n=t.citationMovement,a=t.mentionMovement,r=t.movementComparison,i=t.recentRuns.find(y=>y.kind===bs["answer-visibility"]),o=y=>y.tone==="positive"?"improved":y.tone==="negative"?"declined":y.gained>0||y.lost>0?"mixed":"steady",u=o(a),d=o(n),h=(()=>{if(s)return"A fresh sweep is running now";if(!r.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(r.querySetChanged)return"Tracking scope changed since the previous sweep";if(u===d)return u==="steady"?"Answer mentions and citation coverage held steady":u==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${u}`;const y=u==="mixed"?"Answer mention movement was mixed":u==="steady"?"Answer mentions held steady":`Answer mentions ${u}`,N=d==="mixed"?"citation movement was mixed":d==="steady"?"citation coverage held steady":`citation coverage ${d}`;return`${y}; ${N}`})(),x=[r.addedQueryCount>0&&`${r.addedQueryCount} ${r.addedQueryCount===1?"query":"queries"} added`,r.removedQueryCount>0&&`${r.removedQueryCount} ${r.removedQueryCount===1?"query":"queries"} removed`].filter(Boolean).join(", "),c=`${r.comparableQueryCount} comparable ${r.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:h})]}),e.jsx("p",{className:"overview-brief-updated",children:i?`Updated ${i.startedAt}`:"No completed sweep"})]}),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(en,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(en,{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"}),r.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"}),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.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Cited"}),n.gained===0&&n.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[n.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",n.gained]}),n.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",n.lost]})]})]})]}),e.jsx("p",{className:`overview-brief-panel-copy ${r.querySetChanged?"text-caution-400/80":""}`,children:r.querySetChanged?`${x||"Query set changed"} · ${c}.`:`${c}.`})]}):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:"Run another sweep to measure mention and citation movement."})]})]})]})]})}function pa({id:t,eyebrow:s,title:n,meta:a,defaultOpen:r=!1,children:i}){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($a,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:i})]})}function xx({summary:t,projectLabel:s}){const n=t.breakdown;if(n.perCompetitor.length===0)return null;const a=n.projectMentionSnapshots+n.competitorMentionSnapshots;if(a===0)return null;const r=[{label:`${s} (you)`,mentions:n.projectMentionSnapshots,isYou:!0},...n.perCompetitor.map(o=>({label:o.domain,mentions:o.mentionSnapshots,isYou:!1}))].sort((o,u)=>u.mentions-o.mentions),i=r[0]?.mentions??1;return e.jsxs("div",{className:"mention-share-breakdown",children:[e.jsx("p",{className:"mention-share-breakdown-title",children:"Mention share breakdown · latest run"}),e.jsx("ul",{className:"mention-share-breakdown-rows",children:r.map(o=>{const u=o.mentions/a*100;return e.jsxs("li",{className:"mention-share-breakdown-row",children:[e.jsx("span",{className:`mention-share-breakdown-label ${o.isYou?"text-heading font-medium":"text-secondary"}`,children:o.label}),e.jsx("div",{className:"mention-share-breakdown-bar",children:e.jsx("div",{className:`mention-share-breakdown-bar-fill ${o.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${Math.max(o.mentions/i*100,2)}%`}})}),e.jsx("span",{className:"mention-share-breakdown-count",children:o.mentions}),e.jsxs("span",{className:"mention-share-breakdown-share",children:[u.toFixed(1),"%"]})]},o.label)})})]})}function px({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:a}=Yr(),r=li(),[i,o]=l.useState(new Set);if(t.length===0&&s.rows.length===0)return null;const u=p=>{o(L=>{const E=new Set(L);return E.delete(p),E})},d=p=>{o(L=>new Set(L).add(p)),r.mutate({projectName:n,queries:[p]},{onSuccess:()=>{Ne({tone:"positive",title:`Tracking "${p}"`}),u(p)},onError:L=>{Ne({tone:"negative",title:`Could not track "${p}"`,detail:String(L)}),u(p)}})},h=p=>e.jsxs("div",{className:"py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:p.title}),p.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:p.detail}):null]}),e.jsx(oe,{tone:p.tone,children:p.actionLabel})]}),p.affectedPhrases.length>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:["Evidence · ",p.affectedPhrases.length," affected ",p.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:p.affectedPhrases.map((L,E)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(ba,{state:L.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:L.query}),L.provider?e.jsx(Is,{provider:L.provider}):null,!Z()&&L.evidenceId?e.jsx(k,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(L.evidenceId)},children:"View evidence"}):null]},L.evidenceId||`${p.id}-${E}`))})]}):null]},p.id),x=p=>{const L=i.has(p.query);return e.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:p.query}),e.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:p.reason})]}),Z()?null:e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:L,"aria-label":`Track query "${p.query}"`,onClick:()=>d(p.query),children:L?"Tracking…":"Track"})]},p.query)},c=t.slice(0,1),y=s.rows.slice(0,1),N=t.slice(1),f=s.rows.slice(1),b=N.length+f.length;return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[c.map(h),y.map(x)]}),b>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[b," more ",b===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[N.map(h),f.map(x)]})]}):null]})}function Rx(t){const{projectName:s}=al({from:"/projects/$projectName"}),a=jc()?.dashboard.projects.find(y=>y.project.name===s||y.project.id===s)?.project.name??null,r=Le({...yc({client:Q}),enabled:!a}),i=a??r.data?.find(y=>y.name===s||y.id===s)?.name??null,{commandCenter:o,isLoading:u,latestVisibilityRevision:d,refetch:h}=vc(i),x=!a&&r.isLoading||u;return!i&&!a&&r.isSuccess&&!u?e.jsx("div",{className:"page-container",children:e.jsxs(me,{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(k,{asChild:!0,children:e.jsx(Ut,{to:"/",children:"Return to overview"})})]})}):!o||x?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(y=>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"})]},y))}),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(y=>e.jsx("div",{className:"skeleton-text-sm w-full"},y))})]})]}):e.jsx(fx,{model:o,refetch:h,latestVisibilityRevision:d,...t})}function gx({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null);if(l.useEffect(()=>{if(!n)return;const o=d=>{r.current&&!r.current.contains(d.target)&&a(!1)},u=d=>{d.key==="Escape"&&a(!1)};return document.addEventListener("pointerdown",o),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",o),document.removeEventListener("keydown",u)}},[n]),t.length===0)return null;const i=t.some(o=>o.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 ${i?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(o=>!o),children:["More",e.jsx($a,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(o=>e.jsx(Ut,{to:o.href,role:"menuitem",className:`project-subnav-menu-item ${o.key===s?"project-subnav-menu-item-active":""}`,"aria-current":o.key===s?"page":void 0,onClick:()=>a(!1),children:o.label},o.key))}):null]})}function fx({tab:t,model:s,refetch:n,latestVisibilityRevision:a}){const r=rl(),i=as(),{canWrite:o}=Nc(),u=l.useMemo(()=>{const R=wc();return R?Sc(R.projectTabs):void 0},[]),d=Cc(t,u),h=l.useMemo(()=>s.competitors.map(R=>R.domain),[s.competitors]),[x,c]=l.useState(!1),[y,N]=l.useState(!1),f=li(),b=il({strict:!1}).manageQueries===!0,[p,L]=l.useState(b),[E,q]=l.useState(""),[$,g]=l.useState(!1),[v,w]=l.useState(null),[ee,W]=l.useState(!1),[A,j]=l.useState(""),[D,S]=l.useState(!1),[V,pe]=l.useState(void 0),[ne,X]=l.useState(!1),[te,ce]=l.useState(null),[B,G]=l.useState(null),[P,re]=l.useState(!1),[le,C]=l.useState({scope:"all",queryClass:"non-brand"}),[U,se]=l.useState(!1),M=s?.visibilityEvidence??[],z=s?.project.name??"",we=s?.project.displayName||s?.project.name||z,Oe=kc(),K=Le({...Pc({client:Q,path:{name:z}}),enabled:d==="portfolio"&&!!z,staleTime:0,refetchOnMount:"always"}),ge=Le({...Ac({client:Q,path:{name:z}}),enabled:!Z()&&(d==="portfolio"||d==="overview"||d==="settings")&&!!z,staleTime:0,refetchOnMount:"always"}),Te=Le({...Rc({client:Q,path:{name:z}}),enabled:!Z()&&(d==="portfolio"||d==="overview"||d==="settings")&&!!z,staleTime:0,refetchOnMount:"always"}),je=ge.data?.active??null,Be=je===null?null:Number(je.plan.schemaVersion),et=je?.revision??0;l.useEffect(()=>{C({scope:"all",queryClass:"non-brand"}),se(!1)},[z,et]);const Me={client:Q,path:{name:z},query:{scope:le.scope,...le.groupKey?{groupKey:le.groupKey}:{},queryClass:le.queryClass,...le.search?{search:le.search}:{},limit:50}},J=ll({...$c(Me),enabled:d==="overview"&&!!z&&Be===2,initialPageParam:Me,getNextPageParam:(R,be)=>{if(!R.properties.nextCursor)return;const ye=be[0]?.measurement.displayedRunId;return{path:Me.path,query:{...Me.query,cursor:R.properties.nextCursor,...ye?{runId:ye}:{}}}},placeholderData:Wr,staleTime:0,refetchOnMount:"always"}),De=J.data?.pages[0]?.measurement.displayedRunId,xe=Le({...Ic({client:Q,path:{name:z},query:{revision:et,...De?{runId:De}:{}}}),enabled:d==="overview"&&!!z&&je!==null&&(Be===1||U&&De!==void 0),staleTime:0,refetchOnMount:"always"}),Qe=ge.data!==void 0,O=K.data!==void 0,_=ge.isPending&&!Qe,fe=ge.isError&&!Qe,Ee=K.isPending&&!O,Ue=K.isError&&!O,Ve=xe.data!==void 0,Nt=$h({activePlanSchemaVersion:Te.data?.activeSchemaVersion??Be,hasDraft:Te.data?.draft!==null&&Te.data?.draft!==void 0}),bt=l.useMemo(()=>{const R=J.data?.pages;return R?!id(R):!1},[J.data]),ke=l.useMemo(()=>{const R=J.data?.pages,be=R?.[0],ye=R?.at(-1);if(!(!be||!ye||bt))return{...be,properties:{...be.properties,items:R.flatMap(Pt=>Pt.properties.items),nextCursor:ye.properties.nextCursor}}},[bt,J.data]),Fe=l.useMemo(()=>{if(je)return je.plan.schemaVersion===1?xe.data?qh(je,xe.data):void 0:ke?ld({overview:ke,activePlan:je,report:xe.data,reportState:ke.measurement.displayedRunId===void 0?"ready":xe.isFetching&&xe.data===void 0?"loading":xe.isError&&xe.data===void 0?"error":xe.data?"ready":"loading"}):void 0},[je,xe.data,xe.isError,xe.isFetching,ke]),qt=Be===2?bt?"error":J.isPending?"loading":J.isError&&Fe===void 0?"error":"ready":xe.isPending&&!Ve?"loading":xe.isError&&!Ve?"error":"ready",tt=(s?.recentRuns??[]).some(R=>R.kind===bs["answer-visibility"]&&(R.status===ar.running||R.status===ar.queued)),dt=l.useMemo(()=>(s?.project.locations??[]).map(R=>R.label),[s?.project.locations]),Ye=l.useMemo(()=>new Set(M.map(R=>R.location??"")),[M]),wt=Ye.has(""),St=l.useMemo(()=>[...new Set(M.map(R=>R.query))].sort((R,be)=>R.localeCompare(be)),[M]),Re=l.useMemo(()=>{const R=[...Ye].filter(Boolean);return R.length>1?R:dt},[Ye,dt]);l.useEffect(()=>{if(V===void 0||V===""||!z){G(null),re(!1);return}re(!0),Lc(z,V,20).then(R=>{G(R),re(!1)}).catch(()=>{G(null),re(!1)})},[V,z]);const Ae=l.useMemo(()=>{if(!B)return null;const R=new Map;for(const be of B){for(const[ye,Pt]of Object.entries(be.providerRuns??{}))R.set(`${be.query}::${ye}`,Pt.map(nt=>({runId:nt.runId,citationState:nt.citationState,createdAt:nt.createdAt,answerMentioned:nt.answerMentioned,visibilityState:nt.visibilityState,visibilityTransition:nt.visibilityTransition,mentionState:nt.mentionState,mentionTransition:nt.mentionTransition})));(!be.providerRuns||Object.keys(be.providerRuns).length===0)&&R.set(`${be.query}::`,be.runs.map(ye=>({runId:ye.runId,citationState:ye.citationState,createdAt:ye.createdAt,answerMentioned:ye.answerMentioned,visibilityState:ye.visibilityState,visibilityTransition:ye.visibilityTransition,mentionState:ye.mentionState,mentionTransition:ye.mentionTransition})))}return R},[B]),lt=l.useMemo(()=>{let R=V!==void 0?M.filter(be=>V===""?!be.location:be.location===V):M;if(te){const be=te.toLowerCase();R=R.filter(ye=>ye.competitorDomains.some(Pt=>Pt.toLowerCase()===be))}return Ae?R.map(be=>{const ye=Ae.get(`${be.query}::${be.provider}`)??Ae.get(`${be.query}::`);return ye?{...be,runHistory:ye}:be}):R},[M,V,te,Ae]);async function Ge(){try{await Oe.mutateAsync({projectName:z,projectLabel:we,sourceAction:"project-run"}),n()}catch{}}async function Ot(){N(!0);try{await Mc(z),Ne({title:"Project deleted",detail:`${we} was removed.`,tone:"positive",dedupeKey:`project:delete:${z}`,dedupeMode:"drop"}),r({to:"/"}),n()}catch(R){console.error("Failed to delete project:",R)}finally{N(!1)}}async function Ct(){const R=E.split(`
11
+ `).map(be=>be.trim()).filter(Boolean);if(R.length!==0){g(!0);try{await Oc(z,R),n(),q("")}finally{g(!1)}}}async function Je(R){w(R);try{await qc(z,[R]),n()}catch(be){Ne({title:"Could not remove query",detail:be instanceof Error?be.message:`Failed to remove "${R}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{w(null)}}async function He(){const R=A.trim();if(R){S(!0);try{await Dc(z,[R]),n(),j(""),W(!1)}finally{S(!1)}}}async function F(R){const be=s.competitors.find(ye=>ye.domain===R);if(!be){Ne({title:"Could not remove competitor",detail:`Could not find ${R} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"});return}try{await Ec(z,be.id),n()}catch(ye){Ne({title:"Could not remove competitor",detail:ye instanceof Error?ye.message:`Failed to remove ${be.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function Ce(R,be){const ye=await Fc(R,be);return await i.invalidateQueries({queryKey:ri({client:Q})}),i.setQueryData(_c({client:Q,path:{name:R}}),ye),dx(i,ye),ye}const de=`/projects/${encodeURIComponent(s.project.name)}`,ve=[{key:"overview",label:"Overview",href:de},{key:"search-console",label:"Search Engines",href:`${de}/search-console`},{key:"activity",label:"Activity",href:`${de}/activity`},{key:"technical-aeo",label:"Technical AEO",href:`${de}/technical-aeo`},{key:"local",label:"Local Presence",href:`${de}/local`},{key:"discovery",label:"Query Discovery",href:`${de}/discovery`},{key:"backlinks",label:"Backlinks",href:`${de}/backlinks`}],Ke=[{key:"report",label:"Report",href:`${de}/report`},{key:"history",label:"Change History",href:`${de}/history`}],Wt=ve.filter(R=>Qn(R.key,u)),st=Ke.filter(R=>Qn(R.key,u)),kt=Qn("settings",u)?{key:"settings",label:"Settings",href:`${de}/settings`}:null;function rs(R,be=!1){const ye=document.getElementById(R);if(!ye)return;be&&ye instanceof HTMLDetailsElement&&(ye.open=!0);const Pt=window.matchMedia("(prefers-reduced-motion: reduce)").matches;window.requestAnimationFrame(()=>{ye.scrollIntoView({behavior:Pt?"auto":"smooth",block:"start"}),(ye instanceof HTMLDetailsElement?ye.querySelector("summary"):ye)?.focus({preventScroll:!0})})}return e.jsxs("div",{className:"page-container",children:[x?e.jsxs(me,{className:"surface-card p-6 mb-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(k,{type:"button",variant:"destructive",disabled:y,onClick:Ie(Ot),children:y?"Deleting...":"Yes, delete project"}),e.jsx(k,{type:"button",variant:"outline",disabled:y,onClick:()=>c(!1),children:"Cancel"})]})]}):null,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]}),!Z()&&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(R=>e.jsx("span",{className:"tag",children:R},R))]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:s.dateRangeLabel}),!Z()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ft,{type:"button",variant:"outline",size:"icon",onClick:()=>c(!0),"aria-label":"Delete project",children:e.jsx(ad,{className:"h-4 w-4 text-secondary"})}),e.jsx(ft,{type:"button",disabled:Oe.isPending||tt,onClick:Ie(Ge),children:Oe.isPending?"Starting…":tt?"Sweep running…":"Run now"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[Wt.map(R=>e.jsx(Ut,{to:R.href,className:`project-subnav-link ${R.key===d?"project-subnav-link-active":""}`,"aria-current":R.key===d?"page":void 0,children:R.label},R.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(gx,{items:st,activeTab:d}),kt&&e.jsx(Ut,{to:kt.href,className:`project-subnav-link ${d==="settings"?"project-subnav-link-active":""}`,"aria-current":d==="settings"?"page":void 0,children:kt.label},kt.key)]})]}),d==="portfolio"&&!Z()?e.jsx(xh,{projectName:z,canEdit:o,queries:K.data??[],isQueryLoading:Ee,isQueryError:Ue,onRetryQueries:()=>{K.refetch()},publishedPlan:je,onCreateQueries:async R=>(await f.mutateAsync({projectName:z,queries:[...R]}),(await K.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{r({to:"/projects/$projectName",params:{projectName:z},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([Te.refetch(),ge.refetch()]).finally(()=>{r({to:"/projects/$projectName",params:{projectName:z}})})}},z):d==="overview"?e.jsxs(e.Fragment,{children:[fe?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(k,{type:"button",size:"sm",variant:"outline",onClick:()=>{ge.refetch()},children:"Retry setup check"})]}):null,e.jsx(Rh,{mode:Nt,canEdit:o&&!Z()&&!_&&!fe,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(om,{projectName:s.project.name,competitorDomains:h,analyticsRevision:a})}),e.jsx(hx,{model:s,sweepRunning:tt}),e.jsx(px,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:s.project.name}),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:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[s.competitors.length," tracked"]}),!Z()&&e.jsx(ft,{type:"button",variant:"outline",size:"sm",onClick:()=>W(!ee),children:ee?"Cancel":"+ Add competitor"})]})]}),e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(en,{label:"Mention share",summary:s.mentionShareSummary,tooltip:"Of all brand mentions in answer text across your tracked queries (you + tracked competitors), the percentage that were you. Measured from the latest sweep."}),e.jsx(en,{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(en,{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(xx,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name})]}),ee&&e.jsxs("div",{className:"mt-4 mb-3 flex gap-2 rounded-lg border border-base bg-bg-elevated/40 p-3",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:"competitor.com",value:A,onChange:R=>j(R.target.value),onKeyDown:R=>{R.key==="Enter"&&He()}}),e.jsx(ft,{type:"button",size:"sm",disabled:!A.trim()||D,onClick:Ie(He),children:D?"Adding...":"Add"})]}),s.competitors.length>0&&e.jsxs("details",{className:"inline-disclosure mt-4",children:[e.jsx("summary",{children:"Review tracked competitors"}),e.jsx("div",{className:"mt-3",children:e.jsx(Dd,{competitors:s.competitors,onSelectCompetitor:R=>{ce(R),rs("evidence-section",!0)},onRemoveCompetitor:Z()?void 0:R=>{F(R)},activeFilter:te})})]})]}),e.jsxs(pa,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:Z(),children:[!Z()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(ft,{type:"button",variant:"outline",size:"sm",onClick:()=>L(!p),children:p?"Done":"Manage queries"})}),!Z()&&p&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[St.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:St.map(R=>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:R,children:R}),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 ${R}`,title:`Stop tracking "${R}"`,disabled:v!==null,onClick:()=>{Je(R)},children:v===R?"Removing…":"Remove"})]},R))}):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:E,onChange:R=>q(R.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[E.split(`
12
+ `).filter(R=>R.trim()).length," to add"]}),e.jsx(ft,{type:"button",size:"sm",disabled:!E.trim()||$,onClick:Ie(Ct),children:$?"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 ${V===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":V===void 0,onClick:()=>{pe(void 0)},children:"All locations"}),s.project.locations.map(R=>e.jsx("button",{className:`filter-chip ${V===R.label?"filter-chip-active":""}`,type:"button","aria-pressed":V===R.label,onClick:()=>{pe(R.label),X(!1)},children:R.label},R.label)),wt&&e.jsx("button",{className:`filter-chip ${V===""?"filter-chip-active":""}`,type:"button","aria-pressed":V==="",onClick:()=>{pe(""),X(!1)},children:"No location"}),Re.length>1&&V===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${ne?"filter-chip-active":""}`,type:"button","aria-pressed":ne,onClick:()=>X(R=>!R),title:"Side-by-side location comparison",children:"Compare"})]}),te&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-negative-900/40 bg-negative-950/20 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-negative-400",children:"Competitor filter"}),e.jsxs("span",{className:"text-sm text-strong",children:["Showing queries where ",e.jsx("span",{className:"font-semibold",children:te})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-secondary hover:text-strong",onClick:()=>ce(null),children:"Clear filter ×"})]}),e.jsx(Id,{evidence:lt,compareLocations:ne})]}),e.jsxs(pa,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:Z(),children:[e.jsx(Pu,{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(R=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(Is,{provider:R.provider}),R.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:R.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[R.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[R.cited," of ",R.total]})]},`${R.provider}::${R.model??"unknown"}`))})]})})]})]}),!Z()&&e.jsx(pa,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(R=>e.jsx(Hc,{run:R},R.id))})})]}),report:Fe,reportState:qt,onOpenSetup:Z()?void 0:()=>{r({to:"/projects/$projectName/portfolio",params:{projectName:z}})},onRetryReport:()=>{Be===2?Promise.all([J.refetch(),xe.refetch()]):xe.refetch()},onViewChange:R=>{C({scope:R.scope,...R.groupKey?{groupKey:R.groupKey}:{},queryClass:R.queryClass,...R.search?.trim()?{search:R.search.trim()}:{}})},onLoadMore:R=>{R===ke?.properties.nextCursor&&J.fetchNextPage()},onPropertyExpand:()=>{U&&xe.isError&&xe.refetch(),se(!0)},onRetryEvidence:()=>{xe.refetch()},renderPropertyLink:Be===2&&!Z()?({id:R,name:be})=>e.jsx(Ut,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:z,targetKey:R},className:"text-link hover:underline",children:be}):void 0,isViewLoading:J.isPlaceholderData,isLoadingMore:J.isFetchingNextPage,isLoadMoreError:J.isFetchNextPageError,viewSearch:le.search??""},`${z}:${et}`)]}):d==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(nx,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(R,be)=>{await Ce(R,be)},onRefresh:()=>{n()}}),e.jsx(rx,{project:s.project,onSave:async R=>{await Ce(s.project.name,R)}}),o&&!Z()&&Nt.surface!=="simple-overview"?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:"Change which Properties and questions are measured."}),e.jsx(k,{type:"button",variant:"outline",onClick:()=>{r({to:"/projects/$projectName/portfolio",params:{projectName:z}})},children:"Edit setup"})]}):null,e.jsx(lx,{projectName:s.project.name}),e.jsx(cx,{projectName:s.project.name})]}):d==="report"?e.jsx(Uh,{projectName:s.project.name}):d==="discovery"?e.jsx(fm,{projectName:z}):d==="technical-aeo"?e.jsx(Rm,{projectName:s.project.name,projectId:s.project.id}):d==="history"?e.jsx($m,{projectName:s.project.name}):d==="activity"?e.jsx(Bd,{projectName:s.project.name}):d==="backlinks"?e.jsx(ku,{projectName:s.project.name}):d==="local"?e.jsx(su,{projectName:s.project.name,projectId:s.project.id}):d==="search-console"?e.jsx(mx,{projectName:s.project.name}):null]})}export{Rx as ProjectPage,dx as patchProjectDashboardCache};