@canonry/canonry 7.126.0 → 7.128.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/assets/agent-workspace/skills/aero/references/getting-started.md +2 -3
  2. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +6 -1
  3. package/assets/agent-workspace/skills/canonry/references/getting-started.md +2 -3
  4. package/assets/agent-workspace/skills/canonry/references/indexing.md +4 -1
  5. package/assets/assets/{AccessControls-ogV5Gz4X.js → AccessControls-QW1RtXqK.js} +2 -2
  6. package/assets/assets/{AgentSetupPage-DEVRQ04Z.js → AgentSetupPage-BFO6Jx36.js} +4 -4
  7. package/assets/assets/{AuditHistoryPanel-DyXqEWpq.js → AuditHistoryPanel-Cn9Tnnxo.js} +1 -1
  8. package/assets/assets/{BacklinksPage-B4powgfU.js → BacklinksPage-Bv12EM38.js} +1 -1
  9. package/assets/assets/{ChartPrimitives-De8aCfZp.js → ChartPrimitives-DIAAi1Eq.js} +1 -1
  10. package/assets/assets/{HistoryPage-CN2VzZeY.js → HistoryPage-Bfn3nVjo.js} +1 -1
  11. package/assets/assets/MeasurementPropertyPage-Cwyl4MS5.js +4 -0
  12. package/assets/assets/ProjectPage-JCH068IS.js +15 -0
  13. package/assets/assets/{RunsPage-p4FSGSzR.js → RunsPage-B56n3Xwl.js} +1 -1
  14. package/assets/assets/{ServerTrafficSection-xzcv0S85.js → ServerTrafficSection-JZ7tID1A.js} +3 -3
  15. package/assets/assets/{SettingsPage-C6Oh-XQT.js → SettingsPage-C1XRb6UB.js} +1 -1
  16. package/assets/assets/{ToneBadge-CxostV9z.js → ToneBadge-DSr49xyr.js} +2 -2
  17. package/assets/assets/{TrafficPage-D5_wyrCY.js → TrafficPage-BIbFPquR.js} +1 -1
  18. package/assets/assets/{TrafficSourceDetailPage-CGbQlo1a.js → TrafficSourceDetailPage-DpJyjmCY.js} +1 -1
  19. package/assets/assets/{account-context-Mya_uodz.js → account-context-CRwUczVQ.js} +1 -1
  20. package/assets/assets/{agent-trust-copy-DjdjfF7q.js → agent-trust-copy-DduiTpc0.js} +1 -1
  21. package/assets/assets/{card-B20lVlLX.js → card-DtN_FyC4.js} +1 -1
  22. package/assets/assets/index-CmdxqiD3.js +43 -0
  23. package/assets/assets/{preload-helper-DN5snQJ-.js → preload-helper-CqQPtzI4.js} +1 -1
  24. package/assets/assets/{query-client-2aOrFPOz.js → query-client-BcqjBQN8.js} +1 -1
  25. package/assets/assets/react-query-Bt-PaSFW.js +1 -0
  26. package/assets/assets/{react-sigma_core.esm.min-DHJ5hJS1.js → react-sigma_core.esm.min-BTRnvmn2.js} +1 -1
  27. package/assets/assets/{server-traffic-Cx7fQ2OF.js → server-traffic-D598cM_v.js} +1 -1
  28. package/assets/assets/service--wSlHsiA.js +1 -0
  29. package/assets/index.html +9 -9
  30. package/dist/activity-2KFFWLYN.js +13 -0
  31. package/dist/{ads-7JYMSESY.js → ads-PB3VFUPV.js} +4 -4
  32. package/dist/{agent-3AIKIBOZ.js → agent-VOL7SOEQ.js} +8 -8
  33. package/dist/{agent-ask-F7OMYKXU.js → agent-ask-F46ERE3W.js} +4 -4
  34. package/dist/{agent-conversations-W3WMXSDE.js → agent-conversations-T5Q43627.js} +4 -4
  35. package/dist/{agent-journeys-SNUC3IGG.js → agent-journeys-GVEVJ5J2.js} +4 -4
  36. package/dist/{agent-memory-PFVKTCZC.js → agent-memory-XXN7QXNM.js} +4 -4
  37. package/dist/{agent-providers-TV3SV75C.js → agent-providers-U6XIM5JI.js} +4 -4
  38. package/dist/{agent-transcript-X6RMTVV5.js → agent-transcript-ONEA6JBO.js} +4 -4
  39. package/dist/{analytics-U6CLZESN.js → analytics-XWVTM57N.js} +4 -4
  40. package/dist/{answerability-YJSPCE4T.js → answerability-GNYSELX5.js} +4 -4
  41. package/dist/{apply-VBX4BJCQ.js → apply-WXW4KWUK.js} +4 -4
  42. package/dist/{backfill-VY4PWO5A.js → backfill-SWDR5M4O.js} +11 -11
  43. package/dist/{backlinks-U7SI3OOX.js → backlinks-5LIBLUEG.js} +4 -4
  44. package/dist/{bing-HONIKTUQ.js → bing-4U4ODKGV.js} +4 -4
  45. package/dist/{bootstrap-K7LRU624.js → bootstrap-FY72AHVW.js} +11 -11
  46. package/dist/{cdp-VVETHJFO.js → cdp-H5WMBYIF.js} +8 -8
  47. package/dist/{chunk-474HYXOY.js → chunk-2PLJ4QG5.js} +4 -4
  48. package/dist/{chunk-WCRFVAYB.js → chunk-2T4OGJWP.js} +1 -1
  49. package/dist/{chunk-UQXWOIPI.js → chunk-2VDYFOKB.js} +8 -8
  50. package/dist/{chunk-2BSAW7H4.js → chunk-3GE4Z4J3.js} +5 -5
  51. package/dist/{chunk-CWV3JV2S.js → chunk-3ZNDJ4OM.js} +5 -5
  52. package/dist/{chunk-N7NL4SCF.js → chunk-425BZPKK.js} +5 -5
  53. package/dist/{chunk-SBAQZ6PY.js → chunk-5WDU7ZML.js} +7 -7
  54. package/dist/{chunk-V7LDAQAK.js → chunk-6TXHNNKW.js} +4 -4
  55. package/dist/{chunk-RKM6YN3X.js → chunk-A36PZKKS.js} +2 -2
  56. package/dist/{chunk-I3MJISLF.js → chunk-BAO3PHQP.js} +2 -2
  57. package/dist/{chunk-CFGVH4K5.js → chunk-DWFCDUE2.js} +372 -372
  58. package/dist/{chunk-VNCDWND5.js → chunk-DY2Q3VIM.js} +2 -2
  59. package/dist/{chunk-MVTPR7ZY.js → chunk-FIF4N7DP.js} +1 -1
  60. package/dist/{chunk-QQXE2GUM.js → chunk-FMS7CIEK.js} +2 -2
  61. package/dist/{chunk-6ZJKEUGC.js → chunk-G2NIO2J3.js} +2 -2
  62. package/dist/{chunk-2WT4IQD7.js → chunk-GCBFSIKI.js} +1 -1
  63. package/dist/{chunk-DRNCCGUW.js → chunk-GKQ4CYUM.js} +22 -2
  64. package/dist/{chunk-4IC3FHM5.js → chunk-GPPTW3HU.js} +4 -4
  65. package/dist/{chunk-GNQZBQ5X.js → chunk-GRX2DION.js} +4 -4
  66. package/dist/{chunk-OU7TJX25.js → chunk-GTX7C5Y5.js} +5 -5
  67. package/dist/{chunk-3CYLLBEC.js → chunk-GW4CL5ZO.js} +106 -25
  68. package/dist/{chunk-VRBKUMA3.js → chunk-HQEH4YRO.js} +1 -1
  69. package/dist/{chunk-LLKNKNEB.js → chunk-HS2HYFPX.js} +79 -4
  70. package/dist/{chunk-IOXAYJ4Z.js → chunk-IIL4NKRU.js} +4 -4
  71. package/dist/{chunk-UQG5TWLM.js → chunk-K3YHPTKL.js} +2 -2
  72. package/dist/{chunk-DP2SUDRW.js → chunk-LWRPSAVC.js} +1 -1
  73. package/dist/{chunk-6JQ5ZM5H.js → chunk-M4IAXLBT.js} +3 -3
  74. package/dist/{chunk-F2TGOWIW.js → chunk-MG4COK23.js} +2 -2
  75. package/dist/{chunk-V3GIVVXW.js → chunk-NEJEHRPT.js} +2 -2
  76. package/dist/{chunk-2CRAVATO.js → chunk-OKIAF573.js} +1 -1
  77. package/dist/{chunk-2RF4RB53.js → chunk-PWXLKW2F.js} +3 -3
  78. package/dist/{chunk-5UJ5CG6J.js → chunk-QWD3ABAW.js} +1 -1
  79. package/dist/{chunk-SF2KLXZM.js → chunk-QXRI6DRE.js} +6 -6
  80. package/dist/{chunk-DU26WF7A.js → chunk-RDCEFEXP.js} +3 -3
  81. package/dist/{chunk-N3QGWIWL.js → chunk-RMLGMB5B.js} +1 -1
  82. package/dist/{chunk-CF6R6DUA.js → chunk-RPAWPX7B.js} +1 -1
  83. package/dist/{chunk-FVPJ5CRH.js → chunk-X6DD3OIR.js} +3 -2
  84. package/dist/{chunk-KTRRC5P4.js → chunk-XONND7NT.js} +3 -3
  85. package/dist/{chunk-NCOW55N3.js → chunk-ZKIEOEUZ.js} +2 -2
  86. package/dist/{citations-UREMIMHU.js → citations-622BWQTR.js} +5 -5
  87. package/dist/{cli-catalog-JXAESW3A.js → cli-catalog-ACK3FVAX.js} +4 -4
  88. package/dist/cli-commands-IM2ISRXZ.js +18 -0
  89. package/dist/cli.js +14 -14
  90. package/dist/{competitor-DIM5OLHQ.js → competitor-QYZIWXGC.js} +4 -4
  91. package/dist/{content-A2V3BCU6.js → content-PJASAMIV.js} +4 -4
  92. package/dist/{dashboard-ZOBWCHMG.js → dashboard-FQOS3J4B.js} +7 -7
  93. package/dist/{demo-6OE36ZR7.js → demo-ZGGVSKN4.js} +3 -3
  94. package/dist/{demo-server-GIUEYO52.js → demo-server-TLXLEPOI.js} +13 -13
  95. package/dist/{discover-Y67SDM3U.js → discover-ZLDSXDRI.js} +5 -5
  96. package/dist/{discover-eval-Z6DAQNRE.js → discover-eval-7F5Q3RXS.js} +4 -4
  97. package/dist/{doctor-XBAVQYHA.js → doctor-3KSQZDZ3.js} +4 -4
  98. package/dist/{evidence-OYRYCO3J.js → evidence-BJZIRJ4U.js} +4 -4
  99. package/dist/{export-cmd-MZRJI63B.js → export-cmd-BYPGV4IU.js} +4 -4
  100. package/dist/{ga-VPVM2NI3.js → ga-A3BAZCYH.js} +4 -4
  101. package/dist/{gbp-SKZQA4E5.js → gbp-U6VCRAFN.js} +4 -4
  102. package/dist/{google-6LWEJTAC.js → google-UNQZBUGS.js} +5 -5
  103. package/dist/{google-marketing-X2FOU4W2.js → google-marketing-QSIRQAVH.js} +2 -2
  104. package/dist/{health-cmd-XF5PCISV.js → health-cmd-Z5KTTJQU.js} +5 -5
  105. package/dist/{history-TP6O4LMA.js → history-IIGUZMOM.js} +4 -4
  106. package/dist/index.d.ts +90 -70
  107. package/dist/index.js +27 -27
  108. package/dist/{init-YMFUF4YJ.js → init-GGKLWNRS.js} +13 -13
  109. package/dist/{insights-ZKTREJVG.js → insights-UQ234W6T.js} +4 -4
  110. package/dist/intelligence-service-S3GTOTGQ.js +15 -0
  111. package/dist/{journeys-T65PNRFS.js → journeys-2EZIRL7K.js} +4 -4
  112. package/dist/{keys-U54Y36FC.js → keys-NIAANGXE.js} +4 -4
  113. package/dist/{keyword-JHQKINGN.js → keyword-LHHNG3GL.js} +4 -4
  114. package/dist/{logs-6RH3NGMN.js → logs-UFOOIKTC.js} +4 -4
  115. package/dist/{mcp-JVJUVT3I.js → mcp-AZYUFL5V.js} +5 -5
  116. package/dist/mcp.js +11 -11
  117. package/dist/{measurement-plan-MOBOCU7X.js → measurement-plan-H2HIHJ3D.js} +6 -6
  118. package/dist/{notify-M3YPFBKX.js → notify-TIE2ZJ26.js} +4 -4
  119. package/dist/{organic-evidence-VDSGYYEB.js → organic-evidence-BX5MGZTK.js} +4 -4
  120. package/dist/{overview-FAJ5KKSI.js → overview-MGQE43GU.js} +7 -7
  121. package/dist/{project-3X4JNUQ2.js → project-2JL4ZW52.js} +4 -4
  122. package/dist/{project-setup-CMIASV25.js → project-setup-CXOVBRLZ.js} +4 -4
  123. package/dist/{query-NLTDZVPT.js → query-Q5BF63QF.js} +4 -4
  124. package/dist/{research-DATD7M5T.js → research-RQBZ57W5.js} +4 -4
  125. package/dist/{results-export-ONHLJT35.js → results-export-TVCBJNJN.js} +4 -4
  126. package/dist/{run-ZZ65W4T2.js → run-L6WG5WP2.js} +6 -6
  127. package/dist/{schedule-L6NQQWZP.js → schedule-3HQMG3AM.js} +4 -4
  128. package/dist/{search-JBV4A3JB.js → search-ZLQE4J66.js} +4 -4
  129. package/dist/{serve-JTVUXC5V.js → serve-VV4SVEJW.js} +34 -32
  130. package/dist/{session-L5ZT52AV.js → session-IJLUYO4T.js} +15 -15
  131. package/dist/{settings-N3HNIFMB.js → settings-T3U7TQOF.js} +4 -4
  132. package/dist/{sitemaps-HQV366MP.js → sitemaps-UZPLGN4W.js} +4 -4
  133. package/dist/{skills-6MCHPZAQ.js → skills-P4WSSFPF.js} +3 -3
  134. package/dist/{snapshot-SJKZGC7B.js → snapshot-ROJPISJE.js} +4 -4
  135. package/dist/{src-BUUBDKML.js → src-ZYWTGILQ.js} +2 -2
  136. package/dist/{status-T3LFFLRY.js → status-43XNR3NS.js} +6 -6
  137. package/dist/{support-BIPNOY7V.js → support-I7E4I3GG.js} +2 -2
  138. package/dist/{technical-aeo-APUKKLVK.js → technical-aeo-D4F2R6M3.js} +4 -4
  139. package/dist/{telemetry-RGSGE6ED.js → telemetry-5DMVDDZI.js} +5 -5
  140. package/dist/{tools-LPL4IECG.js → tools-M534GJMS.js} +12 -12
  141. package/dist/{traffic-SU7KRKO3.js → traffic-R2UA27AZ.js} +6 -6
  142. package/dist/{trends-3NJBRFXS.js → trends-BXOZIWIE.js} +4 -4
  143. package/dist/{users-SU4AONBT.js → users-X6WJV7VJ.js} +4 -4
  144. package/dist/{visibility-stats-EQEBABZR.js → visibility-stats-MCNUXUCL.js} +5 -5
  145. package/dist/{wordpress-SNOM6ETD.js → wordpress-AMGUJUZX.js} +4 -4
  146. package/package.json +1 -1
  147. package/assets/assets/MeasurementPropertyPage-CP9p7C6B.js +0 -4
  148. package/assets/assets/ProjectPage-Dq1mGFwA.js +0 -15
  149. package/assets/assets/index-rQgaFhmc.js +0 -43
  150. package/assets/assets/react-query-CEsVk5jq.js +0 -1
  151. package/assets/assets/service-DNaYUxv9.js +0 -1
  152. package/dist/activity-D5YDZLCK.js +0 -13
  153. package/dist/cli-commands-X4XPZQZH.js +0 -18
  154. package/dist/intelligence-service-LNXDWZ3F.js +0 -15
@@ -1,15 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./react-sigma_core.esm.min-DHJ5hJS1.js","./rolldown-runtime-XKyaHtl9.js","./vendor-lucide-C3F7vHjd.js"])))=>i.map(i=>d[i]);
2
- import{n as e,r as t,t as n}from"./rolldown-runtime-XKyaHtl9.js";import{$ as r,A as i,B as a,C as o,F as s,I as c,J as l,N as u,Q as d,T as f,V as p,X as m,Z as h,a as g,b as _,c as v,ct as y,g as b,h as x,i as S,it as C,lt as w,n as T,ot as E,p as D,s as O,t as k,v as A,w as j,z as M}from"./vendor-lucide-C3F7vHjd.js";import{a as N,i as P,o as F,r as I,s as ee,t as L}from"./vendor-radix-CXYx3LLU.js";import{r as R}from"./vendor-markdown-DMxglFrF.js";import{O as z,T as te,_ as ne,d as B,f as V,p as H,r as re,u as U,v as ie,x as W}from"./vendor-tanstack-ZnWhYpCU.js";import{a as ae,c as oe,d as se,f as ce,h as le,i as ue,l as de,m as fe,n as pe,o as me,p as he,r as ge,s as _e,t as ve,u as ye}from"./vendor-recharts-DAGVAt0P.js";import{$c as be,$o as xe,$s as Se,$t as Ce,At as we,B as Te,Bc as Ee,Bo as De,Co as Oe,Ct as G,Dc as ke,Ec as Ae,Et as je,Fc as Me,Ft as Ne,Go as Pe,Gs as Fe,Gt as Ie,H as Le,Hc as Re,Hn as ze,Ho as Be,Hs as Ve,I as He,Ja as Ue,Jc as We,Jo as Ge,Js as Ke,Jt as qe,Kc as Je,Ko as Ye,Ks as Xe,Kt as Ze,Lc as Qe,Ln as $e,Lo as et,Mo as tt,Nc as nt,Nt as rt,Oc as it,P as at,Pc as ot,Qc as st,Qo as ct,Qs as lt,Qt as ut,R as dt,Ro as ft,Rs as pt,Rt as mt,Sc as ht,Sn as gt,So as _t,St as vt,Tc as yt,To as bt,Uc as xt,Uo as St,Us as Ct,Ut as wt,V as Tt,Vc as Et,Vn as Dt,Vo as Ot,Wn as kt,Wo as At,Ws as jt,Wt as Mt,Xo as Nt,Xs as Pt,Y as Ft,Ya as It,Yc as Lt,Yo as Rt,Ys as zt,Z as Bt,Zc as Vt,Zo as Ht,Zs as Ut,Zt as Wt,_ as Gt,_c as Kt,_o as qt,_s as Jt,_t as Yt,a as Xt,as as Zt,bc as Qt,bn as $t,bo as en,bs as tn,c as nn,cc as rn,cl as an,d as on,dc as sn,ds as cn,dt as ln,ec as un,el as dn,en as fn,es as pn,fs as mn,g as hn,go as gn,gs as _n,gt as vn,h as yn,hs as bn,ic as xn,jn as Sn,jo as Cn,jt as K,kt as wn,l as Tn,lc as En,lo as Dn,ls as On,lt as kn,m as An,mc as jn,mn as Mn,ms as Nn,nl as Pn,nn as Fn,ns as In,o as Ln,oc as Rn,ol as zn,os as Bn,p as Vn,ps as Hn,pt as Un,q as Wn,qo as Gn,qs as Kn,qt as qn,r as q,rc as Jn,rs as Yn,s as Xn,sc as Zn,sl as Qn,ss as $n,t as J,tl as er,ts as tr,tt as nr,u as rr,uc as ir,us as ar,ut as or,vn as sr,vo as cr,vs as lr,vt as ur,w as dr,wc as fr,wo as pr,wt as mr,xc as hr,xn as gr,xo as _r,xs as vr,xt as Y,yn as yr,yo as br,ys as xr,zc as Sr,zo as Cr}from"./ToneBadge-CxostV9z.js";import{t as wr}from"./preload-helper-DN5snQJ-.js";import{B as Tr,C as Er,D as Dr,F as Or,I as kr,L as Ar,M as jr,N as Mr,O as Nr,P as Pr,R as Fr,S as Ir,T as Lr,_ as Rr,a as zr,b as Br,c as Vr,d as Hr,f as Ur,g as Wr,h as Gr,i as Kr,j as qr,k as Jr,l as Yr,m as Xr,n as Zr,o as Qr,p as $r,r as ei,s as ti,t as ni,u as ri,x as ii,y as ai,z as oi}from"./ChartPrimitives-De8aCfZp.js";import{r as si}from"./account-context-Mya_uodz.js";import{t as ci}from"./async-handler-Bj3TnIRw.js";import{d as li,l as ui,n as di,o as fi,s as pi,t as mi,u as hi}from"./query-client-2aOrFPOz.js";import{$ as gi,$t as _i,A as vi,An as yi,At as bi,B as xi,Bn as Si,Bt as Ci,C as wi,Ct as Ti,D as Ei,Dt as Di,E as Oi,En as ki,F as Ai,Fn as ji,Ft as Mi,G as Ni,Gn as Pi,Gt as Fi,H as Ii,Hn as Li,Ht as Ri,I as zi,In as Bi,It as Vi,J as Hi,Jn as Ui,Jt as Wi,K as Gi,Kn as Ki,Kt as qi,L as Ji,Ln as Yi,M as Xi,Mn as Zi,N as Qi,Nn as $i,Nt as ea,O as ta,P as na,Pn as ra,Pt as ia,Q as aa,Qt as oa,R as sa,Rn as ca,Rt as la,S as ua,St as da,T as fa,Tn as pa,U as ma,V as ha,Vn as ga,Vt as _a,W as va,Wn as ya,X as ba,Xt as xa,Y as Sa,Yt as Ca,Z as wa,Zt as Ta,_ as Ea,_t as Da,an as Oa,at as ka,b as Aa,bn as ja,c as Ma,ct as Na,d as Pa,dn as Fa,dt as Ia,en as La,et as Ra,f as za,fn as Ba,ft as Va,g as Ha,gt as Ua,h as Wa,ht as Ga,in as Ka,it as qa,j as Ja,jn as Ya,jt as Xa,k as Za,kn as Qa,lt as $a,m as eo,mt as to,n as no,nn as ro,nt as io,on as ao,ot as oo,p as so,pn as co,pt as lo,q as uo,qn as fo,qt as po,r as mo,rn as ho,rt as go,sn as _o,st as vo,t as yo,tn as bo,tt as xo,un as So,ut as Co,v as wo,vn as To,vt as Eo,w as Do,wt as Oo,x as ko,xt as Ao,y as jo,yn as Mo,yt as No,z as Po,zn as Fo,zt as Io}from"./react-query-CEsVk5jq.js";import{A as Lo,B as Ro,C as zo,D as Bo,E as Vo,F as Ho,I as Uo,L as Wo,M as Go,N as Ko,O as qo,P as Jo,R as Yo,S as Xo,T as Zo,V as Qo,_ as $o,a as es,b as ts,c as ns,d as rs,f as is,g as as,h as os,i as ss,j as cs,k as ls,l as us,m as ds,n as fs,o as ps,p as ms,r as hs,s as gs,u as _s,v as vs,w as ys,x as bs,y as xs,z as Ss}from"./AccessControls-ogV5Gz4X.js";import{t as X}from"./InfoTooltip-Dm4gYO4N.js";import{t as Cs}from"./card-B20lVlLX.js";import{n as ws,t as Ts}from"./extract-error-message-C1RkZ7dQ.js";import{$ as Es,A as Ds,At as Os,B as ks,C as As,Ct as js,D as Ms,Dt as Ns,E as Ps,Et as Fs,F as Is,G as Ls,H as Rs,I as zs,J as Bs,K as Vs,L as Hs,N as Us,O as Ws,Ot as Gs,P as Ks,Q as qs,R as Js,S as Ys,St as Xs,T as Zs,Tt as Qs,U as $s,V as ec,W as tc,X as nc,Y as rc,Z as ic,_ as ac,_t as oc,a as sc,at as cc,b as lc,d as uc,dt as dc,et as fc,f as pc,ft as mc,g as hc,h as gc,ht as _c,i as vc,it as yc,jt as bc,k as xc,kt as Sc,lt as Cc,m as wc,nt as Tc,o as Ec,p as Dc,pt as Oc,q as kc,r as Ac,s as jc,st as Mc,t as Nc,u as Pc,ut as Fc,vt as Ic,w as Lc,wt as Rc,x as zc,xt as Bc,yt as Vc,z as Hc}from"./index-rQgaFhmc.js";import{t as Uc}from"./Hint-Drf3KqdJ.js";import{t as Wc}from"./AuditHistoryPanel-DyXqEWpq.js";import{a as Gc,i as Kc,l as qc,n as Jc,o as Yc,r as Xc,t as Zc,u as Qc}from"./service-DNaYUxv9.js";import{a as $c,c as el,s as tl,t as nl}from"./server-traffic-Cx7fQ2OF.js";import{i as rl,n as il,r as al}from"./agent-trust-copy-DjdjfF7q.js";import{t as ol}from"./ServerTrafficSection-xzcv0S85.js";function sl(e){return e.split(/[?#]/)[0]||`/`}var cl=1e6;function ll(e,t=`USD`,n={}){let r=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:t,...n.fractionDigits===void 0?{}:{minimumFractionDigits:n.fractionDigits,maximumFractionDigits:n.fractionDigits}}),i=r.format(e/cl);if(n.showTinyAsLessThan&&e>0&&i===r.format(0)){let e=10**-(r.resolvedOptions().maximumFractionDigits??0);return`<${r.format(e)}`}return i}var Z=t(w(),1),ul={projectWide:`Project-wide`,projectWideHelp:`This tab covers the whole project. Your measurement scope stays selected for AI Visibility and Queries.`,savedScopeUnavailable:`Saved scope unavailable`};function dl(e,t){return e!==`viewer`||t!==null}function fl(e,t){return e===`research`&&!t?`tracked`:e}function pl(e,t){return t.measurementScope===`project`?!1:!t.measurementScopeKey||!(t.measurementScope===`group`?e.groups:t.measurementScope===`property`?e.targets:e.markets).some(e=>e.stableKey===t.measurementScopeKey)}function ml(e,t){return e.find(e=>e.kind===t.measurementScope&&(e.kind===`project`||e.id===t.measurementScopeKey))}function hl(e){return e.measurementScope!==`project`||e.marketKey!==void 0}function gl(e){if(e.embedded)return{kind:`none`};let{tab:t}=e;switch(t){case`overview`:return e.surface===`advanced-overview`?{kind:`report-picker`}:{kind:`none`};case`queries`:case`discovery`:{let{tracking:t}=e;return e.queryWorkspace!==`tracked`||t.state!==`ready`||t.mode!==`advanced`?{kind:`none`}:t.scopeUnavailable?{kind:`scope-unavailable`}:{kind:`tracking-picker`}}case`search-console`:case`activity`:case`traffic`:case`agent-readiness`:case`conversions`:case`local`:case`backlinks`:case`history`:return e.scoped&&e.surface===`advanced-overview`?{kind:`project-wide`}:{kind:`none`};case`client-queries`:case`settings`:case`portfolio`:case`seo-data`:case`journeys`:return{kind:`none`};default:return t}}var Q=R();function _l({state:e,label:t,className:n}){return(0,Q.jsx)(J,{tone:Vc(e),className:n,children:t??(e===`not-measured`?Ar.label:kr(e))})}function vl({id:e,label:t,options:n,value:r,onChange:i,className:a,tabClassName:o,activeTabClassName:s,inactiveTabClassName:c=``}){function l(e){let t=n.findIndex(([e])=>e===r),a;switch(e.key){case`ArrowRight`:a=(t+1)%n.length;break;case`ArrowLeft`:a=(t-1+n.length)%n.length;break;case`Home`:a=0;break;case`End`:a=n.length-1;break;default:return}e.preventDefault(),i(n[a][0]),e.currentTarget.querySelectorAll(`[role="tab"]`)[a].focus()}return(0,Q.jsx)(`div`,{role:`tablist`,"aria-label":t,className:a,onKeyDown:l,children:n.map(([t,n])=>(0,Q.jsx)(`button`,{id:`${e}-${t}`,type:`button`,role:`tab`,"aria-selected":r===t,"aria-controls":`${e}-panel`,tabIndex:r===t?0:-1,className:`${o} ${r===t?s:c}`,onClick:()=>i(t),children:n},t))})}var yl=[{value:`non-brand`,label:`Non-brand`},{value:`branded`,label:`Branded`}],bl={"non-brand":`Non-brand`,branded:`Branded`,pooled:`All queries`},xl={"non-brand":`On queries that do not contain your name: of the brand names written into the answer text, the share that were yours. Branded queries are scored separately because you are named on nearly all of them and a competitor cannot be.`,branded:`On queries that contain your name: of the brand names written into the answer text, the share that were yours. This is recognition, not competitive placement, and it is never pooled with the non-brand figure.`,pooled:`This project has no brand name or domain to match on, so branded and non-brand queries could not be separated. This figure pools both and is not a competitive read. Set a display name or aliases to split them.`},Sl=`Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.`;function Cl(e,t){return t.unavailable?{headline:`No data`,numeric:!1,detail:`could not load, refresh to retry`,showRows:!1}:t.noRun?{headline:`No data`,numeric:!1,detail:`no check has run yet`,showRows:!1}:e.snapshotsTotal===0?t.otherClassHasData?{headline:`No non-brand queries`,numeric:!1,detail:`every tracked query names your brand`,showRows:!1}:{headline:`No queries`,numeric:!1,detail:`none tracked`,showRows:!1}:e.snapshotsWithAnswerText===0?{headline:`No answers`,numeric:!1,detail:`no answer text in this run`,showRows:!1}:t.hasCompetitors?e.combinedMentionSnapshots===0||e.score===null?{headline:`No mentions`,numeric:!1,detail:`no brand named in ${e.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:Ut(e.score,Je.percent),numeric:!0,detail:`${e.projectMentionSnapshots} of ${e.combinedMentionSnapshots} brand mentions`,showRows:!0}:{headline:`No comparison`,numeric:!1,detail:`you were named in ${e.projectMentionSnapshots} of ${e.snapshotsWithAnswerText} answers`,showRows:!1}}function wl({breakdown:e,projectLabel:t}){if(e.ranking.length===0)return null;let n=e.ranking.map(e=>({label:e.kind===`project`?`${t} (you)`:e.domain??``,mentions:e.mentionSnapshots,share:e.share,isYou:e.kind===`project`}));return(0,Q.jsxs)(`table`,{className:`mention-share-table`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Brand mentions by domain, most mentioned first`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`mention-share-row mention-share-row-head`,children:[(0,Q.jsx)(`th`,{scope:`col`,className:`mention-share-row-label`,children:`Domain`}),(0,Q.jsx)(`th`,{"aria-hidden":`true`}),(0,Q.jsxs)(`th`,{scope:`col`,className:`mention-share-count`,children:[`Mentions`,(0,Q.jsx)(X,{text:Sl})]}),(0,Q.jsx)(`th`,{scope:`col`,className:`mention-share-share`,children:`Share`})]})}),(0,Q.jsx)(`tbody`,{className:`mention-share-rows`,children:n.map(e=>(0,Q.jsxs)(`tr`,{className:`mention-share-row`,children:[(0,Q.jsx)(`th`,{scope:`row`,className:`mention-share-row-label ${e.isYou?`text-heading text-label-14-strong`:`text-secondary`}`,children:e.label}),(0,Q.jsx)(`td`,{"aria-hidden":`true`,children:(0,Q.jsx)(`div`,{className:`mention-share-bar`,children:(0,Q.jsx)(`div`,{className:`mention-share-bar-fill ${e.isYou?`bg-positive-500/70`:`bg-mono-500/60`}`,style:{width:`${e.share>0?Math.max(e.share*100,1.5):0}%`}})})}),(0,Q.jsx)(`td`,{className:`mention-share-count`,children:e.mentions}),(0,Q.jsx)(`td`,{className:`mention-share-share`,children:Ut(e.share)})]},e.label))})]})}function Tl({summary:e,projectLabel:t,competitorDomains:n}){let[r,i]=(0,Z.useState)(`non-brand`),a=(0,Z.useId)(),o=e.scope===`pooled`,s=!o&&e.branded.snapshotsTotal>0,c=s?r:`non-brand`,l=o?`pooled`:c,u=c===`branded`?e.branded:e.breakdown,d=c===`branded`?e.breakdown:e.branded,f=Cl(u,{hasCompetitors:n.length>0,unavailable:e.unavailable===!0,noRun:e.breakdown.snapshotsTotal===0&&e.branded.snapshotsTotal===0,otherClassHasData:d.snapshotsTotal>0}),p=Pr(f.headline),m=l===`non-brand`?oc[e.tone]:`text-secondary`;function h(e){let t=yl.findIndex(e=>e.value===c),n=null;e.key===`ArrowRight`||e.key===`ArrowDown`?n=(t+1)%yl.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?n=(t-1+yl.length)%yl.length:e.key===`Home`?n=0:e.key===`End`&&(n=yl.length-1),n!==null&&(e.preventDefault(),i(yl[n].value),e.currentTarget.querySelectorAll(`[role="radio"]`)[n]?.focus())}return(0,Q.jsxs)(`div`,{className:`mention-share`,children:[(0,Q.jsxs)(`div`,{className:`mention-share-head`,children:[(0,Q.jsxs)(`div`,{className:`mention-share-label`,children:[(0,Q.jsx)(`h3`,{id:a,className:`mention-share-label-text`,children:`Mention share`}),(0,Q.jsx)(X,{text:xl[l]})]}),s?(0,Q.jsx)(`div`,{role:`radiogroup`,"aria-labelledby":a,className:`segmented flex-wrap`,onKeyDown:h,children:yl.map(e=>{let t=e.value===c;return(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":t,tabIndex:t?0:-1,onClick:()=>i(e.value),className:`segmented-option min-h-11 ${t?`segmented-option-active`:``}`,children:e.label},e.value)})}):(0,Q.jsx)(`span`,{className:`mention-share-class`,children:bl[l]})]}),f.numeric?(0,Q.jsxs)(`p`,{className:`mention-share-value ${m}`,children:[p.figure,p.sign?(0,Q.jsx)(`span`,{className:`text-faint`,children:p.sign}):null]}):(0,Q.jsx)(`p`,{className:`mention-share-value-text`,children:f.headline}),(0,Q.jsxs)(`p`,{className:`mention-share-caption`,children:[(0,Q.jsx)(`span`,{className:`mention-share-caption-scope`,children:bl[l]}),` · ${f.detail}`]}),o&&(0,Q.jsx)(`p`,{className:`mention-share-note`,children:`Set a brand name to split branded from non-brand.`}),f.showRows&&(0,Q.jsx)(wl,{breakdown:u,projectLabel:t})]})}function El({items:e,label:t=`Details`}){return e.length===0?null:(0,Q.jsxs)(`details`,{className:`av-details`,children:[(0,Q.jsx)(`summary`,{children:t}),(0,Q.jsx)(`ul`,{className:`av-details-list`,children:e.map((e,t)=>(0,Q.jsx)(`li`,{children:e},t))})]})}var Dl=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],Ol={"7d":`last 7 days`,"30d":`last 30 days`,"90d":`last 90 days`,all:`all checks`},kl={"non-brand":`Non-brand`,branded:`Branded`,all:`All queries`},Al={"non-brand":`Counts queries that do not name your brand.`,branded:`Counts queries that name your brand.`,all:`Counts every tracked query, so mention share is not shown.`},jl={"select-query-class":`no query type selected`,"answer-selection":`answers selected by the brands they named`,"no-competitors":`no competitors configured`,"insufficient-observed":`needs 3 observed competitors, each named in 3 or more answers`,"no-answers":`no answer text`,"no-mentions":`no brands named`,unavailable:`competitor data unavailable`},Ml=`Mention share: your share of the brand mentions in these answers, each brand counted at most once per answer. Named: answers that name the brand. Cited: answers whose sources link to its site. Company names in answers are observations. Only competitor sites count toward mention share.`,Nl=100;function Pl(e){return e?e.evidence.answeredResults>0||e.evidence.sourceResults>0?`measured`:`not-measured`:`unavailable`}function Fl(e){return e===`unavailable`?`Unavailable`:`Not measured`}function Il(e){switch(e){case`own`:return`Your domain`;case`direct-competitor`:return`Competitor`;case`ota-aggregator`:return`Aggregator`;case`editorial-media`:return`Editorial`;case`other`:return`Other`;default:return`Unclassified`}}function Ll(e,t,n){return e===1?t:n}function Rl(e){let t=e.label.trim(),n=We(e.domain);return t&&t.toLowerCase()!==e.domain.toLowerCase()&&t.toLowerCase()!==n.toLowerCase()?t:null}function zl({row:e,aliases:t=[],autoAliases:n=[]}){let r=Rl(e),i=[...t.map(e=>({alias:e,auto:!1})),...n.map(e=>({alias:e,auto:!0}))],a=i.length>0?(0,Q.jsxs)(`span`,{className:`av-of block`,children:[`Also named`,` `,i.map(({alias:e,auto:t},n)=>(0,Q.jsxs)(`span`,{children:[n>0?`, `:``,e,t?(0,Q.jsx)(`span`,{className:`av-alias-auto`,title:`Detected automatically from this project's stored answers`,children:` (auto)`}):null]},`${t?`auto`:`curated`}:${e}`))]}):null;return r?(0,Q.jsxs)(Q.Fragment,{children:[r,` `,(0,Q.jsx)(`span`,{className:`av-of`,children:e.domain}),a]}):(0,Q.jsxs)(Q.Fragment,{children:[e.domain,a]})}function Bl(e){let t=Rl(e);return t?`${t} (${e.domain})`:e.domain}function Vl(e,t){return t&&e>=Nl?(0,Q.jsxs)(Q.Fragment,{children:[`top `,(0,Q.jsx)(`strong`,{children:e})]}):(0,Q.jsx)(`strong`,{children:e})}function Hl({action:e,domain:t,mutation:n}){let[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(null);async function s(){if(!r){i(!0),o(null);try{await n(t)===!1&&o(`Could not ${e} competitor. Try again.`)}catch{o(`Could not ${e} competitor. Try again.`)}finally{i(!1)}}}return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:r,onClick:()=>{s()},children:[e===`pin`?`Pin`:`Unpin`,` `,(0,Q.jsx)(`span`,{className:`sr-only`,children:t})]}),a?(0,Q.jsx)(`span`,{role:`alert`,className:`sr-only`,children:a}):null]})}function Ul({urls:e}){return(0,Q.jsxs)(`details`,{className:`inline-disclosure text-left text-label-12 text-secondary`,children:[(0,Q.jsx)(`summary`,{children:`Source URLs`}),(0,Q.jsx)(`ul`,{className:`mt-2 max-w-72 space-y-1 text-label-12-mono`,children:e.map(e=>(0,Q.jsx)(`li`,{className:`break-all`,children:e},e))})]})}function Wl({count:e,of:t,state:n,toneClass:r}){return n===`measured`?(0,Q.jsxs)(`span`,{className:`whitespace-nowrap`,children:[(0,Q.jsx)(`span`,{className:`av-n-sm ${r}`,children:e}),` `,(0,Q.jsxs)(`span`,{className:`av-of`,children:[`of `,t]})]}):(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:Fl(n)})}function Gl({percent:e,state:t,toneClass:n}){if(t!==`measured`||e===null)return(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:t===`measured`?`Not measured`:Fl(t)});let{figure:r,sign:i}=Pr(Ut(e,Je.percent));return(0,Q.jsxs)(`span`,{className:`av-n-sm ${n}`,children:[r,i?(0,Q.jsx)(`span`,{className:`text-faint`,children:i}):null]})}function Kl({rows:e,state:t,named:n,cited:r,onPin:i}){return(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`av-grid av-grid-dense`,"aria-label":`Other competitors seen`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Competitor`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Type`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Named`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Cited`}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,className:`av-row-label`,children:(0,Q.jsx)(zl,{row:e})}),(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:Il(e.surfaceClass)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Wl,{count:e.mentionCount,of:n,state:t,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Wl,{count:e.citationCount,of:r,state:t,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`flex min-w-max items-start gap-2`,children:[t===`measured`&&e.sampleUrls.length>0?(0,Q.jsx)(Ul,{urls:e.sampleUrls}):null,i?(0,Q.jsx)(Hl,{action:`pin`,domain:e.domain,mutation:i}):null]})})]},e.domain))})]})})}function ql({onAddCompetitor:e}){let t=(0,Z.useId)(),[n,r]=(0,Z.useState)(``),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(null);async function c(){let t=n.trim();if(t&&!i){a(!0),s(null);try{if(await e(t)===!1){s(`Could not add competitor. Try again.`);return}r(``)}catch{s(`Could not add competitor. Try again.`)}finally{a(!1)}}}return(0,Q.jsxs)(`details`,{className:`inline-disclosure`,children:[(0,Q.jsx)(`summary`,{children:`Manage competitors`}),(0,Q.jsxs)(`form`,{className:`mt-3 flex flex-wrap items-end gap-2`,onSubmit:e=>{e.preventDefault(),c()},"aria-busy":i,children:[(0,Q.jsxs)(`label`,{htmlFor:t,className:`min-w-56 flex-1 text-label-14-strong text-heading`,children:[`Competitor domain`,(0,Q.jsx)(`input`,{id:t,type:`text`,value:n,onChange:e=>r(e.target.value),placeholder:`competitor.com`,className:`mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-label-14 text-primary placeholder-mono-400 focus:outline-none focus:ring-2 focus:ring-mono-400`})]}),(0,Q.jsx)(q,{type:`submit`,size:`sm`,className:`min-h-10`,disabled:i||!n.trim(),children:i?`Adding…`:`Add competitor`}),o?(0,Q.jsx)(`p`,{role:`alert`,className:`w-full text-copy-14 text-negative`,children:o}):null]})]})}function Jl({window:e,landscape:t,pinnedFallback:n=[],competitorAliases:r={},competitorAutoAliases:i={},canWrite:a,isEmbed:o,onWindowChange:s,onPin:c,onUnpin:l,onAddCompetitor:u,error:d,onRetry:f,isLoading:p=!1,scopeLabel:m,advancedPortfolio:h=!1}){let g=(0,Z.useId)(),_=a&&!o,v=t?.pinned??n,y=t?.observed??[],b=t?.otherSources??[],x=t?.evidence,S=Pl(t),C=t?.basis===`observed`,w=C?y.filter(e=>e.shareOfVoice!==null):v,T=C?y.filter(e=>e.shareOfVoice===null):y,E=t?.filters.queryClass,D=t?.marketState?.draft?.pendingCompetitorDomains.length??0,O=t?.truncated===!0,k=x?.answeredResults??0,A=x?x.answeredResults+x.missingAnswerTextResults:0,j=E===`non-brand`&&t?.project.shareOfVoice!=null?oc[Ic(t.project.shareOfVoice)]:`text-primary`,M=e=>_?e.pinned?l?(0,Q.jsx)(Hl,{action:`unpin`,domain:e.domain,mutation:l}):null:c?(0,Q.jsx)(Hl,{action:`pin`,domain:e.domain,mutation:c}):null:null,N=w.some(e=>M(e)!==null),P=[m,E?kl[E]:null,Ol[e],t?.basis?C?`observed competitors only`:`tracked competitors only`:null].filter(Boolean).join(` · `),F=[];if(t&&!C&&w.length===0&&F.push({key:`no-pins`,text:`No pinned competitors.`}),t?.reason&&F.push({key:`reason`,text:`Mention share: ${jl[t.reason]}`}),t&&T.length>0){let e=T.length;F.push({key:`others`,text:O&&e>=Nl?`${Nl} or more other competitors seen`:`${e} other ${Ll(e,`competitor`,`competitors`)} seen`})}D>0&&F.push({key:`pending`,text:`${t?.scope.kind===`all-markets`?`Pending publication across markets`:`Pending publication`}: ${D} ${Ll(D,`competitor`,`competitors`)}`});let I=[x&&x.missingAnswerTextResults>0?`Answer data incomplete`:null,x&&x.incompleteSourceResults>0?`Citation data incomplete`:null].filter(Boolean);I.length>0&&F.push({key:`incomplete`,text:I.join(` · `),className:oc.caution});let ee=[];if(t&&x){ee.push(t.runCount===void 0?(0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:x.answeredResults}),` `,Ll(x.answeredResults,`answer`,`answers`)]}):(0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:t.runCount}),` `,Ll(t.runCount,`check`,`checks`),`, `,(0,Q.jsx)(`strong`,{children:x.answeredResults}),` `,Ll(x.answeredResults,`answer`,`answers`)]})),!t.reason&&S===`measured`&&t.project.shareOfVoice!==null&&ee.push((0,Q.jsxs)(Q.Fragment,{children:[`Mention share: you `,(0,Q.jsx)(`strong`,{children:t.project.mentionCount}),w.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[`, `,e.domain,` `,(0,Q.jsx)(`strong`,{children:e.mentionCount})]},e.domain)),` `,`of `,(0,Q.jsx)(`strong`,{children:x.mentionCredits}),` `,C?`brand mentions`:`tracked-brand mentions`]})),ee.push((0,Q.jsxs)(Q.Fragment,{children:[`Answers with source links: `,(0,Q.jsx)(`strong`,{children:x.sourceResults})]})),T.length===0&&ee.push(`Other competitors seen: none`),x.missingAnswerTextResults>0&&ee.push((0,Q.jsxs)(Q.Fragment,{children:[`No answer text: `,(0,Q.jsx)(`strong`,{children:x.missingAnswerTextResults}),` `,Ll(x.missingAnswerTextResults,`answer`,`answers`),`, left out of mention share`]})),x.incompleteSourceResults>0&&ee.push((0,Q.jsxs)(Q.Fragment,{children:[`Incomplete source lists: `,(0,Q.jsx)(`strong`,{children:x.incompleteSourceResults}),` `,Ll(x.incompleteSourceResults,`answer`,`answers`),`, not counted as misses`]}));let e=x.excludedProbeResults+x.excludedNonCompletedResults;e>0&&ee.push((0,Q.jsxs)(Q.Fragment,{children:[`Left out: `,(0,Q.jsx)(`strong`,{children:e}),` `,Ll(e,`answer`,`answers`),` from spot checks or unfinished checks`]}))}let L=[...t?[{name:`You`,row:t.project}]:[],...w.map(e=>({name:e.domain,row:e}))].filter(e=>e.row.sampleUrls.length>0);S===`measured`&&L.length>0&&ee.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsx)(`summary`,{children:`Sample pages cited`}),(0,Q.jsx)(`div`,{className:`av-subdetails-body`,children:L.map(({name:e,row:t})=>(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{children:e}),(0,Q.jsx)(`ul`,{className:`space-y-1 text-label-12-mono text-muted`,children:t.sampleUrls.map(e=>(0,Q.jsx)(`li`,{className:`break-all`,children:e},e))})]},t.domain))})]})),t&&T.length>0&&ee.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Other competitors seen: `,Vl(T.length,O)]}),(0,Q.jsx)(`div`,{className:`av-subdetails-body`,children:(0,Q.jsx)(Kl,{rows:T,state:S,named:k,cited:A,onPin:_?c:void 0})})]}));let R=t?.observedNames??[];if(R.length>0){let e=t?.observedNamesTotal??R.length;ee.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Company names in answers: `,e>R.length?(0,Q.jsxs)(Q.Fragment,{children:[`top `,(0,Q.jsx)(`strong`,{children:R.length}),` of `,(0,Q.jsx)(`strong`,{children:e})]}):(0,Q.jsx)(`strong`,{children:R.length})]}),(0,Q.jsx)(`ul`,{className:`av-subdetails-body`,children:R.map(e=>(0,Q.jsxs)(`li`,{children:[e.name,` · `,e.answerCount,` `,Ll(e.answerCount,`answer`,`answers`)]},e.name))})]}))}return b.length>0&&ee.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Other sites cited: `,Vl(b.length,O)]}),(0,Q.jsx)(`ul`,{className:`av-subdetails-body`,children:b.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`span`,{children:[Bl(e),` · `,Il(e.surfaceClass),` · `,e.citationCount,` `,Ll(e.citationCount,`citation`,`citations`)]}),e.sampleUrls.length>0?(0,Q.jsx)(`ul`,{className:`mt-1 space-y-1 text-label-12-mono text-muted`,children:e.sampleUrls.map(e=>(0,Q.jsx)(`li`,{className:`break-all`,children:e},e))}):null]},e.domain))})]})),(0,Q.jsxs)(`section`,{"aria-labelledby":g,"aria-busy":p,className:`overview-brief`,children:[(0,Q.jsxs)(`div`,{className:`av-card-head`,children:[(0,Q.jsxs)(`div`,{className:`inline-flex items-center`,children:[(0,Q.jsx)(`h2`,{id:g,className:`av-card-title`,children:`Competitors over time`}),(0,Q.jsx)(X,{text:E?`${Al[E]} ${Ml}`:Ml})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[(0,Q.jsx)(`p`,{className:`av-card-meta`,children:P}),(0,Q.jsx)(Bc,{label:`Competitors over time window`,className:`flex-wrap`,options:Dl,value:e,onChange:s})]})]}),(0,Q.jsxs)(`div`,{className:`av-card-body space-y-3`,children:[d?(0,Q.jsxs)(`div`,{role:`alert`,className:`flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-3 text-label-14 text-negative`,children:[(0,Q.jsx)(`span`,{children:d}),f?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:f,children:`Retry competitors over time`}):null]}):null,p&&!t&&v.length===0?(0,Q.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`h-24 animate-pulse rounded-md bg-surface`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Loading competitors over time`})}):t||w.length>0?(0,Q.jsxs)(`table`,{className:`av-grid av-grid-brands`,"aria-label":`Competitors over time`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Brand`})}),(0,Q.jsx)(`th`,{scope:`col`,className:`av-brand-type`,children:`Type`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Mention share`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Named`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Cited`}),N?(0,Q.jsx)(`th`,{scope:`col`,className:`av-brand-actions`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Actions`})}):null]})}),(0,Q.jsxs)(`tbody`,{children:[t?(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,className:`av-row-label`,children:t.project.label.trim()?(0,Q.jsxs)(Q.Fragment,{children:[t.project.label.trim(),` `,(0,Q.jsx)(`span`,{className:`av-of`,children:`(you)`})]}):`You`}),(0,Q.jsx)(`td`,{className:`av-brand-type text-label-13 text-secondary`,children:`Your brand`}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Gl,{percent:t.project.shareOfVoice,state:S,toneClass:j})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Wl,{count:t.project.mentionCount,of:k,state:S,toneClass:j})}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(Wl,{count:t.project.citationCount,of:A,state:S,toneClass:j}),h&&S===`measured`?(0,Q.jsx)(`span`,{className:`block text-label-13 text-secondary`,children:Mr(t.project.domain,`cited`)}):null]}),N?(0,Q.jsx)(`td`,{className:`av-brand-actions`}):null]}):null,w.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,className:`av-row-label`,children:(0,Q.jsx)(zl,{row:e,aliases:e.pinned?r[e.domain]:void 0,autoAliases:e.pinned?i[e.domain]:void 0})}),(0,Q.jsx)(`td`,{className:`av-brand-type text-label-13 text-secondary`,children:Il(e.surfaceClass)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Gl,{percent:e.shareOfVoice,state:S,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Wl,{count:e.mentionCount,of:k,state:S,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Wl,{count:e.citationCount,of:A,state:S,toneClass:`text-primary`})}),N?(0,Q.jsx)(`td`,{className:`av-brand-actions`,children:M(e)}):null]},e.domain))]})]}):null,F.length>0?(0,Q.jsx)(`div`,{className:`space-y-1 text-label-13 text-secondary`,children:F.map(e=>(0,Q.jsx)(`p`,{className:e.className,children:e.text},e.key))}):null]}),(0,Q.jsx)(El,{items:ee}),_&&u?(0,Q.jsx)(`div`,{className:`border-t border-subtle px-5 py-3`,children:(0,Q.jsx)(ql,{onAddCompetitor:u})}):null]})}function Yl(e){return e.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function Xl(e){let t=e;try{t=decodeURIComponent(e.replace(/\+/g,` `))}catch{}let n=``,r=e.indexOf(`?`);return r>=0&&new URLSearchParams(e.slice(r+1)).forEach((e,t)=>{n+=` ${t} ${e}`}),`${e} ${t}${n}`}function Zl(e,t=36,n=18){let r=[...e];return r.length<=t+n+1?e:`${r.slice(0,t).join(``)}…${r.slice(-n).join(``)}`}function Ql({value:e,headLength:t,tailLength:n,className:r,title:i}){let a=Zl(e,t,n);return(0,Q.jsx)(`span`,{className:r,title:i??e,children:a===e?e:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:e}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:a})]})})}function $l({rows:e,getSearchText:t,pageSize:n=25}){let[r,i]=(0,Z.useState)(``),[a,o]=(0,Z.useState)(1),s=(0,Z.useMemo)(()=>Yl(r),[r]),c=(0,Z.useMemo)(()=>s.length===0||!t?e:e.filter(e=>{let n=t(e).toLocaleLowerCase();return s.every(e=>n.includes(e))}),[t,e,s]),l=Math.max(1,Math.ceil(c.length/n)),u=Math.min(Math.max(1,a),l),d=(u-1)*n,f=(0,Z.useMemo)(()=>c.slice(d,d+n),[c,n,d]);return{query:r,setQuery:(0,Z.useCallback)(e=>{i(e),o(1)},[]),page:u,setPage:(0,Z.useCallback)(e=>{o(Math.max(1,e))},[]),rows:f,filteredRows:c,totalRows:c.length,totalPages:l,pageSize:n,rangeStart:c.length===0?0:d+1,rangeEnd:d+f.length,hasQuery:r.trim().length>0}}function eu({value:e,onChange:t,label:n,placeholder:r=`Filter rows`,className:i}){return(0,Q.jsxs)(`div`,{className:`relative ${i??``}`,children:[(0,Q.jsx)(x,{"aria-hidden":`true`,className:`pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted`}),(0,Q.jsx)(`input`,{type:`search`,value:e,onChange:e=>{kt(e.target.value),t(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&kt(e.currentTarget.value,!0)},"aria-label":n,placeholder:r,autoComplete:`off`,spellCheck:!1,className:`h-9 w-full rounded-md border border-default bg-surface/50 pl-9 pr-9 text-label-14 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`}),e.trim().length>0?(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(``),"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:(0,Q.jsx)(T,{"aria-hidden":`true`,className:`size-3.5`})}):null]})}function tu({page:e,pageSize:t=25,visibleRows:n,totalRows:r,hasNextPage:i,onPageChange:a,itemLabel:o=`rows`,className:s,disabled:c=!1}){if(n===0)return null;let l=(e-1)*t+1,u=l+n-1,d=r===void 0?void 0:Math.max(1,Math.ceil(r/t)),f=i??(d!==void 0&&e<d),p=e>1||f;return(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-label-12 text-secondary ${s??``}`,children:[(0,Q.jsxs)(`p`,{className:`tabular-nums`,children:[l.toLocaleString(`en-US`),` to `,u.toLocaleString(`en-US`),r===void 0?`${f?`+`:``} ${o}`:` of ${r.toLocaleString(`en-US`)} ${o}`]}),p?(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>a(e-1),disabled:c||e<=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:[(0,Q.jsx)(h,{"aria-hidden":`true`,className:`size-3.5`}),`Previous`]}),(0,Q.jsx)(`span`,{className:`tabular-nums`,children:d===void 0?`Page ${e}`:`Page ${e} of ${d}`}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>a(e+1),disabled:c||!f,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`,(0,Q.jsx)(m,{"aria-hidden":`true`,className:`size-3.5`})]})]}):null]})}function nu({history:e,maxDots:t=12,signal:n=`citations`}){let r=e.slice(-t);if(r.length===0)return(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:`No data`});let i=n===`mentions`?`Mention`:`Citation`,a=n===`mentions`?{cited:`mentioned`,"not-cited":`not mentioned`,lost:`mention lost`,emerging:`new mention`,pending:`mention pending`}:{cited:`cited`,"not-cited":`not cited`,"not-measured":Ar.timeline,lost:`citation lost`,emerging:`new citation`,pending:`citation pending`},o={cited:`bg-positive-400`,"not-cited":`bg-mono-600`,"not-measured":`border border-mono-500 bg-transparent`,lost:`bg-negative-400`,emerging:`bg-caution-400 ring-1 ring-caution-300/60`},s={cited:`rounded-full`,"not-cited":`rounded-sm`,"not-measured":`rounded-full`,lost:`rotate-45 rounded-[1px]`,emerging:`rounded-full`},c=r.length-1,l=new Date(r[0].createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),u=new Date(r[c].createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),d=`${r.length} ${r.length===1?`run`:`runs`}`,f=r.map((e,t)=>{let n=new Date(e.createdAt).toLocaleDateString();return`${t===c?`Latest run, `:``}${n}: ${a[e.citationState]??e.citationState}${e.model?`, model ${e.model.includes(`/`)?Me(e.model):e.model}`:``}`}).join(`; `);return(0,Q.jsxs)(`div`,{className:`inline-flex w-max items-center gap-2 whitespace-nowrap`,role:`img`,"aria-label":`${i} history across ${d}. ${f}`,children:[r.length>1?(0,Q.jsx)(`span`,{className:`text-label-12 text-secondary shrink-0`,"aria-hidden":`true`,children:l}):null,(0,Q.jsx)(`div`,{className:`flex shrink-0 items-center gap-[3px]`,title:d,"aria-hidden":`true`,children:r.map((e,t)=>{let n=!!(e.model&&t>0&&r[t-1]?.model&&r[t-1].model!==e.model),i=t===c;return(0,Q.jsx)(`span`,{className:`h-2.5 w-2.5 shrink-0 ${s[e.citationState]??`rounded-sm`} ${o[e.citationState]??`bg-mono-700`} ${n?`ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg`:``} ${i?`outline outline-1 outline-offset-2 outline-mono-400`:``}`,title:[a[e.citationState]??e.citationState,new Date(e.createdAt).toLocaleDateString(),e.model?`model ${e.model.includes(`/`)?Me(e.model):e.model}`:null,n?`model changed`:null,i?`latest run`:null].filter(Boolean).join(` · `)},`${e.runId}:${e.createdAt}`)})}),(0,Q.jsxs)(`span`,{className:`text-label-12 shrink-0 text-secondary`,"aria-hidden":`true`,children:[u,` `,(0,Q.jsx)(`span`,{children:`latest`})]})]})}function ru(e){let t=new Map;for(let n of e)for(let e of n.runHistory){let n=t.get(e.createdAt);n?n.states.push(e.citationState):t.set(e.createdAt,{states:[e.citationState],runId:e.runId})}return[...t.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,{states:t,runId:n}])=>({runId:n,createdAt:e,citationState:t.includes(`cited`)?`cited`:t.includes(`emerging`)?`emerging`:t.every(e=>e===`not-measured`)?`not-measured`:`not-cited`}))}function iu(e){let t=e.filter(e=>e!==`pending`);if(t.length===0)return`pending`;let n=Cn(t.map(au));return n===Kt.cited?t.includes(`cited`)?`cited`:`emerging`:n===Kt[`not-cited`]?t.includes(`lost`)?`lost`:`not-cited`:`not-measured`}function au(e){switch(e){case`cited`:case`emerging`:return Kt.cited;case`not-cited`:case`lost`:return Kt[`not-cited`];case`not-measured`:return Kt[`not-measured`]}}var ou=320;function su(e){return e===`branded`?`Branded`:e===`non-brand`?`Non-brand`:`Unclassified`}function cu(e){return e===`non-brand`?0:e===`branded`?1:2}function lu(e){let t=[];for(let n of e){let e=t.at(-1);e&&e.queryClass===n.queryClass?e.rows.push(n):t.push({queryClass:n.queryClass,rows:[n]})}return t}function uu(e){return e.phrase}function du(e,t){return t===`citations`?e.citationState:e.visibilityState===`pending`||e.answerMentioned==null&&e.visibilityState==null?`pending`:e.visibilityState===`visible`||e.answerMentioned===!0?`cited`:`not-cited`}function fu(e,t){if(t===`mentions`)switch(e){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(e){case`cited`:return`Cited`;case`not-cited`:return`Not cited`;case`not-measured`:return Ar.label;case`lost`:return`Lost`;case`emerging`:return`Emerging`;case`pending`:return`Pending`}}function pu(e,t){return e.map(e=>mu(e,t))}function mu(e,t){return t===`citations`?e:{...e,citationState:du(e,t),runHistory:e.runHistory.map(e=>({...e,citationState:du(e,t)}))}}function hu(e,t){let n=t===`mentions`?`mention`:`citation`,r=t===`mentions`?`Mention`:`Citation`;if(e.length===0)return{key:t,label:`${r} pending`,tone:`pending`};if(e.at(-1).citationState===`not-measured`)return{key:t,label:Ar.signal,tone:`neutral`};let i=e.filter(e=>e.citationState!==`not-measured`),a=i[i.length-1].citationState,o=i.length>=2?i[i.length-2].citationState:null,s=a===`cited`||a===`emerging`,c=o===`cited`||o===`emerging`;return a===`lost`||o!==null&&c&&!s?{key:t,label:`Lost ${n}`,tone:`negative`}:a===`emerging`||o!==null&&!c&&s?{key:t,label:`New ${n}`,tone:`positive`}:o===null&&s?{key:t,label:`First ${n}`,tone:`positive`}:s?{key:t,label:t===`mentions`?`Still mentioned`:`Still cited`,tone:`neutral`}:{key:t,label:`No ${n}`,tone:`neutral`}}function gu(e){let t=ru(pu(e,`mentions`)),n=ru(e);return[hu(t,`mentions`),hu(n,`citations`)]}function _u({signal:e}){let t=e.tone===`positive`?`text-positive`:e.tone===`negative`?`text-negative`:e.tone===`pending`?`text-caution`:`text-secondary`;return(0,Q.jsx)(`span`,{className:t,children:e.label})}function vu({items:e}){return(0,Q.jsx)(`div`,{className:`query-evidence-signals`,"aria-label":`Latest run mention and citation signals`,children:gu(e).map(e=>(0,Q.jsx)(_u,{signal:e},e.key))})}function yu({queryClass:e,actions:t}){return(0,Q.jsxs)(Q.Fragment,{children:[t?(0,Q.jsx)(`div`,{className:`query-evidence-toolbar`,children:(0,Q.jsxs)(`div`,{className:`query-evidence-actions`,children:[!e&&(0,Q.jsx)(Ks,{}),t]})}):null,e?(0,Q.jsx)(Is,{queryClass:e,manage:!!t}):null]})}function bu({evidence:e,compareLocations:t=!1,defaultDensity:n=`detailed`,providerSelection:r,onProviderSelectionChange:i,addedQueries:a=[],actions:o,actionPanel:s}){let{openEvidence:c}=Tc(),l=(0,Z.useId)(),[u,d]=(0,Z.useState)(new Set),f=Js(),[p,h]=(0,Z.useState)(`mentions`),[g,_]=(0,Z.useState)(n),[v,y]=(0,Z.useState)(`all`),[b,x]=(0,Z.useState)(``),S=r??b,C=e=>{x(e),i?.(e)},w=(0,Z.useMemo)(()=>[...new Set([...e.map(e=>e.provider).filter(Boolean),...S?[S]:[]])].sort(),[e,S]),T=(0,Z.useMemo)(()=>{let n=new Map;for(let r of e){if(S&&r.provider!==S)continue;let e=r.query,i=r.queryClass??null,a=t?r.location??null:null,o=JSON.stringify([e,i,a]),s=n.get(o)??{key:o,phrase:e,queryClass:i,location:a,items:[],rawItems:[]};s.items.push(mu(r,p)),s.rawItems.push(r),n.set(o,s)}return[...n.values()].sort((e,t)=>cu(e.queryClass)-cu(t.queryClass))},[e,p,t,S]),E=$l({rows:(0,Z.useMemo)(()=>T.filter(e=>v===`all`||(v===`unclassified`?e.queryClass===null:e.queryClass===v)),[T,v]),getSearchText:uu}),D=(0,Z.useMemo)(()=>{let e=new Map;for(let t of E.filteredRows){let n=e.get(t.queryClass)??new Set;n.add(t.phrase),e.set(t.queryClass,n)}return e},[E.filteredRows]),O=(0,Z.useMemo)(()=>new Set(a.map(tt)),[a]),k=f?6:5,A=E.rows.map(e=>e.key),j=A.length>0&&A.every(e=>u.has(e)),M=e=>{d(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},N=p===`mentions`?`mentioned`:`cited`,P=p===`mentions`?`Mention History`:`Citation History`,F=p===`mentions`?`mentioned`:`cited`;return(0,Q.jsxs)(`div`,{className:`query-evidence`,children:[(0,Q.jsx)(yu,{queryClass:v,actions:o}),s,(0,Q.jsxs)(`div`,{className:`query-evidence-view-row`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(`div`,{className:`query-evidence-tabs`,role:`tablist`,"aria-label":`Citation tracking view`,children:[`mentions`,`citations`].map(e=>(0,Q.jsx)(`button`,{id:`${l}-${e}`,type:`button`,role:`tab`,"aria-controls":l,"aria-selected":p===e,tabIndex:p===e?0:-1,onClick:()=>h(e),onKeyDown:t=>{if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t.key))return;t.preventDefault();let n=t.key===`Home`?`mentions`:t.key===`End`||e===`mentions`?`citations`:`mentions`;h(n),document.getElementById(`${l}-${n}`)?.focus()},children:e===`mentions`?`Mentions`:`Citations`},e))}),(0,Q.jsx)(X,{text:`Mentions track your brand or domain in answer text. Citations track your domain in source links. Each signal is measured independently.`})]}),(0,Q.jsxs)(`div`,{className:`query-evidence-display-controls`,children:[(0,Q.jsxs)(`label`,{className:`query-evidence-preview-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:g===`detailed`,onChange:e=>_(e.target.checked?`detailed`:`compact`)}),`Show answer previews`]}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:A.length===0,onClick:()=>{d(e=>{let t=new Set(e);for(let e of A)j?t.delete(e):t.add(e);return t})},children:j?`Collapse page`:`Expand page`})]})]}),e.length>0||S?(0,Q.jsxs)(`div`,{className:`query-evidence-filters`,children:[(0,Q.jsx)(eu,{value:E.query,onChange:E.setQuery,label:`Find a query`,placeholder:`Find a query`,className:`query-evidence-search`}),(0,Q.jsxs)(`label`,{className:`query-evidence-filter`,children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:`Answer engine`}),(0,Q.jsxs)(`select`,{value:S,onChange:e=>{C(e.target.value),E.setPage(1)},children:[(0,Q.jsx)(`option`,{value:``,children:`All engines`}),w.map(e=>(0,Q.jsx)(`option`,{value:e,children:Vo(e)},e))]})]}),(0,Q.jsxs)(`label`,{className:`query-evidence-filter`,children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:`Query class`}),(0,Q.jsxs)(`select`,{value:v,onChange:e=>{y(e.target.value),E.setPage(1)},children:[(0,Q.jsx)(`option`,{value:`all`,children:`All queries`}),(0,Q.jsx)(`option`,{value:`branded`,children:`Branded`}),(0,Q.jsx)(`option`,{value:`non-brand`,children:`Non-brand`}),(0,Q.jsx)(`option`,{value:`unclassified`,children:`Unclassified`})]})]})]}):null,(0,Q.jsxs)(`div`,{id:l,role:`tabpanel`,"aria-labelledby":`${l}-${p}`,children:[(0,Q.jsx)(`div`,{className:`query-evidence-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`evidence-table query-evidence-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Query`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Status`}),f&&(0,Q.jsx)(`th`,{scope:`col`,"aria-label":`Sentiment`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center`,children:[`Sentiment`,(0,Q.jsx)(X,{text:`Branded query rows show the favorable share of judged answers. Non-brand rows show only their unfavorable and mixed answers. Expanded engine rows show each stored answer’s sentiment; factual and unmentioned answers are not judgments.`})]})}),(0,Q.jsx)(`th`,{scope:`col`,children:P}),(0,Q.jsx)(`th`,{scope:`col`,children:`Latest run`}),(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Answer`})})]})}),lu(E.rows).map(e=>(0,Q.jsxs)(`tbody`,{children:[(0,Q.jsx)(`tr`,{className:`query-evidence-group`,children:(0,Q.jsxs)(`th`,{scope:`rowgroup`,colSpan:k,children:[su(e.queryClass),` (`,D.get(e.queryClass)?.size??0,`)`]})}),e.rows.map(({key:e,phrase:n,queryClass:r,location:i,items:a,rawItems:o})=>{let s=u.has(e),d=A.indexOf(e),h=`${l}-query-${d}`,_=O.has(tt(n)),v=iu(a.map(e=>e.citationState)),y=[...new Set(o.map(e=>e.queryId).filter(e=>!!e))],b=o.map(e=>e.sourceSnapshotId).filter(e=>!!e),x=ru(a),S=a.filter(e=>e.citationState===Kt.cited||e.citationState===`emerging`).length,C=p===`citations`?a.filter(e=>e.citationState===`not-measured`).length:0,w=a.length-C,T=`${S} of ${w} engines ${F}${C>0?`, ${C} not measured`:``}`;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:`query-evidence-row`,onClick:()=>M(e),children:[(0,Q.jsx)(`td`,{className:`evidence-query-cell`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`query-evidence-query`,"aria-label":n,"aria-describedby":h,"aria-expanded":s,onClick:t=>{t.stopPropagation(),M(e)},children:[(0,Q.jsx)(m,{size:16,"aria-hidden":`true`,className:s?`rotate-90`:``}),(0,Q.jsxs)(`span`,{className:`min-w-0`,children:[(0,Q.jsx)(`span`,{children:n}),(0,Q.jsxs)(`span`,{id:h,className:`query-evidence-meta`,children:[(0,Q.jsx)(`span`,{children:su(r)}),t&&(0,Q.jsx)(`span`,{children:i??`No location`})]})]})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(_l,{state:v,label:fu(v,p),className:`rounded-none border-0 bg-transparent p-0 text-label-14`}),w>0?(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary tabular-nums`,"aria-label":T,title:T,children:[S,`/`,w]}):null]})}),f&&(0,Q.jsx)(`td`,{children:(0,Q.jsx)(zs,{queryId:y.length===1?y[0]:null,sourceSnapshotIds:y.length>1?[]:b,queryClass:r,location:t?i:void 0})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(nu,{history:x,signal:p})}),(0,Q.jsx)(`td`,{className:`evidence-change-cell`,children:_?(0,Q.jsx)(`span`,{className:`query-evidence-new`,children:`new query`}):(0,Q.jsx)(vu,{items:o})}),(0,Q.jsx)(`td`,{})]}),s&&a.map((e,t)=>(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:`query-evidence-engine-row`,children:[(0,Q.jsx)(`td`,{className:`evidence-query-cell`,children:(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:e.provider?Vo(e.provider):`Awaiting engine`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(_l,{state:e.citationState,className:`rounded-none border-0 bg-transparent p-0 text-label-14`,label:fu(e.citationState,p)})}),f&&(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Us,{queryId:e.queryId,sourceSnapshotIds:e.sourceSnapshotId?[e.sourceSnapshotId]:[],queryClass:e.queryClass,provider:e.provider,location:e.location??null})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(nu,{history:e.runHistory,signal:p})}),(0,Q.jsx)(`td`,{className:`evidence-change-cell`,children:_?null:(0,Q.jsx)(vu,{items:[o[t]??e]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(q,{variant:`ghost`,className:`pointer-coarse:min-h-11`,type:`button`,title:`View ${e.provider?Vo(e.provider):`saved`} answer for ${e.query}`,onClick:t=>{t.stopPropagation(),t.currentTarget.focus({preventScroll:!0}),c(e.id)},children:`View`})})]}),g===`detailed`&&(0,Q.jsx)(`tr`,{className:`query-evidence-preview-row`,children:(0,Q.jsx)(`td`,{colSpan:k,children:(0,Q.jsx)(Cu,{item:e,mode:p,onViewFull:()=>c(e.id)},p)})})]},e.id))]},e)})]},e.queryClass??`unclassified`))]})}),E.totalRows===0&&(E.hasQuery||v!==`all`||S)?(0,Q.jsx)(`p`,{className:`supporting-copy mt-3`,children:`No tracked queries match this filter.`}):null,(0,Q.jsx)(tu,{page:E.page,pageSize:E.pageSize,visibleRows:E.rows.length,totalRows:E.totalRows,onPageChange:E.setPage,itemLabel:E.hasQuery||v!==`all`||S?`matches`:`queries`})]}),(0,Q.jsxs)(`p`,{className:`sr-only`,"aria-live":`polite`,children:[`Showing `,N===`cited`?`citations (sources)`:`mentions (answer text)`,`.`]})]})}function xu(e){let t=(e.matchedTerms??[]).filter(e=>e.trim().length>2),n=Oc(e),r=[];return t.length>0&&r.push({terms:t,className:`answer-highlight-brand`}),n.length>0&&r.push({terms:n,className:`answer-highlight-competitor`}),r}function Su(e,t){let n=t.toLowerCase().replace(/^www\./,``);return(e.citedCompetitorDomains??[]).some(e=>e.toLowerCase().replace(/^www\./,``)===n)}function Cu({item:e,mode:t,onViewFull:n}){let[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1);if(t===`mentions`)return(0,Q.jsx)(wu,{item:e,onViewFull:n});let s=e.evidenceUrls.length>0?e.evidenceUrls.map(t=>({uri:t,title:e.groundingSources.find(e=>e.uri===t)?.title})):e.groundingSources,c=e.citationState===`not-measured`;return(0,Q.jsxs)(`div`,{className:`query-evidence-preview space-y-3`,children:[(0,Q.jsx)(`p`,{className:`text-copy-13-strong text-secondary`,children:e.evidenceUrls.length>0?`Cited sources`:s.length>0?`Grounding sources`:c?`Sources`:`Cited domains`}),c&&s.length===0&&e.citedDomains.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Ar.sources}):s.length>0?(0,Q.jsx)(`ul`,{className:`space-y-4`,children:s.slice(0,a?void 0:6).map((t,n)=>(0,Q.jsxs)(`li`,{className:`min-w-0`,children:[(0,Q.jsx)(Cc,{url:t.uri,title:t.title}),Su(e,Lt(t.uri)??``)&&(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:`Competitor source`})]},`${n}-${t.uri}`))}):e.citedDomains.length>0?(0,Q.jsx)(`ul`,{className:`space-y-1 text-label-14 text-secondary`,children:e.citedDomains.slice(0,a?void 0:6).map(t=>(0,Q.jsxs)(`li`,{className:`[overflow-wrap:anywhere]`,children:[t,Su(e,t)?` · competitor source`:``]},t))}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No cited sources captured for this run.`}),(s.length>6||s.length===0&&e.citedDomains.length>6)&&(0,Q.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-expanded":a,onClick:()=>o(e=>!e),children:a?`Show fewer sources`:`View all sources`}),e.answerSnippet.trim()?(0,Q.jsxs)(`details`,{open:r,className:`border-t border-subtle pt-1`,children:[(0,Q.jsx)(`summary`,{className:`min-h-11 cursor-pointer py-3 text-label-14 text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:e=>{e.preventDefault(),i(e=>!e)},children:`Answer text`}),r&&(0,Q.jsx)(wu,{item:e,onViewFull:n,contextOnly:!0})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No answer text captured for this run.`})]})}function wu({item:e,onViewFull:t,contextOnly:n=!1}){let{matchedTerms:r,mentionedCompetitorDomains:i,mentionedCompetitorTerms:a,recommendedCompetitors:o}=e,s=(0,Z.useMemo)(()=>xu({matchedTerms:r,mentionedCompetitorDomains:i,mentionedCompetitorTerms:a,recommendedCompetitors:o}),[r,i,a,o]);if(!(e.answerSnippet.trim().length>0))return(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No answer text captured for this run.`});let c=e.answerSnippet.length>ou;return(0,Q.jsxs)(`div`,{className:`query-evidence-preview space-y-3`,children:[!n&&(0,Q.jsx)(`p`,{className:`text-copy-13-strong text-secondary`,children:`Answer text`}),(0,Q.jsx)(dc,{headingLevel:4,highlightGroups:s,previewLength:ou,children:e.answerSnippet}),(!n&&e.citedDomains.length>0||(e.mentionedCompetitorDomains?.length??0)>0)&&(0,Q.jsxs)(`dl`,{className:`space-y-2 text-label-13 text-secondary`,children:[!n&&e.citedDomains.length>0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-13-strong`,children:`Cited domains`}),(0,Q.jsxs)(`dd`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:[e.citedDomains.slice(0,6).map(t=>(0,Q.jsxs)(`span`,{className:`[overflow-wrap:anywhere]`,children:[t,Su(e,t)?` · competitor source`:``]},`c-${t}`)),e.citedDomains.length>6&&(0,Q.jsxs)(`span`,{children:[`+`,e.citedDomains.length-6,` more`]})]})]}),(e.mentionedCompetitorDomains?.length??0)>0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-13-strong`,children:`Competitors in answer`}),(0,Q.jsxs)(`dd`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:[e.mentionedCompetitorDomains.slice(0,4).map(e=>(0,Q.jsx)(`span`,{className:`[overflow-wrap:anywhere]`,children:e},`co-${e}`)),e.mentionedCompetitorDomains.length>4&&(0,Q.jsxs)(`span`,{children:[`+`,e.mentionedCompetitorDomains.length-4,` more`]})]})]})]}),c&&(0,Q.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:e=>{e.stopPropagation(),e.currentTarget.focus({preventScroll:!0}),t()},children:`View full answer`})]})}function Tu({windows:e,value:t,onChange:n,label:r,formatOption:i,disabled:a=!1}){return(0,Q.jsx)(`div`,{className:`segmented`,role:`group`,"aria-label":r,children:e.map(e=>(0,Q.jsx)(`button`,{type:`button`,"aria-pressed":t===e,disabled:a,className:`segmented-option ${t===e?`segmented-option-active`:``}`,onClick:()=>{e!==t&&ze(`window`),n(e)},children:i?i(e):e},e))})}var Eu=[``,`sm:grid-cols-1`,`sm:grid-cols-2`,`sm:grid-cols-3`],Du=[``,`lg:grid-cols-1`,`lg:grid-cols-2`,`lg:grid-cols-3`,`lg:grid-cols-4`,`lg:grid-cols-5`,`lg:grid-cols-6`],Ou=14,ku=zr[1],Au={current:`current`,previous:`previous`},ju=e=>e.series?.filter(e=>e.current!==null).length??0,Mu=e=>e.interactive??ju(e)>=2,Nu=e=>e!=null;function Pu(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Fu(e){if(!e)return``;if(e.kind===`note`)return Pu(e.text);if(e.direction===`flat`)return`no change ${e.basis}`;let t=e.tone===`better`?`, an improvement`:e.tone===`worse`?`, a decline`:``;return`${e.direction} ${e.amount} ${e.basis}${t}`}function Iu({date:e,observedAt:t}){return t?$r(Gr(t)):ri(e)}function Lu({date:e,observedAt:t}){return t?Wr(Gr(t)):Number(e.slice(0,4))}function Ru(e){return e.label??Iu(e)}function zu(e,t){if(!e)return;let n=`since ${Ru(e.basis)}`;if(e.difference===0)return{kind:`delta`,amount:t===`fraction`?`0 pts`:`0`,direction:`flat`,tone:`neutral`,basis:n};let r=Math.abs(e.difference);return{kind:`delta`,amount:t===`fraction`?`${lt(r).magnitude} pts`:r.toLocaleString(),direction:e.difference>0?`up`:`down`,tone:e.tone,basis:n}}function Bu(e){let t=new Set(e.map(e=>e.change?Ru(e.change.basis):null)),[n]=[...t];return t.size===1&&n?`since ${n}`:void 0}function Vu(e){return e.series.map(e=>({date:e.observedAt??e.date,current:e.value,...e.label?{label:e.label}:{}}))}function Hu(e,t){if(e.label&&t.label)return e.label===t.label?e.label:`${e.label} to ${t.label}`;let n=(e,t)=>t?`${Iu(e)}, ${Lu(e)}`:Iu(e);return`${n(e,Lu(e)!==Lu(t))} to ${n(t,!0)}`}function Uu({change:e,hideBasis:t}){if(!e)return null;if(e.kind===`note`)return(0,Q.jsx)(`span`,{className:`block min-h-5 text-label-13 text-secondary`,children:e.text});if(e.direction===`flat`)return(0,Q.jsxs)(`span`,{className:`block min-h-5 text-label-13 text-secondary`,children:[`No change`,t?``:` ${e.basis}`]});let n=e.direction===`up`?C:y,r=e.tone===`better`?`text-positive`:e.tone===`worse`?`text-negative`:`text-secondary`;return(0,Q.jsxs)(`span`,{className:`flex min-h-5 flex-wrap items-center gap-x-1 text-label-13 tabular-nums`,children:[(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-label-13-strong ${r}`,children:[(0,Q.jsx)(n,{"aria-hidden":`true`,className:`size-3.5`,strokeWidth:2.5}),e.amount]}),!t&&(0,Q.jsx)(`span`,{className:`text-secondary`,children:e.basis})]})}function Wu({figure:e,active:t,compact:n}){return e.stateValue?(0,Q.jsx)(`span`,{className:`flex min-h-10 items-center text-label-14 text-secondary`,children:e.value}):(0,Q.jsxs)(`span`,{className:`flex flex-wrap items-baseline gap-x-1.5`,children:[(0,Q.jsx)(`span`,{className:`${n?`text-heading-20 sm:text-heading-32`:`text-heading-32`} tabular-nums transition-colors duration-150 ${t?`text-primary`:`text-strong`}`,title:e.exactValue,children:e.value}),e.detail&&(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:e.detail})]})}function Gu(e,t){return e.formatExact?.(t)??e.formatValue?.(t)??t.toLocaleString()}function Ku({active:e,payload:t,figure:n,previousLabel:r,rowLabel:i}){let a=t?.[0]?.payload;if(!e||!a)return null;let o=e=>Nu(e)?Gu(n,e):`—`;return(0,Q.jsxs)(`div`,{className:`material-tooltip min-w-48 px-3 py-2 text-label-13`,children:[(0,Q.jsx)(`p`,{className:`mb-1 text-copy-13-strong text-heading`,children:n.label}),(0,Q.jsxs)(`p`,{className:`flex items-center justify-between gap-6`,children:[(0,Q.jsx)(`span`,{className:`text-secondary`,children:i(a)}),(0,Q.jsx)(`span`,{className:`tabular-nums text-primary`,children:a.current===null?`Not recorded`:o(a.current)})]}),r&&a.previous!==void 0&&(0,Q.jsxs)(`p`,{className:`flex items-center justify-between gap-6`,children:[(0,Q.jsx)(`span`,{className:`text-secondary`,children:a.previousDate?Yr(a.previousDate):r}),(0,Q.jsx)(`span`,{className:`tabular-nums text-secondary`,children:o(a.previous)})]})]})}function qu({name:e,groups:t,mode:n=`single`,selected:r,onSelect:i,span:a,cadence:o=`day`,instants:s=!1,currentLabel:c,previous:l,chart:u,legendExtra:f,controls:p,notice:m,emptyChartMessage:h,refreshing:g=!1,chartHeight:_=240,frame:v=`card`,showChartData:y=!1,compact:b=!1,minimumReadings:x=1,hideSpan:S=!1,basisInNotice:C=!1}){let w=(0,Z.useId)().replace(/:/g,``),T=e=>s?Ur(Gr(e)):Yr(e),E=e=>e.label??T(e.date),D=e=>Xr(Gr(new Date(e).toISOString())),[O,k]=(0,Z.useState)(new Set),[A,j]=(0,Z.useState)(!1),M=!$s(),N=t.flatMap(e=>e.figures),P=n===`single`?N.find(e=>e.key===r[0]&&Mu(e)):void 0,F=P?.series??[],I=s?F.map(e=>({...e,at:Date.parse(e.date)})):F,ee=new Map(F.flatMap(e=>e.label?[[e.date,e.label]]:[])),L=!!l?.available&&F.some(e=>Nu(e.previous)),R=F.some(e=>e.current!==null||L&&Nu(e.previous)),z=x<=1||ju(P??{key:``,label:``,value:``})>=x,te=!L||!O.has(Au.current),ne=L&&!O.has(Au.previous),B=ju(P??{key:``,label:``,value:``})<Ou?`linear`:`monotone`,V=`per ${o}`,H=c?Pu(c):a,re=P?`${P.label} ${V}${H?`, ${H}`:``}${L?` and the previous period`:``}`:``,U=N.filter(Mu).map(e=>e.key),ie=U.includes(r[0]??``)?r[0]:U[0],W=e=>{i(e),document.getElementById(`${w}-tab-${e}`)?.focus()},ae=(e,t)=>{let n=U.indexOf(t),r=U.length-1,i=e.key===`ArrowRight`?n===r?0:n+1:e.key===`ArrowLeft`?n<=0?r:n-1:e.key===`Home`?0:e.key===`End`?r:null;i!==null&&(e.preventDefault(),W(U[i]))},se=e=>k(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),ce=(e,t,a)=>{let o=Mu(e),s=o&&r.includes(e.key),c=!!t.basis,l=[`${e.label} ${e.spokenValue??e.value}${e.detail?` ${e.detail}`:``}`,Fu(e.change)].filter(Boolean).join(`, `),u=(0,Q.jsxs)(`div`,{className:`flex min-h-5 items-center gap-1.5`,children:[n===`compare`&&o&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`inline-block size-2.5 shrink-0 rounded-full`,style:{backgroundColor:s?e.color:`transparent`,border:`1.5px solid ${e.color}`}}),e.picker?(0,Q.jsxs)(`span`,{className:`relative inline-flex max-w-full items-center`,children:[(0,Q.jsx)(`select`,{"aria-label":e.picker.ariaLabel,value:e.picker.value,onChange:t=>e.picker.onChange(t.target.value),className:`max-w-full cursor-pointer appearance-none truncate rounded-sm bg-transparent py-0.5 pr-5 text-label-14-strong [field-sizing:content] transition-colors duration-150 hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${s?`text-link`:`text-secondary`}`,children:e.picker.options.map(e=>(0,Q.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,Q.jsx)(d,{"aria-hidden":`true`,className:`pointer-events-none absolute right-0 size-3.5 ${s?`text-link`:`text-muted`}`})]}):(0,Q.jsx)(`span`,{className:`${b?`text-label-12 sm:text-label-14-strong`:`text-label-14-strong`} ${s?n===`single`?`text-link`:`text-heading`:`text-secondary`}`,children:e.label}),e.help&&(0,Q.jsx)(X,{text:e.help})]});return a?(0,Q.jsxs)(`div`,{className:`relative flex min-w-0 flex-col ${b?`px-2 pb-2 pt-2 sm:px-4 sm:pb-4 sm:pt-3`:`px-4 pb-4 pt-3`} transition-colors duration-150 ${s&&n===`single`?`bg-surface-active`:o?`hover:bg-surface-hover`:``}`,children:[n===`single`&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`absolute inset-x-0 top-0 h-[3px] bg-link transition-opacity duration-200 ${s?`opacity-100`:`opacity-0`}`}),u,(0,Q.jsxs)(`button`,{type:`button`,id:`${w}-tab-${e.key}`,...n===`single`?{role:`tab`,"aria-selected":s,"aria-controls":`${w}-panel`,"aria-disabled":!o||void 0,tabIndex:o&&e.key===ie?0:-1,onKeyDown:t=>ae(t,e.key)}:{"aria-pressed":s},"aria-label":l,disabled:n===`compare`&&(e.disabled||!o),onClick:o?()=>i(e.key):void 0,className:`${b?`sm:mt-auto`:`mt-auto`} block w-full rounded-sm pt-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${o?``:`cursor-default`} ${e.disabled?`disabled:cursor-not-allowed disabled:opacity-50`:``}`,children:[(0,Q.jsx)(Wu,{figure:e,active:s,compact:b}),(0,Q.jsx)(Uu,{change:e.change,hideBasis:c})]})]},e.slot??e.key):(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col px-4 pb-4 pt-3`,children:[(0,Q.jsx)(`dt`,{children:u}),(0,Q.jsxs)(`dd`,{className:`mt-auto pt-1`,children:[(0,Q.jsx)(Wu,{figure:e,active:!1,compact:b}),(0,Q.jsx)(Uu,{change:e.change,hideBasis:c}),e.change&&(0,Q.jsx)(`span`,{className:`sr-only`,children:Fu(e.change)})]})]},e.slot??e.key)};return(0,Q.jsxs)(`div`,{className:`${v===`card`?`overflow-hidden material-base`:`-mx-4`} transition-opacity duration-200 ${g?`opacity-60`:``}`,children:[(0,Q.jsx)(`div`,{className:`flex flex-col lg:flex-row`,children:t.map((t,r)=>{let i=(!b||t.figures.length>1)&&t.figures.some(Mu),a=`${w}-group-${t.key}`,o=`grid ${b?{1:`grid-cols-1`,3:`grid-cols-3`}[t.figures.length]??`grid-cols-2`:`grid-cols-2`} ${Eu[Math.min(t.figures.length,3)]} ${Du[Math.min(t.figures.length,6)]}`;return(0,Q.jsxs)(`div`,{role:t.label?`group`:void 0,"aria-labelledby":t.label?a:void 0,className:`min-w-0 lg:basis-0 ${r>0?`border-t border-default lg:border-l lg:border-t-0`:``}`,style:{flexGrow:t.figures.length},children:[(t.label||t.basis&&!C)&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-3 px-4 pt-3`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`span`,{id:a,className:`text-label-13 text-secondary`,children:t.label}),t.help&&(0,Q.jsx)(X,{text:t.help})]}),t.basis&&!C&&(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:t.basis})]}),i?(0,Q.jsx)(`div`,{role:n===`single`?`tablist`:void 0,"aria-label":n===`single`?e:void 0,className:o,children:t.figures.map(e=>ce(e,t,!0))}):(0,Q.jsx)(`dl`,{className:o,children:t.figures.map(e=>ce(e,t,!1))})]},t.key)})}),(0,Q.jsxs)(`div`,{id:`${w}-panel`,...n===`single`&&P&&U.length>0&&(!b||N.length>1)?{role:`tabpanel`,"aria-labelledby":`${w}-tab-${P.key}`}:{role:`region`,"aria-label":`${e} chart`},className:`border-t border-default px-4 ${b?`py-2`:`pb-3 pt-4`}`,children:[m&&(0,Q.jsx)(`div`,{className:`${b?`mb-1.5 text-copy-13`:`mb-3 text-copy-14`} text-secondary`,children:m}),n===`compare`?u:!P||!R||!z?(0,Q.jsx)(`p`,{className:`${b?`flex min-h-20 items-center justify-center px-6 text-center text-copy-14`:`px-4 py-4 text-copy-13`} text-secondary`,children:h}):(0,Q.jsx)(`div`,{role:`img`,"aria-label":re,style:{height:_},children:(0,Q.jsx)(le,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(ve,{data:[...I],margin:{top:8,right:0,bottom:0,left:4},children:[(0,Q.jsx)(oe,{stroke:ei,vertical:!1}),s?(0,Q.jsx)(ue,{dataKey:`at`,type:`number`,scale:`time`,domain:[`dataMin`,`dataMax`],tick:Zr,tickLine:!1,axisLine:{stroke:ni},tickFormatter:D,minTickGap:32,padding:{left:12,right:12}}):(0,Q.jsx)(ue,{dataKey:`date`,tick:Zr,tickLine:!1,axisLine:{stroke:ni},tickFormatter:e=>ee.get(e)??Hr(e),minTickGap:32,padding:ee.size>0?{left:40,right:40}:{left:12,right:12}}),(0,Q.jsx)(ge,{orientation:`right`,reversed:P.reverseValueAxis,domain:P.reverseValueAxis?[1,`auto`]:void 0,tick:Zr,tickLine:!1,axisLine:!1,width:52,allowDecimals:P.allowDecimals??!1,tickFormatter:e=>P.formatValue?.(e)??e.toLocaleString()}),(0,Q.jsx)(he,{cursor:{stroke:Kr.textFaint,strokeWidth:1},wrapperStyle:{outline:`none`},content:(0,Q.jsx)(Ku,{figure:P,previousLabel:L?l?.label:void 0,rowLabel:E})}),ne&&(0,Q.jsx)(_e,{type:B,dataKey:Au.previous,stroke:ku,strokeOpacity:.65,strokeWidth:1.5,strokeDasharray:`4 4`,dot:!1,activeDot:{r:3,strokeWidth:0,fill:ku},connectNulls:!1,isAnimationActive:M,animationDuration:320,animationEasing:`ease-out`}),te&&(0,Q.jsx)(_e,{type:B,dataKey:Au.current,stroke:ku,strokeWidth:2.25,dot:B===`linear`&&{r:3,strokeWidth:0,fill:ku},activeDot:{r:5,strokeWidth:2,stroke:ku,fill:`var(--color-bg)`},connectNulls:!1,isAnimationActive:M,animationDuration:320,animationEasing:`ease-out`})]})})}),n===`single`&&P&&R&&(c||y)||f||a&&!S||p?(0,Q.jsxs)(`div`,{className:b?`flex flex-wrap items-center justify-between gap-x-4 border-t border-subtle pt-1`:`mt-2 flex flex-wrap items-center justify-between gap-x-6 gap-y-1`,children:[y&&P&&R&&(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":A,"aria-controls":`${w}-chart-data`,className:`min-h-8 rounded-sm text-button-14 text-secondary hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 pointer-coarse:min-h-11`,onClick:()=>j(e=>!e),children:`Chart data`}),(L||f||!b)&&(0,Q.jsxs)(`fieldset`,{className:`flex flex-wrap gap-x-5 text-label-13 text-secondary`,children:[(0,Q.jsx)(`legend`,{className:`sr-only`,children:P?`${P.label} series`:`${e} options`}),n===`single`&&P&&R&&c&&l&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ju,{label:c,checked:te,disabled:!L||te&&!ne,onChange:()=>se(Au.current),dash:void 0}),(0,Q.jsx)(Ju,{label:L?l.label:`${l.label}: no earlier data`,checked:ne,disabled:!L||ne&&!te,onChange:()=>se(Au.previous),dash:`4 3`})]}),f]}),(0,Q.jsxs)(`div`,{className:`ml-auto flex flex-wrap items-center gap-x-4 gap-y-1`,children:[a&&!S&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:a}),p]})]}):null,n===`single`&&P&&R&&(0,Q.jsx)(`div`,{id:`${w}-chart-data`,className:y&&A?`border-t border-subtle pt-2`:`sr-only`,children:(0,Q.jsxs)(`table`,{className:y&&A?`w-full text-label-13 [&_td]:py-2 [&_td]:text-right [&_td]:tabular-nums [&_th:first-child]:text-left [&_th:not(:first-child)]:text-right [&_tr]:border-b [&_tr]:border-subtle`:void 0,children:[(0,Q.jsx)(`caption`,{className:y&&A?`sr-only`:void 0,children:re}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:F.some(e=>e.label)?`Release`:`Date`}),(0,Q.jsx)(`th`,{scope:`col`,children:P.label}),L&&(0,Q.jsx)(`th`,{scope:`col`,children:l.label})]})}),(0,Q.jsx)(`tbody`,{children:F.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,children:E(e)}),(0,Q.jsx)(`td`,{children:e.current===null?`Not recorded`:Gu(P,e.current)}),L&&(0,Q.jsx)(`td`,{children:Nu(e.previous)?Gu(P,e.previous):`No data`})]},e.date))})]})})]})]})}function Ju({label:e,checked:t,disabled:n,onChange:r,dash:i}){return(0,Q.jsxs)(`label`,{className:`flex min-h-9 items-center gap-2 pointer-coarse:min-h-11`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,checked:t,disabled:n,onChange:r}),(0,Q.jsx)(`svg`,{"aria-hidden":`true`,width:`18`,height:`10`,viewBox:`0 0 18 10`,className:`shrink-0`,children:(0,Q.jsx)(`line`,{x1:`0`,y1:`5`,x2:`18`,y2:`5`,stroke:ku,strokeWidth:i?1.5:2.5,strokeDasharray:i})}),e]})}var Yu=`baseline`;function Xu(e,t=[]){let n=(e?.series??[]).map((e,t)=>({dataKey:`s${t}`,key:e.key,label:e.label})),r=new Map;for(let t of e?.days??[])r.set(t.date,t.values);let i=new Map(t.map(e=>[e.date,e.value]));return{rows:[...new Set([...r.keys(),...i.keys()])].sort().map(e=>{let t=r.get(e),a={date:e,[Yu]:i.get(e)??null};for(let e of n)a[e.dataKey]=t?.[e.key]??0;return a}),series:n}}var Zu=`text-label-12-strong normal-case text-muted`;function Qu({id:e,title:t,tooltip:n,meta:r,actions:i}){return(0,Q.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-start justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h2`,{id:e,className:`text-heading-16 text-primary`,children:t}),n&&(0,Q.jsx)(X,{text:n})]}),r&&(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:r})]}),i]})}function $u({children:e}){return(0,Q.jsx)(`div`,{className:`[&>details:first-child]:border-t-0`,children:e})}function ed({label:e,meta:t,children:n}){let[r,i]=(0,Z.useState)(!1);return(0,Q.jsxs)(`details`,{className:`visibility-disclosure`,"aria-label":e,onToggle:e=>i(e.currentTarget.open),children:[(0,Q.jsxs)(`summary`,{className:`visibility-disclosure-summary`,children:[(0,Q.jsx)(`span`,{className:`visibility-disclosure-label`,children:e}),(0,Q.jsx)(`span`,{className:`visibility-disclosure-meta`,children:t})]}),r&&(0,Q.jsx)(`div`,{className:`visibility-disclosure-panel`,children:n})]})}var td={3:`lg:grid-cols-3`,4:`lg:grid-cols-4`,5:`lg:grid-cols-5`};function nd({items:e,label:t}){return(0,Q.jsx)(`div`,{role:`group`,"aria-label":t,children:(0,Q.jsx)(`dl`,{className:`grid grid-cols-2 gap-x-6 gap-y-4 border-y border-default py-4 sm:grid-cols-3 ${td[e.length]??`lg:grid-cols-4`}`,children:e.map(e=>(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsxs)(`dt`,{className:`flex items-center gap-1 text-label-13 text-secondary`,children:[e.label,e.tooltip&&(0,Q.jsx)(X,{text:e.tooltip})]}),(0,Q.jsx)(`dd`,{className:`mt-1 truncate text-label-20-strong text-primary tabular-nums`,title:e.value,children:e.value}),e.detail&&(0,Q.jsx)(`dd`,{className:`mt-0.5 text-label-13 text-secondary tabular-nums`,children:e.detail})]},e.label))})})}function rd({label:e,sortKey:t,current:n,dir:r,onSort:i,align:a,help:o}){let s=n===t,c=(0,Q.jsxs)(`button`,{type:`button`,className:`${Zu} cursor-pointer select-none rounded transition-colors hover:text-neutral focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400`,onClick:()=>i(t),children:[e,s&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`ml-0.5`,children:r===`asc`?`↑`:`↓`})]});return(0,Q.jsx)(`th`,{className:`py-2 ${a===`right`?`pl-4 text-right`:`text-left`}`,"aria-sort":s?r===`asc`?`ascending`:`descending`:void 0,children:o?(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[c,(0,Q.jsx)(X,{text:o})]}):c})}function id({label:e,align:t,help:n}){return(0,Q.jsx)(`th`,{className:`py-2 ${t===`right`?`pl-4 text-right`:`text-left`}`,children:n?(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Q.jsx)(`span`,{className:Zu,children:e}),(0,Q.jsx)(X,{text:n})]}):(0,Q.jsx)(`span`,{className:Zu,children:e})})}function ad(e,t,n=`desc`){return e.key===t?{key:t,dir:e.dir===`desc`?`asc`:`desc`}:{key:t,dir:n}}function od(e,t){return(n,r)=>{let i=n[e],a=r[e],o=typeof i==`string`&&typeof a==`string`?i.localeCompare(a):Number(i)-Number(a);return t===`asc`?o:-o}}function sd(e,t){return(n,r)=>{let i=e(n),a=e(r);return i===null||a===null?Number(i===null)-Number(a===null):t===`asc`?i-a:a-i}}function cd({groups:e,groupLabel:t,caption:n,childColumns:r,childRowKey:i,renderChildCells:a,pinLast:o,extraColumns:s=[],defaultSort:c,referenceRow:l}){let u=(0,Z.useId)(),[f,p]=(0,Z.useState)(new Set),[h,g]=(0,Z.useState)(c??{key:`sessions`,dir:`desc`}),_=(0,Z.useMemo)(()=>{let t=s.find(e=>e.key===h.key),n=t?.sortValue?sd(t.sortValue,h.dir):od(h.key,h.dir);return[...e].sort((e,t)=>Number(o?.(e)??!1)-Number(o?.(t)??!1)||n(e,t))},[e,h,o,s]),v=e=>g(t=>ad(t,e,s.find(t=>t.key===e)?.firstDir??(e===`label`?`asc`:`desc`))),y=e=>p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`w-full text-label-14 ${s.length>0?`min-w-[48rem]`:`min-w-[36rem]`}`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:n}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,Q.jsx)(rd,{label:t,sortKey:`label`,current:h.key,dir:h.dir,onSort:v,align:`left`}),(0,Q.jsx)(rd,{label:`Sessions`,sortKey:`sessions`,current:h.key,dir:h.dir,onSort:v,align:`right`}),(0,Q.jsx)(rd,{label:`Organic`,sortKey:`organicSessions`,current:h.key,dir:h.dir,onSort:v,align:`right`}),(0,Q.jsx)(rd,{label:`Paid`,sortKey:`paidSessions`,current:h.key,dir:h.dir,onSort:v,align:`right`}),(0,Q.jsx)(id,{label:`Share`,align:`right`}),s.map(e=>e.sortValue?(0,Q.jsx)(rd,{label:e.label,sortKey:e.key,current:h.key,dir:h.dir,onSort:v,align:`right`,help:e.help},e.key):(0,Q.jsx)(id,{label:e.label,align:`right`,help:e.help},e.key))]})}),(0,Q.jsxs)(`tbody`,{children:[l,_.map((e,t)=>{let n=f.has(e.label),o=`${u}-group-${t}`,c=e.sources.length;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,Q.jsx)(`td`,{className:`py-2 pr-3`,children:(0,Q.jsxs)(`button`,{type:`button`,"aria-expanded":n,"aria-controls":n?o:void 0,onClick:()=>y(e.label),className:`inline-flex min-h-8 max-w-full items-center gap-2 rounded text-left text-strong hover:text-primary focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400`,children:[n?(0,Q.jsx)(d,{"aria-hidden":`true`,className:`size-3.5 shrink-0 text-secondary`}):(0,Q.jsx)(m,{"aria-hidden":`true`,className:`size-3.5 shrink-0 text-muted`}),(0,Q.jsx)(`span`,{className:`truncate`,title:e.label,children:e.label}),(0,Q.jsxs)(`span`,{className:`shrink-0 text-label-12 text-secondary tabular-nums`,children:[c,` `,c===1?`source`:`sources`]})]})}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-secondary tabular-nums`,children:e.organicSessions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-secondary tabular-nums`,children:e.paidSessions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-secondary tabular-nums`,children:Ut(e.share)}),s.map(t=>(0,Q.jsx)(Z.Fragment,{children:t.render(e)},t.key))]}),n&&(0,Q.jsx)(`tr`,{id:o,children:(0,Q.jsx)(`td`,{colSpan:5+s.length,className:`pb-3 pl-6`,children:(0,Q.jsx)(`div`,{className:`overflow-x-auto material-base px-3 pb-1`,children:(0,Q.jsxs)(`table`,{className:`w-full min-w-[32rem] text-label-13`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`${e.label} sources`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsx)(`tr`,{children:r.map(e=>(0,Q.jsx)(id,{label:e.label,align:e.align,help:e.help},e.label))})}),(0,Q.jsx)(`tbody`,{children:e.sources.map(e=>(0,Q.jsx)(`tr`,{className:`border-t border-subtle`,children:a(e)},i(e)))})]})})})})]},e.label)})]})]})})}function ld(e,t){return e===`other`?Kr.textDim:zr[t%zr.length]}function ud({input:e,baseline:t,baselineLabel:n,label:r,height:i=224}){let{rows:a,series:o}=(0,Z.useMemo)(()=>Xu(e,t),[e,t]),[s,c]=(0,Z.useState)(new Set),[l,u]=(0,Z.useState)(!1);if(a.length===0)return null;let d=o.filter(e=>!s.has(e.key)),f=new Map(o.map(e=>[e.dataKey,e.label])),p=e=>c(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{role:`img`,"aria-label":r,style:{height:i},children:(0,Q.jsx)(le,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(ve,{data:a,margin:{top:4,right:4,bottom:0,left:0},children:[(0,Q.jsx)(oe,{stroke:ei,vertical:!1}),(0,Q.jsx)(ue,{dataKey:`date`,tick:Zr,tickLine:!1,axisLine:{stroke:ni},tickFormatter:Hr,minTickGap:24}),(0,Q.jsx)(ge,{tick:Zr,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,Q.jsx)(he,{...ti,labelFormatter:Yr,formatter:(e,t)=>[typeof e==`number`?e.toLocaleString():String(e??0),t===`baseline`?n??`Total`:f.get(String(t))??String(t)]}),d.map(e=>{let t=ld(e.key,o.indexOf(e));return(0,Q.jsx)(me,{type:`monotone`,dataKey:e.dataKey,name:e.dataKey,stackId:`stack`,stroke:t,fill:t,fillOpacity:.35,strokeWidth:1.5},e.dataKey)}),l&&n&&(0,Q.jsx)(_e,{type:`monotone`,dataKey:`baseline`,name:`baseline`,stroke:Kr.textFaint,strokeWidth:1.5,strokeDasharray:`5 4`,dot:!1,connectNulls:!1})]})})}),(0,Q.jsxs)(`fieldset`,{className:`mt-2 flex flex-wrap gap-x-5 text-label-13 text-secondary`,children:[(0,Q.jsx)(`legend`,{className:`sr-only`,children:`${r} series`}),o.map((e,t)=>(0,Q.jsxs)(`label`,{className:`flex min-h-9 items-center gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,checked:!s.has(e.key),onChange:()=>p(e.key)}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`inline-block size-2.5 shrink-0 rounded-sm`,style:{backgroundColor:ld(e.key,t)}}),e.label]},e.key)),n&&(0,Q.jsxs)(`label`,{className:`flex min-h-9 items-center gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,checked:l,onChange:()=>u(e=>!e)}),(0,Q.jsx)(`svg`,{"aria-hidden":`true`,width:`18`,height:`10`,viewBox:`0 0 18 10`,className:`shrink-0`,children:(0,Q.jsx)(`line`,{x1:`0`,y1:`5`,x2:`18`,y2:`5`,stroke:Kr.textFaint,strokeWidth:`2`,strokeDasharray:`5 3`})}),n]})]})]})}var dd=[`sessions`,`activeUsers`,`organicSessions`,`engagementRate`,`keyEvents`],fd=`canonry.siteTraffic.slots`;function pd(e){return typeof e==`string`&&ar.some(t=>t===e)}function md(){try{let e=JSON.parse(window.localStorage.getItem(fd)??`null`);if(Array.isArray(e)&&e.length===dd.length&&e.every(pd))return[...e]}catch{}return[...dd]}function hd(e){try{window.localStorage.setItem(fd,JSON.stringify(e))}catch{}}function gd(e,t,n){let r=lr(e,t);return r===null||t===null?{kind:`note`,text:`No earlier data`}:{kind:`delta`,amount:Ut(Math.abs(t),Je.percent),direction:t>0?`up`:t<0?`down`:`flat`,tone:r===bn.better?`better`:r===bn.worse?`worse`:`neutral`,basis:n}}function _d({overview:e,refreshing:t=!1}){let[n,r]=(0,Z.useState)(md),[i,a]=(0,Z.useState)(0),o=vr(e.window)?mn[e.window]:null,s=o===null?`This period`:`Last ${o} days`,c=o===null?`vs the previous period`:`vs prior ${o} days`,l=(e,t)=>r(n=>{let r=[...n],i=r.indexOf(t);return i!==-1&&i!==e&&(r[i]=r[e]),r[e]=t,hd(r),r}),u=n.map((t,n)=>({key:t,slot:`slot-${n}`,label:On[t].label,value:Jt(t,e.totals[t],{compact:!0}),exactValue:Jt(t,e.totals[t]),change:gd(t,e.changePct[t],c),series:e.days.map(e=>({date:e.date,previousDate:e.previousDate,current:e.values[t],previous:e.previousValues[t]})),interactive:!0,picker:{ariaLabel:`Figure ${n+1}`,value:t,options:ar.map(e=>({value:e,label:On[e].label})),onChange:e=>{pd(e)&&l(n,e)}},formatValue:e=>Jt(t,e,{compact:!0}),formatExact:e=>Jt(t,e),allowDecimals:On[t].unit!==_n.count})),d=n[i]??dd[0],f=e.current.startDate&&e.current.endDate&&e.previous.startDate&&e.previous.endDate?`${vd(e.current.startDate,e.current.endDate,!0)} vs ${vd(e.previous.startDate,e.previous.endDate,!1)}`:void 0;return(0,Q.jsx)(qu,{name:`Site traffic figures`,groups:[{key:`site-traffic`,figures:u}],selected:[d],onSelect:e=>{let t=n.indexOf(e);t!==-1&&a(t)},span:f,currentLabel:s,previous:{label:`Previous period`,available:!0},notice:e.syncedAt===null?`These figures fill in after the next GA4 sync.`:void 0,emptyChartMessage:`No daily ${On[d].label.toLowerCase()} yet.`,refreshing:t})}function vd(e,t,n){let r=(e,t)=>new Date(`${e}T00:00:00Z`).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,...t?{year:`numeric`}:{},timeZone:`UTC`});return`${r(e,!1)} to ${r(t,n)}`}function yd(e){return e?Yr(e.slice(0,10)):`—`}function bd({children:e,onClick:t,disabled:n,title:r}){return(0,Q.jsx)(`button`,{type:`button`,title:r,disabled:n,onClick:t,className:`rounded px-1.5 py-0.5 text-button-14 text-secondary hover:bg-surface-hover hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-50`,children:e})}function xd({rows:e,expanded:t,loading:n,onToggle:r,actions:i,lastReadLabel:a,empty:o}){let s=i?6:5,c=(e,a)=>{let o=t.has(e.url),s=n?.has(e.url)??!1;return(0,Q.jsxs)(`tr`,{className:`group`,children:[(0,Q.jsx)(`td`,{className:`max-w-md ${a?`pl-9`:``}`,children:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-0.5`,children:[e.isIndex&&!a&&(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":o,"aria-label":`${o?`Hide`:`Show`} the sitemaps in ${e.label}`,className:`rounded p-0.5 text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>r(e.url),children:o?(0,Q.jsx)(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(m,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),(0,Q.jsx)(Ql,{value:e.label,title:e.url,className:`font-mono text-label-13 text-neutral`}),e.isIndex&&(0,Q.jsx)(`span`,{className:`shrink-0 text-label-12 text-secondary`,children:s?`Loading…`:e.files?`Index · ${e.files.length} ${e.files.length===1?`sitemap`:`sitemaps`}`:`Index`}),e.kind&&(0,Q.jsx)(`span`,{className:`shrink-0 text-label-12 text-secondary`,children:e.kind}),e.isDefault&&(0,Q.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 text-label-12 text-secondary`,children:[`Default`,(0,Q.jsx)(X,{text:`Canonry uses this sitemap when a command names none.`})]})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5 whitespace-nowrap`,children:[(0,Q.jsx)(J,{tone:e.status.tone,children:e.status.label}),e.status.detail&&(0,Q.jsx)(`span`,{className:`text-label-12 text-secondary`,children:e.status.detail})]})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.urls===null?`—`:e.urls.toLocaleString()}),(0,Q.jsx)(`td`,{className:`whitespace-nowrap tabular-nums text-secondary`,children:e.missing?`—`:e.submittedAt?yd(e.submittedAt):a?(0,Q.jsx)(`span`,{title:`Submitted through its sitemap index.`,children:`Via index`}):(0,Q.jsx)(`span`,{title:`Nobody submitted it: the engine found it on its own.`,children:`Not submitted`})}),(0,Q.jsx)(`td`,{className:`whitespace-nowrap tabular-nums text-secondary`,children:e.missing?`—`:e.lastReadAt?yd(e.lastReadAt):`Not yet`}),i&&(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsx)(`div`,{className:`flex justify-end gap-0.5 whitespace-nowrap ${e.missing?``:`opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 pointer-coarse:opacity-100`}`,children:i(e,a)})})]},`${a?.url??``}|${e.url}`)};return(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Sitemap`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Status`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`URLs`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Submitted`}),(0,Q.jsx)(`th`,{className:`text-left`,children:a}),i&&(0,Q.jsx)(`th`,{className:`text-right`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,Q.jsxs)(`tbody`,{children:[e.length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:s,className:`py-6 text-center text-secondary`,children:o})}),e.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[c(e,null),e.isIndex&&t.has(e.url)&&(e.files??[]).map(t=>c(t,e))]},e.url))]})]})})}var Sd=10,Cd={ok:`positive`,pending:`neutral`,warnings:`caution`,errors:`negative`,other:`neutral`},wd={site:`on your site`,google:`in Google`,bing:`in Bing`};function Td(e){return e.map(e=>wd[e]).join(` and `)}function Ed(e){let t=[e.errors?`${e.errors} error${e.errors===1?``:`s`}`:``,e.warnings?`${e.warnings} warning${e.warnings===1?``:`s`}`:``].filter(Boolean);return t.length>0?t.join(` · `):void 0}function Dd(e){let{engine:t,data:n,label:r}=e,[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(new Set),[u,d]=(0,Z.useState)(new Set),[f,p]=(0,Z.useState)(``),m=n?.sitemaps??[],h=t=>({url:t.url,label:r(t.url),isIndex:t.isIndex,kind:!t.isIndex&&t.type&&!/^sitemap$/i.test(t.type)?t.type:void 0,status:{label:t.statusLabel,tone:Cd[t.state],detail:Ed(t)},urls:t.urlCount,submittedAt:t.submittedAt,lastReadAt:t.lastReadAt,isDefault:e.defaultUrl===t.url}),g=(n?.missing??[]).map(e=>({url:e.url,label:r(e.url),isIndex:!1,status:u.has(e.url)?{label:`Sent`,tone:`neutral`,detail:`shows after the next sync`}:{label:`Missing`,tone:`caution`,detail:Td(e.foundIn)},urls:null,submittedAt:null,lastReadAt:null,missing:!0})),_=m.filter(e=>e.parentUrl===null).map(e=>({...h(e),files:e.isIndex?m.filter(t=>t.parentUrl===e.url).map(h):void 0})),v=$l({rows:[...g,..._],getSearchText:e=>`${e.url} ${e.files?.map(e=>e.url).join(` `)??``}`,pageSize:Sd});async function y(t){let n=await e.onSubmit(t);return n.length>0&&d(e=>new Set([...e,...n])),n}let b=g.filter(e=>!u.has(e.url)).length,x=_.filter(e=>e.isIndex).length;return(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{children:`Sitemaps`}),(0,Q.jsx)(X,{text:`Canonry compares the sitemaps your site lists (from the latest Agent Readiness audit scan) with what ${t} and the other engine have, and shows what ${t} is missing. Submitting asks ${t} to read a sitemap; it does not guarantee indexing.`})]}),b>0&&(0,Q.jsx)(X,{tone:`caution`,label:`${b} missing`,text:`${b===1?`One sitemap your site or the other engine has is`:`${b} sitemaps your site or the other engine has are`} not in ${t}. Add ${b===1?`it`:`them`} from the list.`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n&&(0,Q.jsxs)(`span`,{className:`text-label-13 text-secondary`,children:[`As of `,Jr(n.syncedAt)]}),!e.readOnly&&(e.canSubmit?(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,disabled:i||e.submitting,onClick:()=>a(!0),children:`Add another`}):e.submitBlocked)]})]}),i&&e.canSubmit&&!e.readOnly&&(0,Q.jsxs)(`form`,{className:`mb-3 flex flex-col gap-2 sm:flex-row`,onSubmit:e=>{e.preventDefault();let t=o.trim();t&&y([t]).then(e=>{e.includes(t)&&(s(``),a(!1))})},children:[(0,Q.jsx)(`input`,{"aria-label":`Sitemap URL`,className:`flex-1 rounded border border-strong bg-transparent px-2 py-1.5 font-mono text-label-13 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`url`,autoFocus:!0,placeholder:`https://example.com/sitemap.xml`,value:o,onChange:e=>s(e.target.value)}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(q,{type:`submit`,size:`sm`,disabled:e.submitting||!o.trim(),children:e.submitting?`Submitting…`:`Submit to ${t}`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{a(!1),s(``)},children:`Cancel`})]})]}),e.loadError?(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load sitemaps: `,e.loadError]}):n===void 0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Loading sitemaps…`}):n===null?e.notRead:(0,Q.jsxs)(Q.Fragment,{children:[(_.length>0||g.length>0)&&(0,Q.jsxs)(`div`,{className:`mb-2 flex flex-wrap items-center justify-between gap-2`,children:[(0,Q.jsx)(eu,{className:`w-full sm:w-64`,value:f,onChange:e=>{p(e),v.setQuery(e)},label:`Filter sitemaps`,placeholder:`Filter sitemaps…`}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsxs)(`span`,{className:`text-label-13 text-secondary`,children:[_.length,` in `,t,x>0?`, ${x} ${x===1?`index`:`indexes`}`:``]}),e.bulk]})]}),(0,Q.jsx)(xd,{rows:v.rows,expanded:c,onToggle:e=>l(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),lastReadLabel:`Last read`,empty:`${t} lists no sitemaps for this site, and Canonry found none to add.`,actions:e.readOnly?void 0:n=>n.missing?(0,Q.jsx)(bd,{disabled:!e.canSubmit||e.submitting||u.has(n.url),onClick:()=>void y([n.url]),children:u.has(n.url)?`Sent`:`Add to ${t}`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(bd,{disabled:!e.canSubmit||e.submitting,onClick:()=>void y([n.url]),children:n.submittedAt?`Resubmit`:`Submit`}),e.onInspect&&(0,Q.jsx)(bd,{disabled:e.inspecting,onClick:()=>e.onInspect(n.url),children:`Inspect URLs`}),e.onSetDefault&&!n.isDefault&&(0,Q.jsx)(bd,{disabled:e.settingDefault,title:`Canonry uses this sitemap when a command names none.`,onClick:()=>e.onSetDefault(n.url),children:`Set as default`})]})}),v.totalRows>Sd&&(0,Q.jsx)(tu,{page:v.page,pageSize:Sd,visibleRows:v.rows.length,totalRows:v.totalRows,onPageChange:v.setPage,itemLabel:`sitemaps`})]})]})}function Od({label:e,items:t,disabled:n=!1,menuLabel:r,triggerRef:i}){let[a,o]=(0,Z.useState)(!1),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null),l=i??c,u=(0,Z.useId)();return(0,Z.useEffect)(()=>{if(!a)return;s.current?.querySelector(`[role="menuitem"]:not([disabled])`)?.focus();let e=e=>{s.current&&!s.current.contains(e.target)&&o(!1)},t=e=>{e.key===`Escape`&&(o(!1),l.current?.focus())};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[a,l]),(0,Q.jsxs)(`div`,{className:`relative inline-flex`,ref:s,children:[(0,Q.jsxs)(q,{ref:l,type:`button`,variant:`outline`,size:`sm`,disabled:n,"aria-haspopup":`menu`,"aria-expanded":a,"aria-controls":a?u:void 0,onClick:()=>o(e=>!e),children:[e,(0,Q.jsx)(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]}),a&&(0,Q.jsx)(`div`,{id:u,role:`menu`,"aria-label":r,className:`project-subnav-menu min-w-[16rem]`,onKeyDown:e=>{let t=[...e.currentTarget.querySelectorAll(`[role="menuitem"]:not([disabled])`)],n=t.indexOf(document.activeElement),r=e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n-1+t.length)%t.length:null;r!==null&&(e.preventDefault(),t[r]?.focus())},onBlur:e=>{s.current?.contains(e.relatedTarget)||o(!1)},children:t.map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`menuitem`,tabIndex:-1,disabled:e.disabled,className:`project-subnav-menu-item flex flex-col items-start gap-0.5 text-left disabled:cursor-not-allowed disabled:opacity-50`,onClick:()=>{o(!1),e.onSelect()},children:[(0,Q.jsx)(`span`,{children:e.label}),e.description&&(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:e.description})]},e.key))})]})}function kd(e){let t=e.details;if(e.code!==`FORBIDDEN`||!t||t.reason!==`gsc-api-disabled`)return null;let n=typeof t.projectNumber==`string`?t.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 t.enableUrl==`string`?t.enableUrl:void 0,indexingApiUrl:typeof t.indexingApiUrl==`string`?t.indexingApiUrl:void 0,projectNumber:n}}var Ad=`Unexpected OAuth redirect URL. Please try again.`;async function jd(e,t,n){let{authUrl:r,redirectUri:i}=await Yt(e,t);if(!r.startsWith(`https://accounts.google.com/`))throw Error(Ad);let a=window.open(r,`_blank`,`width=600,height=700`);if(!a)return window.location.assign(r),`redirect`;let o=i?new URL(i).origin:window.location.origin,s=!1,c=e=>{s||(s=!0,window.clearInterval(u),window.removeEventListener(`message`,l),n(e))};function l(e){if(e.source!==a||e.origin!==o||!e.data||typeof e.data!=`object`)return;let n=e.data;n.type===`canonry:google-oauth-complete`&&n.connectionType===t&&c(!0)}window.addEventListener(`message`,l);let u=window.setInterval(()=>{a.closed&&c(!1)},1e3);return`popup`}var Md=`Search Console is not connected yet. Your Canonry team can set this up.`,Nd=[`7d`,`30d`,`90d`,`all`],Pd=500,Fd=[{key:`clicks`,label:`Clicks`,color:zr[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:zr[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:Qr.caution,format:e=>Ut(e)},{key:`position`,label:`Avg position`,color:zr[2],inverted:!0,format:e=>e.toFixed(1)}],Id=25;function Ld(e,t,n){if(!e)return{kind:`note`,text:`No comparison period`};if(!e.comparable)return{kind:`note`,text:`Property-level comparison unavailable`};let r=`${e.days} ${e.days===1?`day`:`days`}`,i=`vs prior ${r}`,a=e=>e===!!n?`worse`:`better`,o=t===`ctr`||t===`position`?e.difference?.[t]:void 0;if(o!=null&&Number.isFinite(o))return o===0?{kind:`delta`,amount:t===`ctr`?`0 pts`:`0`,direction:`flat`,tone:`neutral`,basis:i}:{kind:`delta`,amount:t===`ctr`?`${lt(Math.abs(o)).magnitude} pts`:Se(o),direction:o>0?`up`:`down`,tone:a(o>0),basis:i};let s=e.change[t];if(s===null||!Number.isFinite(s)){let n=e.prior[t],i=e.trailing[t];return n!==null&&i!==null&&n<=0&&i>0?{kind:`note`,text:`New in the last ${r}`}:n===null||n<=0?{kind:`note`,text:`No prior ${r} to compare`}:i===null?{kind:`note`,text:`No value in the last ${r}`}:{kind:`note`,text:`Comparison unavailable`}}return s===0?{kind:`delta`,amount:`0%`,direction:`flat`,tone:`neutral`,basis:i}:{kind:`delta`,amount:Ut(Math.abs(s)),direction:s>0?`up`:`down`,tone:a(s>0),basis:i}}var Rd=[{key:`google-indexed`,engine:`google`,color:zr[0]},{key:`bing-indexed`,engine:`bing`,color:zr[6]}];function zd(e){if(!e)return`Tile percentages compare the selected window with the equal-length period before it.`;let{days:t,basis:n,prior:r,trailing:i}=e,a=t===1?`day`:`days`,o=`${r.startDate} to ${r.endDate}`,s=`Tile percentages compare these ${t} ${a} (${`${i.startDate} to ${i.endDate}`}) with the ${t} ${a} before them (${o}).`;return n===`split-window`?`${s} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`:s}function Bd(e,t){let n;try{n=new URL(e)}catch{return e}let r=`${n.pathname}${n.search}`;if(t?.startsWith(`sc-domain:`)){if(n.hostname===t.slice(10))return r}else if(t&&e.startsWith(t.replace(/\/?$/,`/`)))return`/${e.slice(t.replace(/\/?$/,`/`).length)}`;return`${n.host}${r}`}function Vd({projectName:e,refreshNonce:t}){let n=z(),{isAdmin:r}=si(),i=rt(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)([]),[l,u]=(0,Z.useState)([]),[d,f]=(0,Z.useState)([]),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)([]),[_,v]=(0,Z.useState)([]),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(``),[C,w]=(0,Z.useState)(``),[T,E]=(0,Z.useState)(`30`),[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(`30d`),[j,M]=(0,Z.useState)(null),N=W({...To({client:Y,path:{name:e},query:j?{surface:`index-coverage`,...j}:{surface:`index-coverage`,window:k}}),staleTime:di,placeholderData:te}),[P,F]=(0,Z.useState)([`clicks`,`impressions`]),[I,ee]=(0,Z.useState)(!0),[L,R]=(0,Z.useState)(null),[ne,B]=(0,Z.useState)(0),[V,H]=(0,Z.useState)({startDate:``,endDate:``,query:``,page:``}),[re,ie]=(0,Z.useState)(0),[ae,oe]=(0,Z.useState)(!1),[se,ce]=(0,Z.useState)(0),[le,ue]=(0,Z.useState)(!1),[de,fe]=(0,Z.useState)(``),[pe,me]=(0,Z.useState)(!0),[he,ge]=(0,Z.useState)(!1),[_e,ve]=(0,Z.useState)(!1),[ye,xe]=(0,Z.useState)(!1),[Se,we]=(0,Z.useState)(!1),[Te,Ee]=(0,Z.useState)(!1),[De,Oe]=(0,Z.useState)(!1),[G,ke]=(0,Z.useState)(null),[Ae,je]=(0,Z.useState)(!1),[Me,Ne]=(0,Z.useState)(null),[Pe,Fe]=(0,Z.useState)(!1),[Ie,Le]=(0,Z.useState)(!1),[Re,ze]=(0,Z.useState)(!1),[Be,Ve]=(0,Z.useState)(!1),[He,Ue]=(0,Z.useState)(`indexed`),We=(0,Z.useId)(),[Ge,Ke]=(0,Z.useState)(null),Je=!!(V.query.trim()||V.page.trim()||Ge),Ye=Ge!==null,Xe=(0,Z.useMemo)(()=>{if(!Ge)return d;let{key:e,dir:t}=Ge;return[...d].sort((n,r)=>{let i=e===Br.CTR?Number.isFinite(n.ctr)?n.ctr:0:n[e],a=e===Br.CTR?Number.isFinite(r.ctr)?r.ctr:0:r[e];return t===`asc`?i-a:a-i})},[d,Ge]),Ze=$l({rows:Xe,pageSize:25}),Qe=le?Ze.rows:Xe,[$e,et]=(0,Z.useState)([]),[tt,nt]=(0,Z.useState)(null),[it,at]=(0,Z.useState)(1),ot=(0,Z.useMemo)(()=>{if($e.length<2)return null;let e=$e[$e.length-1],t=$e[$e.length-2];return{indexed:e.indexed-t.indexed,notIndexed:e.notIndexed-t.notIndexed}},[$e]);(0,Z.useEffect)(()=>{at(1)},[G,He,tt]);let st=(0,Z.useMemo)(()=>tt?(G?.reasonGroups??[]).find(e=>e.reason===tt):void 0,[G,tt]),ct=(0,Z.useMemo)(()=>G?He===`indexed`?G.indexed:He===`deindexed`?G.deindexed:He===`notIndexed`?tt?st?.urls??[]:(G.reasonGroups??[]).length===0?G.notIndexed:[]:[]:[],[G,He,tt,st]),lt=Math.max(1,Math.ceil(ct.length/Id)),ut=Math.min(Math.max(1,it),lt),dt=(ut-1)*Id,ft=(0,Z.useMemo)(()=>G?.indexed.slice(dt,dt+Id)??[],[G,dt]),pt=(0,Z.useMemo)(()=>G?.notIndexed.slice(dt,dt+Id)??[],[G,dt]),mt=(0,Z.useMemo)(()=>G?.deindexed.slice(dt,dt+Id)??[],[G,dt]),ht=(0,Z.useMemo)(()=>(st?.urls??[]).slice(dt,dt+Id),[st,dt]),[gt,_t]=(0,Z.useState)(!1),[vt,yt]=(0,Z.useState)(null),[bt,xt]=(0,Z.useState)(null),[St,wt]=(0,Z.useState)(null),[Tt,Et]=(0,Z.useState)(null);function Dt(e,t){let n=Ts(e),r=kd(n);r?(xt(r),yt(null)):(xt(null),yt(n.message||t))}let Ot=s.find(e=>e.connectionType===`gsc`),kt=(Ot?.scopes??[]).includes(`https://www.googleapis.com/auth/webmasters`),At=W({...So({client:Y,path:{name:e}}),staleTime:di,enabled:!!Ot?.propertyId&&!i}),jt=At.data?.google?.sitemaps??[],Mt=jt.filter(e=>e.parentUrl===null),Nt=Mt.filter(e=>e.isIndex).map(e=>e.url),Pt=Nt.length>0?Nt:Mt.map(e=>e.url),Ft=Nt.length,It=Ft===1?`Resubmit sitemap index`:Ft>1?`Resubmit sitemap indexes`:`Resubmit all sitemaps`,Lt=d.length>0||h.length>0||_.length>0,Rt=Ac(),zt=vc();async function Bt(t,r=!1){if(i)u([]);else if(!t)u([]),S(``);else{ve(!0);try{let{sites:i}=await n.fetchQuery({...lo({client:Y,path:{name:e}}),staleTime:r?0:di});u(i),S(t.propertyId??i[0]?.siteUrl??``),xt(null)}catch(e){u([]),Dt(e,`Failed to load Search Console properties`)}finally{ve(!1)}}}async function Vt(t){we(!0);let r=t??re;try{let t=Je?Pd:25,i=Je?0:r,a={limit:String(t)};V.startDate&&(a.startDate=V.startDate),V.endDate&&(a.endDate=V.endDate),V.query&&(a.query=V.query),V.page&&(a.page=V.page),i>0&&(a.offset=String(i)),k&&k!==`all`&&!V.startDate&&(a.window=k);let o=await n.fetchQuery({...Va({client:Y,path:{name:e},query:a}),staleTime:di}),s=o.rows;Je?(oe(!1),f(s),ce(s.length),ue(!0)):(oe(i+s.length<o.totalMatching),f(s),ce(0),ue(!1))}catch(e){f([]),oe(!1),ce(0),yt(e instanceof Error?e.message:`Failed to load GSC performance data`)}finally{we(!1)}}async function Ht(){try{let t={};V.startDate&&(t.startDate=V.startDate),V.endDate&&(t.endDate=V.endDate),k&&k!==`all`&&!V.startDate&&(t.window=k);let r=await n.fetchQuery({...Ia({client:Y,path:{name:e},query:t}),staleTime:di});m(r),M(t.startDate||t.endDate?{...t.startDate?{startDate:t.startDate}:{},...t.endDate?{endDate:t.endDate}:{}}:null)}catch{m(null)}}async function Gt(t=!1){Ee(!0);try{let r=de.trim()||void 0,i={limit:`20`};r&&(i.url=r);let[a,o]=await Promise.all([n.fetchQuery({...Co({client:Y,path:{name:e},query:i}),staleTime:t?0:di}),n.fetchQuery({...$a({client:Y,path:{name:e}}),staleTime:t?0:di})]);g(a),v(o)}catch(e){g([]),v([]),yt(e instanceof Error?e.message:`Failed to load GSC inspection history`)}finally{Ee(!1)}}async function Kt(t=!1){je(!0);try{let[r,i]=await Promise.all([n.fetchQuery({...Na({client:Y,path:{name:e}}),staleTime:t?0:di}),n.fetchQuery({...vo({client:Y,path:{name:e}}),staleTime:t?0:di}).catch(()=>[])]);ke(r),et(i)}catch(e){ke(null),et([]),yt(e instanceof Error?e.message:`Failed to load coverage data`)}finally{je(!1)}}async function qt(t){_t(!0),yt(null);try{let{succeeded:n,failed:r,total:i}=(await qe(e,{urls:t})).summary;li({title:`Indexing requested`,detail:r===0?`${n} URL${n===1?``:`s`} submitted for indexing.`:`${n}/${i} submitted successfully, ${r} failed.`,tone:r===0?`positive`:`caution`,dedupeKey:`gsc:indexing:${e}`,dedupeMode:`replace`})}catch(e){yt(e instanceof Error?e.message:`Failed to request indexing`)}finally{_t(!1)}}async function Jt(){_t(!0),yt(null);try{let{succeeded:t,failed:n,total:r}=(await qe(e,{urls:[],allUnindexed:!0})).summary;li({title:`Indexing requested`,detail:n===0?`${t} unindexed URL${t===1?``:`s`} submitted for indexing.`:`${t}/${r} submitted successfully, ${n} failed.`,tone:n===0?`positive`:`caution`,dedupeKey:`gsc:indexing-all:${e}`,dedupeMode:`replace`})}catch(e){yt(e instanceof Error?e.message:`Failed to request indexing`)}finally{_t(!1)}}async function Yt(t){let n=[];if(!kt||t.length===0)return n;let r=[...new Set(t)];Le(!0),yt(null),Ne({completed:0,total:r.length});let i=0,a=0,o=0,s=null;try{for(let t=0;t<r.length;t+=50){let c=r.slice(t,t+50);try{let t=await Mn(e,c);n.push(...t.results.filter(e=>e.status===`accepted`).map(e=>e.sitemapUrl)),i+=t.summary.accepted,a+=t.summary.failed,o+=c.length,Ne({completed:o,total:r.length})}catch(t){o+=c.length;let l=c.length,u=r.length-o,d=t instanceof Error?t.message:`The batch request failed`,f=`${i} accepted, ${a} failed, ${l} unconfirmed, ${u} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;return s=`Sitemap submission stopped after a batch request failed. ${f} ${d}`,yt(s),li({title:`Sitemap resubmission partially completed`,detail:f,tone:`caution`,dedupeKey:`gsc:sitemap-submit:${e}`,dedupeMode:`replace`}),n}}let t=r.length;li({title:a===0?`Sitemap submitted to Google`:`Some sitemap submissions need attention`,detail:a===0?`Google accepted the sitemap submission/refetch request; indexing is not guaranteed.`:`Google accepted ${i}/${t} sitemap submissions; ${a} failed. Indexing is not guaranteed.`,tone:a===0?`positive`:`caution`,dedupeKey:`gsc:sitemap-submit:${e}`,dedupeMode:`replace`})}catch(e){yt(e instanceof Error?e.message:`Failed to submit sitemap to Google`)}finally{Le(!1),Ne(null),s&&yt(s)}return n}async function Xt(){let e=jt.filter(e=>!e.isIndex).map(e=>e.url),t=Nt.filter(e=>!jt.some(t=>t.parentUrl===e));await Yt([...e,...t])}async function Zt(t){Fe(!0),yt(null);try{await Ce(e,`gsc`,t),await ui(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,sitemapUrl:t}:e)),li({title:`Default sitemap updated`,detail:t,tone:`positive`,dedupeKey:`gsc:sitemap-default:${e}`,dedupeMode:`replace`})}catch(e){yt(e instanceof Error?e.message:`Failed to set the default sitemap`)}finally{Fe(!1)}}async function $t(t){try{await zt.mutateAsync({projectName:e,projectLabel:e,opts:t?{sitemapUrl:t}:void 0})}catch{}}async function en(){try{let t=(await n.fetchQuery({...Fi({client:Y,path:{name:e},query:{kind:Qt[`gsc-sync`],limit:1}}),staleTime:di}))[0];Et(t?.status===hr.failed&&t.error?`Last saved Search Console sync failed: ${fr(t.error)}`:null)}catch{Et(`Saved Search Console sync status is unavailable.`)}}async function tn(){me(!0),yt(null);try{let[t,a]=await Promise.all([i||!r?Promise.resolve(null):kn().catch(()=>null),n.fetchQuery({...oo({client:Y,path:{name:e}}),staleTime:di}).catch(()=>[])]);o(!!t?.google?.configured),c(a);let s=a.find(e=>e.connectionType===`gsc`);S(s?.propertyId??``),await Promise.all([!i&&s&&!s.propertyId?Bt(s):Promise.resolve(),!i&&s?en():Promise.resolve(),Vt(),Ht(),Gt(),Kt()])}finally{me(!1)}}(0,Z.useEffect)(()=>{u([]),ze(!1),Et(null),xt(null),wt(null)},[e]);let nn=(0,Z.useRef)(t);(0,Z.useEffect)(()=>{tn(),nn.current!==t&&(nn.current=t,N.refetch())},[e,t,r]),(0,Z.useEffect)(()=>{ie(0),R(null),H(e=>e.startDate||e.endDate?{...e,startDate:``,endDate:``}:e),B(e=>e+1),Ht()},[k]);let rn=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{rn.current?(ie(0),Ze.setPage(1),Vt(0)):rn.current=!0},[ne]);function an(e){let t=L===e?null:e;R(t),H(e=>({...e,startDate:t??``,endDate:t??``})),B(e=>e+1)}let on=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{on.current?(ie(0),Vt(0)):on.current=!0},[Ye]);async function sn(){if(!a)yt(`Google OAuth app credentials are not configured yet. Set them on the Settings page first.`);else{ge(!0),yt(null),wt(null);try{await jd(e,`gsc`,e=>{(async()=>{wt(e?`Google connected. Refreshing access…`:`Refreshing Google connection…`);try{await ui(n,`google`),await tn()}finally{wt(null)}})()})===`popup`&&wt(`Finish the Google consent flow in the popup. This page will refresh automatically.`)}catch(e){yt(e instanceof Error?e.message:`Failed to start OAuth flow`)}finally{ge(!1)}}}async function cn(){yt(null),wt(null);try{await ur(e,`gsc`),await ui(n,`google`),c(e=>e.filter(e=>e.connectionType!==`gsc`)),u([]),S(``)}catch(e){yt(e instanceof Error?e.message:`Failed to disconnect`)}}async function ln(){if(x){xe(!0),yt(null);try{await Wt(e,`gsc`,x),await ui(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,propertyId:x}:e)),li({title:`GSC property updated`,detail:`${e} is now linked to ${x}.`,tone:`positive`,dedupeKey:`gsc:property:${e}`,dedupeMode:`drop`})}catch(e){yt(e instanceof Error?e.message:`Failed to save GSC property`)}finally{xe(!1)}}}async function un(){yt(null),wt(null);try{await Rt.mutateAsync({projectName:e,projectLabel:e,opts:{days:parseInt(T,10)||void 0,full:D||void 0}}),await ui(n,`gsc`)}catch{}}async function dn(){if(C.trim()){Oe(!0),yt(null),wt(null);try{let t=await mr(e,C.trim());await ui(n,`gsc`),b(t),w(``),await Gt()}catch(e){yt(e instanceof Error?e.message:`Failed to inspect URL`)}finally{Oe(!1)}}}return(0,Q.jsxs)(`section`,{className:`page-section`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h2`,{children:`Google Search Console`})})}),Tt&&(0,Q.jsx)(`p`,{role:`status`,className:`mb-3 text-copy-14 text-caution`,children:Tt}),bt&&(0,Q.jsx)(`div`,{className:`mb-3 rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-label-14 text-caution-200`,children:(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-caution-100`,children:bt.title}),(0,Q.jsx)(`p`,{className:`mt-0.5 text-caution-200/90`,children:bt.message}),(mc(bt.enableUrl)||mc(bt.indexingApiUrl))&&(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-3`,children:[mc(bt.enableUrl)&&(0,Q.jsx)(`a`,{href:mc(bt.enableUrl),target:`_blank`,rel:`noopener noreferrer`,className:`text-label-14-strong text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50`,children:`Enable Search Console API ↗`}),mc(bt.indexingApiUrl)&&(0,Q.jsx)(`a`,{href:mc(bt.indexingApiUrl),target:`_blank`,rel:`noopener noreferrer`,className:`text-label-14-strong text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50`,children:`Enable Indexing API ↗`})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`text-caution-400 hover:text-caution-200`,onClick:()=>xt(null),children:`×`})]})}),vt&&(0,Q.jsxs)(`div`,{className:`mb-3 rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-label-14 text-negative`,children:[vt,(0,Q.jsx)(`button`,{type:`button`,className:`ml-2 text-negative-400 hover:text-negative-200`,onClick:()=>yt(null),children:`×`})]}),St&&(0,Q.jsxs)(`div`,{className:`mb-3 rounded-md border border-positive-800/40 bg-positive-950/20 px-3 py-2 text-label-14 text-positive`,children:[St,(0,Q.jsx)(`button`,{type:`button`,className:`ml-2 text-positive-400 hover:text-positive-200`,onClick:()=>wt(null),children:`×`})]}),pe?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading…`}):(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[Ot?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-label-12 text-muted`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full bg-positive-500`}),(0,Q.jsx)(`span`,{className:`text-neutral`,children:`Authorized`})]}),(0,Q.jsx)(`span`,{className:`text-mono-700`,children:`·`}),(0,Q.jsx)(`code`,{className:`text-secondary`,children:Ot.domain}),(0,Q.jsx)(`span`,{className:`text-mono-700`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Coverage measured`,` `,G?.lastInspectedAt?Jr(G.lastInspectedAt):`never`]}),!i&&(0,Q.jsx)(`button`,{type:`button`,className:`ml-auto text-muted transition-colors hover:text-negative-400`,onClick:ci(cn),children:`Disconnect`})]}):r?(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{children:`Domain authorization`})}),(0,Q.jsx)(J,{tone:a?`caution`:`negative`,children:a?`Ready to connect`:`App credentials missing`})]}),(0,Q.jsxs)(`div`,{className:`mt-3`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 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.`}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[a?(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:he,onClick:ci(sn),children:he?`Opening…`:`Connect Google Search Console`}):(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,asChild:!0,children:(0,Q.jsx)(U,{to:`/settings`,children:`Open Settings`})}),!a&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-muted`,children:`The same Google OAuth app credentials are shared across all projects.`})]})]})]}):(0,Q.jsx)(Cs,{className:`surface-card`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Md})}),(Ot||Lt)&&(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{children:`Search performance`}),(0,Q.jsx)(X,{text:`${zd(p?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${Pd.toLocaleString()} matching rows while the table shows 25 per page.`})]}),p?.window?.startDate&&p.window.endDate&&(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[p.window.startDate,` to `,p.window.endDate,(p.window.daysSinceLatestData??0)>0&&` · latest data ${p.window.daysSinceLatestData} day${p.window.daysSinceLatestData===1?``:`s`} ago`]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(Tu,{windows:Nd,value:k,onChange:e=>{A(e),ie(0),Ze.setPage(1)},label:`Search Console time period`,formatOption:e=>e===`all`?`All`:e}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Se,onClick:()=>{ie(0),Ze.setPage(1),Vt(0),Ht()},children:Se?`Loading…`:`Apply filters`})]})]}),p&&p.daily.length>0&&(()=>{let{totals:e,daily:t,trends:n,periodComparison:r}=p,i=t=>e[t]??null,a=Rd.flatMap(e=>{let t=N.data?.groups.find(t=>t.key===e.engine),n=t?.figures.find(e=>e.key===`indexed`);return t&&n?[{...e,label:t.label,figure:n}]:[]}),o=new Map(t.map(e=>[e.date,e])),s=new Map(a.map(e=>[e.key,new Map(e.figure.series.map(e=>[e.date,e.value]))])),c=t[t.length-1].date,l=a.filter(e=>P.includes(e.key)).map(e=>e.figure.series.at(-1)?.date).filter(e=>!!e).sort().at(-1),u=l&&l>c?l:c,d=Ct(t[0].date,u).map(e=>{let t={...o.get(e)??{date:e}};for(let n of a)t[n.key]=s.get(n.key)?.get(e)??null;return t}),f=[...Fd.filter(e=>P.includes(e.key)).map(e=>({dataKey:e.key,label:e.label,color:e.color,axisId:e.key,inverted:e.inverted,formatValue:e.format,trend:I?n?.[e.key]??null:null})),...a.filter(e=>P.includes(e.key)).map(e=>({dataKey:e.key,label:`${e.label} indexed pages`,color:e.color,axisId:e.key,formatValue:e=>e.toLocaleString(),connectNulls:!0}))],m={key:`performance`,label:`Google search`,basis:r?.comparable?`vs prior ${r.days} ${r.days===1?`day`:`days`}`:void 0,figures:Fd.map(e=>{let t=i(e.key);return{key:e.key,label:e.label,color:e.color,value:t===null?`—`:e.format(t),change:Ld(r,e.key,e.inverted),interactive:!0,disabled:t===null}})},h=a.length===0?null:{key:`indexed`,label:`Indexed pages`,basis:Bu(a.map(e=>e.figure)),figures:a.map(e=>({key:e.key,label:e.label,color:e.color,value:e.figure.value===null?`—`:e.figure.value.toLocaleString(),change:zu(e.figure.change,e.figure.unit),interactive:!0,disabled:e.figure.value===null}))};return(0,Q.jsxs)(`div`,{className:`mt-3`,children:[(0,Q.jsx)(qu,{name:`Search performance figures`,frame:`none`,mode:`compare`,groups:h?[m,h]:[m],selected:P,onSelect:e=>F(t=>t.includes(e)?t.length===1?t:t.filter(t=>t!==e):[...t,e]),chart:(0,Q.jsx)(Vr,{data:d,xKey:`date`,series:f,xTickFormatter:Hr,labelFormatter:Yr,onSelectX:an,selectedX:L}),legendExtra:(0,Q.jsxs)(`label`,{className:`flex min-h-9 cursor-pointer items-center gap-2 pointer-coarse:min-h-11`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,checked:I,onChange:e=>ee(e.target.checked)}),`Trend line`]})}),(0,Q.jsx)(`div`,{role:`group`,"aria-label":`Filter the table to a single day`,children:t.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-button-14 focus:text-strong`,"aria-pressed":L===e.date,onClick:()=>an(e.date),children:[Yr(e.date),`: `,e.clicks,` clicks, `,e.impressions,` impressions`]},e.date))}),L&&(0,Q.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 text-label-12`,children:[(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`Table showing `,Yr(L)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`text-link hover:underline`,onClick:()=>an(L),children:[`Show all `,e.days,` days`]})]}),e.position!==null&&(e.positionDays??e.days)<e.days&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[`Average position covers `,e.positionDays,` of `,e.days,` days. The rest have no property-level position recorded.`]}),(e.position===null||e.position===void 0)&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[`Average position needs a property-level sync. Run `,(0,Q.jsx)(`code`,{children:`canonry google sync`}),` to record it.`]})]})})(),(0,Q.jsxs)(`div`,{className:`mt-3 grid gap-2 lg:grid-cols-4`,children:[(0,Q.jsx)(`input`,{className:`rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 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:V.startDate,onChange:e=>H(t=>({...t,startDate:e.target.value}))}),(0,Q.jsx)(`input`,{className:`rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`date`,"aria-label":`End date`,title:`End date (inclusive).`,value:V.endDate,onChange:e=>H(t=>({...t,endDate:e.target.value}))}),(0,Q.jsx)(eu,{value:V.query,onChange:e=>H(t=>({...t,query:e})),label:`Filter search queries`,placeholder:`Contains query…`}),(0,Q.jsx)(eu,{value:V.page,onChange:e=>H(t=>({...t,page:e})),label:`Filter page URLs`,placeholder:`Contains page URL…`})]}),d.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Date`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Query`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Page`}),Object.values(Br).map(e=>(0,Q.jsx)(`th`,{className:`text-right`,"aria-sort":Ge?.key===e?Ge.dir===`asc`?`ascending`:`descending`:`none`,children:(0,Q.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:()=>{Ze.setPage(1),Ke(t=>t?.key===e?t.dir===`desc`?{key:e,dir:`asc`}:null:{key:e,dir:`desc`})},children:[ai[e],Ge?.key===e?Ge.dir===`desc`?` ↓`:` ↑`:``]})},e))]})}),(0,Q.jsx)(`tbody`,{children:Qe.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.date}),(0,Q.jsx)(`td`,{className:`max-w-xs truncate text-strong`,children:e.query}),(0,Q.jsx)(`td`,{className:`max-w-xs text-secondary`,children:(0,Q.jsx)(Ql,{value:e.page})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:e.clicks.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.impressions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Ut(e.ctr)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.position.toFixed(1)})]},`${e.date}:${e.query}:${e.page}:${t}`))})]})}),(0,Q.jsx)(tu,{page:le?Ze.page:Math.floor(re/25)+1,pageSize:25,visibleRows:Qe.length,totalRows:le?se:void 0,hasNextPage:le?void 0:ae,disabled:Se,itemLabel:le?`matches`:`rows`,onPageChange:e=>{if(le){Ze.setPage(e);return}let t=(e-1)*25;ie(t),Vt(t)}}),le&&se>=Pd?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Results are capped at `,Pd.toLocaleString(),`; narrow the filters to search beyond this set.`]}):null]}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No performance rows match the current filters yet.`})]}),(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{children:`Index coverage`}),(0,Q.jsx)(X,{text:`Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path.`})]})}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[G&&G.notIndexed.length>0&&(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:gt,onClick:()=>void Jt(),children:gt?`Requesting…`:`Request indexing (${G.notIndexed.length})`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Ae,onClick:()=>void Kt(!0),children:Ae?`Loading…`:`Reload saved coverage`})]})]}),G&&G.summary.total>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mt-6 flex flex-col items-center`,children:(()=>{let e=G.summary.indexedShare??0,t=G.summary.notIndexedShare??0,n=2*Math.PI*54,r=n*(1-e),i=n*t,a=n*e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`relative h-48 w-48`,children:[(0,Q.jsxs)(`svg`,{viewBox:`0 0 128 128`,className:`h-full w-full`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:Kr.trackSubtle,strokeWidth:`14`}),(0,Q.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:Qr.positiveDeep,strokeWidth:`14`,strokeDasharray:n,strokeDashoffset:r,strokeLinecap:`round`,transform:`rotate(-90 64 64)`,style:{transition:`stroke-dashoffset 0.6s ease`}}),G.summary.notIndexed>0&&(0,Q.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:Kr.textFaint,strokeWidth:`14`,strokeDasharray:`${i} ${n-i}`,strokeDashoffset:-a,transform:`rotate(-90 64 64)`,style:{transition:`stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease`}})]}),(0,Q.jsxs)(`div`,{className:`absolute inset-0 flex flex-col items-center justify-center`,children:[(0,Q.jsx)(`span`,{className:`text-heading-32 tabular-nums text-primary`,children:Ut(G.summary.indexedShare)}),(0,Q.jsx)(`span`,{className:`text-label-12 normal-case text-muted mt-0.5`,children:`Indexed`})]})]}),(0,Q.jsxs)(`div`,{className:`mt-4 flex items-center justify-center gap-8`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full bg-positive-500`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-24-strong tabular-nums text-primary`,children:G.summary.indexed.toLocaleString()}),(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Indexed`})]})]}),(0,Q.jsx)(`div`,{className:`h-8 w-px bg-mono-800`}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full bg-mono-500`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-24-strong tabular-nums text-primary`,children:G.summary.notIndexed.toLocaleString()}),(0,Q.jsxs)(`p`,{className:`text-label-12 normal-case text-muted`,children:[`Not indexed`,(G.reasonGroups??[]).length>0&&(0,Q.jsxs)(`span`,{className:`ml-1 text-faint`,children:[`· `,(G.reasonGroups??[]).length,` `,(G.reasonGroups??[]).length===1?`reason`:`reasons`]})]})]})]}),G.summary.deindexed>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`h-8 w-px bg-mono-800`}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full bg-negative-500`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-24-strong tabular-nums text-primary`,children:G.summary.deindexed.toLocaleString()}),(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Deindexed`})]})]})]})]})]})})()}),(0,Q.jsx)(vl,{id:We,label:`Coverage status`,value:He,onChange:e=>{Ue(e),nt(null)},className:`mt-3 flex border-b border-default`,tabClassName:`border-b-2 px-3 py-2 text-button-14 transition-colors`,activeTabClassName:`border-accent text-heading`,inactiveTabClassName:`border-transparent text-secondary hover:border-mono-600 hover:text-strong`,options:[[`indexed`,`Indexed (${G.indexed.length})`],[`notIndexed`,`Not Indexed (${G.notIndexed.length})`],[`deindexed`,`Deindexed (${G.deindexed.length})`]]}),(0,Q.jsxs)(`div`,{id:`${We}-panel`,role:`tabpanel`,"aria-labelledby":`${We}-${He}`,tabIndex:0,className:`mt-3 overflow-x-auto`,children:[He===`indexed`&&G.indexed.length>0&&(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Verdict`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Last Crawl`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Mobile`})]})}),(0,Q.jsx)(`tbody`,{children:ft.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.verdict??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.crawlTime?e.crawlTime.split(`T`)[0]:`—`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.isMobileFriendly===!0?`Yes`:e.isMobileFriendly===!1?`No`:`—`})]},e.id))})]}),He===`notIndexed`&&!tt&&(G.reasonGroups??[]).length>0&&(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Reason`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Pages`})]})}),(0,Q.jsx)(`tbody`,{children:(G.reasonGroups??[]).map(e=>(0,Q.jsxs)(`tr`,{className:`cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>nt(e.reason),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),nt(e.reason))},tabIndex:0,role:`button`,"aria-label":`View ${e.reason} pages`,children:[(0,Q.jsx)(`td`,{className:`text-strong`,children:e.reason}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.count})]},e.reason))})]}),He===`notIndexed`&&!tt&&(G.reasonGroups??[]).length===0&&G.notIndexed.length>0&&(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Indexing State`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Coverage`})]})}),(0,Q.jsx)(`tbody`,{children:pt.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.indexingState??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.coverageState??`Unknown`})]},e.id))})]}),He===`notIndexed`&&tt&&(()=>{let e=(G.reasonGroups??[]).find(e=>e.reason===tt);return e?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`flex items-center gap-2 mb-3`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`text-button-14 text-secondary hover:text-strong transition-colors`,onClick:()=>nt(null),children:[`←`,` Back to reasons`]})}),(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:e.reason}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[e.count,` affected page`,e.count===1?``:`s`]})]}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:gt,onClick:()=>void qt(e.urls.map(e=>e.url)),children:gt?`Requesting…`:`Request indexing (${e.count})`})]}),(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Last Crawl`}),(0,Q.jsx)(`th`,{className:`w-8`})]})}),(0,Q.jsx)(`tbody`,{children:ht.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.crawlTime?e.crawlTime.split(`T`)[0]:`—`}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`text-button-14 text-muted hover:text-strong transition-colors`,disabled:gt,onClick:()=>void qt([e.url]),title:`Request indexing`,children:`Index`})})]},e.id))})]})]}):null})(),He===`deindexed`&&G.deindexed.length>0&&(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Previous`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Current`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Detected`})]})}),(0,Q.jsx)(`tbody`,{children:mt.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.previousState}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.currentState}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.transitionDate.split(`T`)[0]})]},`${e.url}-${t}`))})]}),(He===`indexed`&&G.indexed.length===0||He===`notIndexed`&&!tt&&G.notIndexed.length===0||He===`deindexed`&&G.deindexed.length===0)&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No URLs in this category.`}),(0,Q.jsx)(tu,{page:ut,pageSize:Id,visibleRows:Math.min(Id,ct.length-dt),totalRows:ct.length,onPageChange:at,itemLabel:`URLs`})]}),(0,Q.jsxs)(`div`,{className:`mt-4 border-t border-default pt-3`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`flex w-full items-center justify-between text-left text-button-14 text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,"aria-expanded":Be,onClick:()=>Ve(e=>!e),children:[(0,Q.jsx)(`span`,{children:`Coverage history`}),(0,Q.jsx)(`span`,{children:Be?`Hide snapshots`:$e.length>0?`View ${$e.length} snapshots`:`View history`})]}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[`Current: `,G.summary.indexed.toLocaleString(),` indexed, `,G.summary.notIndexed.toLocaleString(),` not indexed.`,ot&&(0,Q.jsxs)(Q.Fragment,{children:[` Since the last snapshot: `,ot.indexed>=0?`+`:``,ot.indexed.toLocaleString(),` indexed, `,ot.notIndexed>=0?`+`:``,ot.notIndexed.toLocaleString(),` not indexed.`]})]}),Be&&(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:$e.length>0?(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Date`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Indexed`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Not indexed`})]})}),(0,Q.jsx)(`tbody`,{children:$e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.date}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:e.indexed.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.notIndexed.toLocaleString()})]},e.date))})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No saved coverage snapshots yet.`})})]})]}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:Ae?`Loading coverage data…`:`No coverage data yet. Inspect your sitemap to populate this view.`})]}),!i&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Dd,{engine:`Google`,data:At.isError?null:At.isPending&&At.fetchStatus!==`idle`?void 0:At.data?.google??null,loadError:At.isError?be(At.error):null,label:e=>Bd(e,Ot?.propertyId),canSubmit:kt,submitBlocked:Ot?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(X,{tone:`caution`,label:`Read-only access`,text:`Canonry's Google access can read Search Console but not submit sitemaps. Reconnect to allow submitting.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:ci(sn),children:`Reconnect`})]}):void 0,onSubmit:Yt,submitting:Ie,defaultUrl:Ot?.sitemapUrl??null,onSetDefault:e=>void Zt(e),settingDefault:Pe,onInspect:e=>void $t(e),inspecting:zt.isPending,notRead:(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Google's sitemap list arrives with the next Google sync. Refresh search data to read it now.`}),bulk:Mt.length>0?(0,Q.jsx)(Od,{label:Me?`Submitting ${Me.completed} of ${Me.total}`:`Resubmit all`,menuLabel:`Resubmit sitemaps to Google`,disabled:!kt||Ie,items:[{key:`primary`,label:It,description:Ft>0?`Google rereads every sitemap the index lists.`:`Each sitemap in the list, once.`,disabled:Pt.length===0,onSelect:()=>void Yt(Pt)},{key:`files`,label:`Resubmit all files`,description:`Every file inside each index, one by one.`,onSelect:()=>void Xt()}]}):void 0}),(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{children:`Inspect a URL`})})}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-col gap-2 lg:flex-row`,children:[(0,Q.jsx)(`input`,{className:`flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`url`,placeholder:`https://example.com/page`,value:C,onChange:e=>w(e.target.value),onKeyDown:e=>e.key===`Enter`&&void dn()}),(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:De||!Ot?.propertyId||!C.trim(),onClick:ci(dn),children:De?`Inspecting…`:`Inspect URL`})]}),y&&(0,Q.jsxs)(`div`,{className:`mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Indexing state`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:y.indexingState??`Unknown`})]}),(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Verdict`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:y.verdict??`Unknown`})]}),(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Mobile friendly`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:Er(y.isMobileFriendly??null)})]}),(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Last crawl`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:Jr(y.crawlTime)})]})]})]})]}),(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{children:`Inspection log`})}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Te,onClick:()=>void Gt(!0),children:Te?`Loading…`:`Refresh history`})]}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-col gap-2 lg:flex-row`,children:[(0,Q.jsxs)(`label`,{className:`flex flex-1 flex-col gap-1 text-label-13 text-secondary`,children:[`Filter exact URL`,(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`text`,placeholder:`https://example.com/page`,value:de,onChange:e=>fe(e.target.value)})]}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`self-end`,disabled:Te,onClick:()=>void Gt(!0),children:`Apply filter`})]}),h.length>0?(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Indexing`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Verdict`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Coverage`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Mobile`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Inspected`})]})}),(0,Q.jsx)(`tbody`,{children:h.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-neutral`,children:e.indexingState??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.verdict??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.coverageState??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:Er(e.isMobileFriendly??null)}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:Jr(e.inspectedAt)})]},e.id))})]})}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No inspection history yet.`})]}),(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{children:`Recent indexing losses`})})}),_.length>0?(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Previous`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Current`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Changed at`})]})}),(0,Q.jsx)(`tbody`,{children:_.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.previousState??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-neutral`,children:e.currentState??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:Jr(e.transitionDate)})]},`${e.url}:${e.transitionDate}`))})]})}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No deindexed transitions recorded.`})]})]}),Ot&&!i&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`border-t border-default pt-3`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 text-left`,onClick:()=>{Re||Bt(Ot),ze(e=>!e)},children:[(0,Q.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 ${Re?`rotate-90`:``}`,"aria-hidden":`true`,children:(0,Q.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`})}),(0,Q.jsx)(`span`,{className:`text-label-12 normal-case text-muted`,children:`Setup & Configuration`})]})}),Re&&(0,Q.jsx)(`div`,{className:`space-y-3`,children:(0,Q.jsxs)(`div`,{className:`grid gap-3 xl:grid-cols-2`,children:[(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`div`,{children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{children:`Pick the Search Console property`}),(0,Q.jsx)(X,{text:`The selected property is used for future syncs and URL inspections for this project.`})]})})}),(0,Q.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Q.jsx)(`label`,{className:`text-label-12 text-muted`,htmlFor:`gsc-property-${e}`,children:`Property URL`}),(0,Q.jsx)(`select`,{id:`gsc-property-${e}`,className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,value:x,disabled:_e||l.length===0,onChange:e=>S(e.target.value),children:l.length===0?(0,Q.jsx)(`option`,{value:``,children:_e?`Loading properties…`:`No properties available`}):l.map(e=>(0,Q.jsxs)(`option`,{value:e.siteUrl,children:[e.siteUrl,` · `,e.permissionLevel]},e.siteUrl))}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:_e,onClick:()=>void Bt(Ot,!0),children:_e?`Refreshing…`:`Refresh properties`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:!x||ye,onClick:ci(ln),children:ye?`Saving…`:`Save property`})]})]})]}),(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{children:`Import GSC performance data`})})}),(0,Q.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-[160px_1fr]`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`text-label-12 text-muted`,htmlFor:`gsc-sync-days-${e}`,children:`Days`}),(0,Q.jsx)(`input`,{id:`gsc-sync-days-${e}`,type:`number`,min:`1`,className:`mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,value:T,onChange:e=>E(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`flex items-center gap-2 rounded-md border border-default bg-surface-subtle px-3 py-2 text-label-14 text-neutral`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:D,onChange:e=>O(e.target.checked)}),`Replace existing imported rows for the requested range`]})]}),(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:Rt.isPending||!Ot.propertyId,onClick:ci(un),children:Rt.isPending?`Queueing…`:`Queue sync`}),!Ot.propertyId&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-caution-400`,children:`Select a Search Console property before queueing a sync.`})]})]})]})})]})]})]})}var Hd=[`7d`,`30d`,`90d`,`all`],Ud=10,Wd=[{key:`clicks`,label:`Clicks`,color:zr[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:zr[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:Qr.caution,format:e=>Ut(e)},{key:`position`,label:`Avg position`,color:zr[2],inverted:!0,format:e=>e.toFixed(1)}],Gd=`bing-indexed`,Kd=`Impression-weighted across the queries Bing names. Bing reports these per week, so the line moves weekly.`,qd=`Asks Bing directly. Counts against the shared Bing request limit for this key.`;function Jd(e){if(!e)return{kind:`note`,text:`No comparison period`};let t=e.difference.avgImpressionPosition,n=`vs prior ${e.days} ${e.days===1?`day`:`days`}`;return t===null?{kind:`note`,text:`No position in the prior ${e.days} days`}:t===0?{kind:`delta`,amount:`0`,direction:`flat`,tone:`neutral`,basis:n}:{kind:`delta`,amount:Se(t),direction:t>0?`up`:`down`,tone:t>0?`worse`:`better`,basis:n}}function Yd(e){return e==null?`—`:e.toFixed(1)}function Xd(e){return e==null?`—`:Math.round(e).toLocaleString()}function Zd(e){return e.replace(/^https?:\/\//,``).replace(/\/+$/,``)}function Qd(e,t){let n=t.replace(/\/+$/,``);return e.startsWith(n)?e.slice(n.length)||`/`:e}function $d(e,t){return e?.find(e=>e.kind===t)}function ef(e){let t=e?.payload;return t&&typeof t.dailyQuota==`number`&&typeof t.monthlyQuota==`number`?{dailyQuota:t.dailyQuota,monthlyQuota:t.monthlyQuota}:null}function tf(e){let t=e?.payload;return t&&typeof t.crawlBoostAvailable==`boolean`?{crawlBoostAvailable:t.crawlBoostAvailable,crawlBoostEnabled:t.crawlBoostEnabled===!0,crawlRate:Array.isArray(t.crawlRate)?t.crawlRate:[]}:null}function nf(e){return Array.isArray(e?.payload)?e.payload.filter(e=>typeof e==`object`&&!!e):null}var rf=new Set([`entityType`,`requestType`,`type`,`role`]);function af(e,t){return e==null||e===``?`—`:typeof e==`boolean`?e?`Yes`:`No`:typeof e==`number`?e.toLocaleString():typeof e==`string`?/^\d{4}-\d{2}-\d{2}(?:T00:00:00(?:\.000)?Z)?$/.test(e)?Yr(e.slice(0,10)):rf.has(t)&&/^[a-z]+(?:-[a-z]+)*$/.test(e)?e.charAt(0).toUpperCase()+e.slice(1).replaceAll(`-`,` `):e:JSON.stringify(e)}function of({status:e,right:t,children:n}){return(0,Q.jsxs)(`section`,{className:`page-section`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:`Bing Webmaster Tools`}),e]}),t]}),n]})}function sf({projectName:e,refreshNonce:t}){let n=z(),{canWrite:r,isAdmin:i}=si(),a=r&&!K()&&!rt(),[o,s]=(0,Z.useState)(),c=!i&&a&&o?.project===e?o.sites:void 0,l=W({...zi({client:Y,path:{name:e}}),staleTime:di}),u=l.data??null,d=W({...Ai({client:Y,path:{name:e}}),staleTime:di,enabled:!!(i&&a&&u?.connected&&!u.siteUrl)}),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{t>0&&(s(void 0),l.refetch())},[t]);async function v(){if(a&&(i||f.trim())){_(null);try{let t=await Vn(e,f.trim()||void 0);if(!i){let n=Vt(t.domain),r=t.availableSites.filter(e=>e.verified&&n!==null&&Vt(e.url)===n);s({project:e,sites:r})}p(``),await ui(n,`bing`)}catch(e){_(ws(e))}}}async function y(){_(null);try{await An(e),s(void 0),h(``),await ui(n,`bing`)}catch(e){_(ws(e))}}async function b(){if(a&&m.trim()){_(null);try{await hn(e,m.trim()),await ui(n,`bing`)}catch(e){_(ws(e))}}}if(l.isPending)return(0,Q.jsx)(of,{children:(0,Q.jsx)(Cs,{className:`surface-card`,children:(0,Q.jsx)(`div`,{className:`text-label-14 text-secondary`,children:`Loading Bing data…`})})});if(l.isError)return(0,Q.jsx)(of,{children:(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load the Bing connection: `,ws(l.error)]}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void l.refetch(),children:`Retry`})]})});if(!u?.connected)return(0,Q.jsx)(of,{children:(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{children:`Domain authorization`})}),(0,Q.jsx)(J,{tone:`caution`,children:`Not connected`})]}),a?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-neutral`,children:`Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing.`}),(0,Q.jsxs)(`div`,{className:`mt-3`,children:[(0,Q.jsx)(`label`,{className:`text-label-12 text-muted`,htmlFor:`bing-api-key`,children:`API Key`}),(0,Q.jsxs)(`div`,{className:`mt-1 flex flex-col gap-2 sm:flex-row sm:items-center`,children:[(0,Q.jsx)(`input`,{id:`bing-api-key`,type:`password`,className:`min-w-0 flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,placeholder:i?`Leave blank to use the key in Settings`:`Bing Webmaster Tools API key`,value:f,onChange:e=>p(e.target.value),onKeyDown:e=>{e.key===`Enter`&&v()}}),(0,Q.jsx)(fs,{size:`sm`,disabled:!i&&!f.trim(),onClick:ci(v),children:f.trim()||!i?`Connect`:`Connect with saved key`})]}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[`Get your API key from`,` `,(0,Q.jsx)(`a`,{href:`https://www.bing.com/webmasters/`,target:`_blank`,rel:`noopener noreferrer`,className:`text-secondary underline underline-offset-2 hover:text-neutral`,children:`Bing Webmaster Tools`})]})]})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-neutral`,children:`Bing Webmaster Tools is not connected for this project.`}),g&&(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-negative`,children:g})]})});if(!u.siteUrl){let e=c??(i&&a?d.data?.sites:void 0)??[],t=a&&!i&&!c;return(0,Q.jsx)(of,{children:(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{children:`Domain authorization`})}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(J,{tone:`positive`,children:`Connected`}),a&&(0,Q.jsx)(fs,{size:`sm`,variant:`ghost`,onClick:ci(y),children:`Disconnect`})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(`span`,{className:`h-2 w-2 rounded-full bg-positive-500`}),(0,Q.jsx)(`span`,{className:`text-label-14 text-strong`,children:`Authorized for this project domain`}),(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:u.domain})]}),(0,Q.jsx)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:`The API key is connected, but no Bing site is selected yet. A verified site is required for inspections and indexing requests.`})]}),(0,Q.jsxs)(`div`,{className:`grid gap-3 lg:grid-cols-2`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Registered domain`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:u.domain})]}),(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Last auth update`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:u.updatedAt?Jr(u.updatedAt):`—`})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Select site`}),a?t?(0,Q.jsxs)(`form`,{className:`mt-3 flex flex-col gap-2 lg:flex-row`,onSubmit:ci(async e=>{e.preventDefault(),await b()}),children:[(0,Q.jsx)(`input`,{type:`url`,required:!0,"aria-label":`Verified Bing site URL`,placeholder:Vt(u.domain)??`https://example.com/`,className:`min-w-0 flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong`,value:m,onChange:e=>h(e.target.value)}),(0,Q.jsx)(q,{type:`submit`,size:`sm`,disabled:!m.trim(),children:`Set Site`})]}):!c&&d.isError?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-negative`,children:ws(d.error)}):e.length>0?(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-col gap-2 lg:flex-row`,children:[(0,Q.jsxs)(`select`,{"aria-label":`Bing site`,className:`flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,value:m,onChange:e=>h(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Select a site…`}),e.map(e=>(0,Q.jsxs)(`option`,{value:e.url,children:[e.url,e.verified?` (verified)`:``]},e.url))]}),(0,Q.jsx)(q,{size:`sm`,disabled:!m,onClick:ci(b),children:`Set Site`})]}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-muted`,children:!c&&d.isPending?`Loading sites…`:`No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything.`}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-secondary`,children:`Ask a project administrator to select the verified site.`})]})]}),g&&(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-negative`,children:g})]})})}return(0,Q.jsx)(cf,{projectName:e,connection:u,siteUrl:u.siteUrl,onDisconnect:y,error:g})}function cf({projectName:e,connection:t,siteUrl:n,onDisconnect:r,error:i}){let[a,o]=(0,Z.useState)(`30d`),s=rt(),c={name:e},l=W({...Ji({client:Y,path:c,query:{window:a}}),staleTime:di,placeholderData:te,enabled:!s}),u=W({...Qi({client:Y,path:c}),staleTime:di,enabled:!s}),f=W({...na({client:Y,path:c}),staleTime:di,enabled:!s}),p=!s&&!!(l.data?.latestAvailableDate||u.data?.syncedAt||f.data?.syncedAt),m=!l.isPending&&!u.isPending&&!f.isPending,h=[l,u,f].find(e=>e.isError)?.error??null,g=nf($d(u.data?.snapshots,`blocked-urls`))?.length??0;return(0,Q.jsx)(of,{status:(0,Q.jsxs)(`p`,{className:`mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-label-13 text-secondary`,children:[(0,Q.jsx)(`span`,{className:`h-2 w-2 rounded-full bg-positive-500`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:`Connected`}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsx)(`span`,{className:`font-mono`,title:n,children:Zd(n)}),l.data?.latestAvailableDate&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Data through `,Yr(l.data.latestAvailableDate)]})]}),u.data?.syncedAt&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Synced `,Jr(u.data.syncedAt)]})]}),g>0&&(0,Q.jsx)(`span`,{className:`ml-1.5`,children:(0,Q.jsx)(X,{tone:`caution`,label:`${g} blocked URL${g===1?``:`s`}`,text:`Bing is keeping ${g===1?`one URL`:`${g} URLs`} out of its results, which also keeps ${g===1?`it`:`them`} out of Copilot answers. See Site settings.`})})]}),right:(0,Q.jsxs)(`details`,{className:`group`,children:[(0,Q.jsxs)(`summary`,{className:`flex cursor-pointer list-none items-center gap-1 rounded px-2 py-1 text-button-14 text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 [&::-webkit-details-marker]:hidden`,children:[`Connection `,(0,Q.jsx)(d,{className:`h-3.5 w-3.5 transition-transform group-open:rotate-180`,"aria-hidden":`true`})]}),(0,Q.jsxs)(`div`,{className:`material-base mt-2 space-y-2 p-3 text-copy-13`,children:[(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`span`,{className:`text-secondary`,children:`Domain`}),` `,(0,Q.jsx)(`span`,{className:`text-strong`,children:t.domain})]}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`span`,{className:`text-secondary`,children:`Site`}),` `,(0,Q.jsx)(`span`,{className:`font-mono text-strong`,children:n})]}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`span`,{className:`text-secondary`,children:`Last auth update`}),` `,(0,Q.jsx)(`span`,{className:`text-strong`,children:t.updatedAt?Jr(t.updatedAt):`—`})]}),!K()&&!s&&(0,Q.jsx)(fs,{size:`sm`,variant:`ghost`,onClick:ci(r),children:`Disconnect`})]})]}),children:(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[i&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-negative`,children:i}),!s&&(m&&!p&&h?(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load Bing data: `,ws(h)]}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>{l.refetch(),u.refetch(),f.refetch()},children:`Retry`})]}):m&&!p?(0,Q.jsx)(df,{projectName:e,loadedAt:u.dataUpdatedAt}):(0,Q.jsx)(ff,{projectName:e,siteUrl:n,range:a,onRangeChange:o})),(0,Q.jsx)(_f,{projectName:e,siteUrl:n,snapshots:u.data?.snapshots}),p&&(0,Q.jsx)(vf,{projectName:e,siteUrl:n}),p&&(0,Q.jsx)(hf,{projectName:e}),p&&(0,Q.jsx)(bf,{siteUrl:n,snapshots:u.data?.snapshots??[]})]})})}var lf=5e3;function uf(e){return e?.status===hr.queued||e?.status===hr.running}function df({projectName:e,loadedAt:t}){let n=z(),r=W({...Fi({client:Y,path:{name:e},query:{kind:Qt[`bing-sync`],limit:1}}),refetchInterval:e=>uf(e.state.data?.[0])?lf:!1,enabled:!K()}),i=r.data?.[0],a=uf(i),[o,s]=(0,Z.useState)(!1),c=i&&!a&&i.finishedAt?Date.parse(i.finishedAt):0;(0,Z.useEffect)(()=>{c>t&&Rs(n,Qt[`bing-sync`],e)},[c,t,n,e]);async function l(){s(!0);try{let t=await yr(e);Fs({id:t.id,projectId:t.projectId,kind:Qt[`bing-sync`],projectLabel:e,sourceAction:`bing-sync`}),await r.refetch(),li({title:`Bing sync started`,detail:`Search data appears here when it finishes.`,tone:`neutral`,dedupeKey:`bing:sync:${e}`,dedupeMode:`replace`})}catch(t){li({title:`Bing sync could not start`,detail:ws(t),tone:`negative`,dedupeKey:`bing:sync:${e}`,dedupeMode:`replace`})}finally{s(!1)}}let u=!a&&i?.status===hr.failed;return(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-strong`,children:`No Bing search data yet`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:a?`Bing sync ${i?.status===hr.queued?`queued`:`running`}. Search data appears here when it finishes.`:`It arrives with the daily refresh.`}),u&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-negative`,children:[`Last sync failed`,i?.error?`: ${fr(i.error)}`:`.`]}),!K()&&(0,Q.jsx)(fs,{className:`mt-3`,size:`sm`,disabled:a||o,onClick:ci(l),children:a||o?`Sync running…`:u?`Try the sync again`:`Sync Bing data now`})]})}function ff({projectName:e,siteUrl:t,range:n,onRangeChange:r}){let i={name:e},a=W({...Ji({client:Y,path:i,query:{window:n}}),staleTime:di,placeholderData:te}),o=W({...Ja({client:Y,path:i,query:{window:n,groupBy:`week`}}),staleTime:di,placeholderData:te}),s=W({...To({client:Y,path:i,query:{surface:`index-coverage`,window:n}}),staleTime:di,placeholderData:te}),[c,l]=(0,Z.useState)([`clicks`,`impressions`]),[u,d]=(0,Z.useState)(!0),f=a.data,p=s.data?.groups.find(e=>e.key===`bing`)?.figures.find(e=>e.key===`indexed`)??null,m=f?.periodComparison??null,h;if(a.isPending)h=(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:`Loading Bing search data…`});else if(a.isError||!f)h=(0,Q.jsxs)(`p`,{className:`mt-3 text-copy-14 text-negative`,children:[`Could not load Bing search data: `,ws(a.error)]});else{let r=o.data?.totals?.avgImpressionPosition??null,i=Jd(o.data?.comparison),s=m?.comparable?`vs prior ${m.days} ${m.days===1?`day`:`days`}`:void 0,g={key:`performance`,label:`Bing search`,basis:s!==void 0&&(i.kind!==`delta`||i.basis===s)?s:void 0,figures:Wd.map(e=>{if(e.key===`position`)return{key:e.key,label:e.label,help:Kd,color:e.color,value:r===null?`—`:e.format(r),change:i,interactive:!0,disabled:r===null};let t=f.totals[e.key];return{key:e.key,label:e.label,color:e.color,value:e.format(t),change:Ld(m,e.key,!1),interactive:!0,disabled:f.rows.length===0}})},_=p?{key:`indexed`,label:`Indexed pages`,basis:Bu([p]),figures:[{key:Gd,label:`Bing`,color:zr[6],value:p.value===null?`—`:p.value.toLocaleString(),change:zu(p.change,p.unit),interactive:!0,disabled:p.value===null}]}:null,v=f.rows[0]?.date,y=f.rows.at(-1)?.date,b=f.earliestAvailableDate,x=f.window.startDate&&b&&f.window.startDate>b?f.window.startDate:b??f.window.startDate??v,S=f.window.endDate??y,C=new Map(f.rows.map(e=>[e.date,e])),w=new Map((o.data?.weekly??[]).map(e=>[e.date,e.avgImpressionPosition])),T=new Map((p?.series??[]).map(e=>[e.date,e.value])),E=x&&S?Ct(x,S).map(e=>{let t=C.get(e);return{date:e,clicks:t?.clicks??0,impressions:t?.impressions??0,ctr:t&&t.impressions>0?t.ctr:null,position:w.get(e)??null,[Gd]:T.get(e)??null}}):[],D=[...Wd.filter(e=>c.includes(e.key)).map(e=>({dataKey:e.key,label:e.label,color:e.color,axisId:e.key,inverted:`inverted`in e?e.inverted:void 0,formatValue:e.format,trend:u&&e.key!==`position`?f.trends[e.key]:null,connectNulls:e.key===`position`})),...c.includes(Gd)&&p?[{dataKey:Gd,label:`Bing indexed pages`,color:zr[6],axisId:Gd,formatValue:e=>e.toLocaleString(),connectNulls:!0}]:[]];h=(0,Q.jsxs)(`div`,{className:`mt-3`,children:[(0,Q.jsx)(qu,{name:`Bing search figures`,frame:`none`,mode:`compare`,groups:_?[g,_]:[g],selected:c,refreshing:a.isFetching&&a.isPlaceholderData,onSelect:e=>l(t=>t.includes(e)?t.length===1?t:t.filter(t=>t!==e):[...t,e]),chart:E.length>0?(0,Q.jsx)(Vr,{data:E,xKey:`date`,series:D,xTickFormatter:Hr,labelFormatter:Yr,ariaLabel:`Daily Bing search figures`}):void 0,emptyChartMessage:`Bing reported no search traffic in this window.`,legendExtra:(0,Q.jsxs)(`label`,{className:`flex min-h-9 cursor-pointer items-center gap-2 pointer-coarse:min-h-11`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,checked:u,onChange:e=>d(e.target.checked)}),`Trend line`]})}),(0,Q.jsx)(pf,{projectName:e,siteUrl:t,range:n})]})}return(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{children:`Search performance`}),(0,Q.jsx)(X,{text:`${zd(m)} Clicks, impressions and CTR are Bing's daily totals for the whole site. The queries and pages below are the ones Bing names, reported per week, so they do not add up to the site total.`})]}),f?.window.startDate&&f.window.endDate&&(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[Yr(f.window.startDate),` to `,Yr(f.window.endDate)]})]}),(0,Q.jsx)(Tu,{windows:Hd,value:n,onChange:r,label:`Bing time period`,formatOption:e=>e===`all`?`All`:e})]}),h]})}function pf({projectName:e,siteUrl:t,range:n}){let[r,i]=(0,Z.useState)(`queries`),a=(0,Z.useId)(),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(void 0),[u,f]=(0,Z.useState)(1),[p,h]=(0,Z.useState)(null),g={name:e},_=(u-1)*Ud;(0,Z.useEffect)(()=>{let e=o.trim()||void 0;if(e===void 0){l(void 0);return}let t=setTimeout(()=>l(e),300);return()=>clearTimeout(t)},[o]);let v=W({...Ja({client:Y,path:g,query:{window:n,query:c,limit:Ud,offset:_}}),staleTime:di,placeholderData:te,enabled:r===`queries`}),y=W({...vi({client:Y,path:g,query:{window:n,page:c,limit:Ud,offset:_}}),staleTime:di,placeholderData:te,enabled:r===`pages`}),b=r===`queries`?v:y,x=r===`queries`?(v.data?.rows??[]).map(e=>({key:e.query,...e})):(y.data?.rows??[]).map(e=>({key:e.page,...e})),S=b.data?.totalMatching??0,C=r===`queries`?`Query`:`Page`;return(0,Z.useEffect)(()=>{f(1),h(null)},[r,n,c]),(0,Q.jsxs)(`div`,{className:`mt-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3 border-b border-base`,children:[(0,Q.jsx)(vl,{id:a,label:`Bing search rows`,value:r,onChange:i,className:`flex gap-1`,tabClassName:`border-b-2 px-3 py-1.5 text-button-14 transition-colors`,activeTabClassName:`border-mono-200 text-strong`,inactiveTabClassName:`border-transparent text-muted hover:text-neutral`,options:[[`queries`,`Queries`],[`pages`,`Pages`]]}),(0,Q.jsx)(eu,{className:`mb-1.5 w-full sm:w-64`,value:o,onChange:s,label:r===`queries`?`Filter Bing queries`:`Filter Bing pages`,placeholder:r===`queries`?`Contains query…`:`Contains page URL…`})]}),(0,Q.jsxs)(`div`,{id:`${a}-panel`,role:`tabpanel`,"aria-labelledby":`${a}-${r}`,tabIndex:0,children:[b.isError?(0,Q.jsxs)(`p`,{className:`mt-3 text-copy-14 text-negative`,children:[`Could not load Bing `,r,`: `,ws(b.error)]}):(0,Q.jsx)(`div`,{className:`mt-2 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`w-7`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,Q.jsx)(`th`,{className:`text-left`,children:C}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Clicks`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Impressions`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`CTR`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Position`})]})}),(0,Q.jsxs)(`tbody`,{children:[x.length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:6,className:`py-6 text-center text-secondary`,children:b.isPending?`Loading…`:c?`No ${r} match "${c}" in this window.`:`Bing named no ${r} in this window.`})}),x.map(i=>{let a=p===i.key;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":a,"aria-label":`${a?`Hide`:`Show`} details for ${i.key}`,className:`rounded p-0.5 text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>h(a?null:i.key),children:a?(0,Q.jsx)(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(m,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})}),(0,Q.jsx)(`td`,{className:`max-w-md text-strong`,children:r===`pages`?(0,Q.jsx)(Ql,{value:Qd(i.key,t),title:i.key,className:`font-mono text-label-13`}):(0,Q.jsx)(`span`,{className:`block truncate`,title:i.key,children:i.key})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:i.clicks.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:i.impressions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Ut(i.ctr)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Yd(i.avgImpressionPosition)})]}),a&&(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{colSpan:5,className:`pb-4`,children:(0,Q.jsx)(mf,{projectName:e,siteUrl:t,range:n,tab:r,rowKey:i.key})})]})]},i.key)})]})]})}),(0,Q.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Q.jsx)(tu,{page:u,pageSize:Ud,visibleRows:x.length,totalRows:S,disabled:b.isFetching,itemLabel:r,onPageChange:f})})]})]})}function mf({projectName:e,siteUrl:t,range:n,tab:r,rowKey:i}){let a={name:e},[o,s]=(0,Z.useState)(!1),c=W({...Ja({client:Y,path:a,query:{window:n,query:i,match:`exact`,groupBy:`week`}}),staleTime:di,enabled:r===`queries`}),l=W({...vi({client:Y,path:a,query:{window:n,page:i,match:`exact`,groupBy:`week`}}),staleTime:di,enabled:r===`pages`}),u=W({...Xi({client:Y,path:a,query:{query:i}}),staleTime:di,retry:!1,enabled:o&&r===`queries`}),d=W({...Za({client:Y,path:a,query:{page:i}}),staleTime:di,retry:!1,enabled:o&&r===`pages`}),f=(r===`queries`?c.data?.weekly:l.data?.weekly)??[],p=r===`queries`?u:d,m=p.data?.rows??[],h=r===`queries`?`Pages`:`Queries`;return(0,Q.jsxs)(`div`,{className:`grid gap-6 lg:grid-cols-[minmax(260px,1fr)_minmax(280px,1.4fr)]`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`mb-1.5 text-label-13-strong text-strong`,children:`By week`}),(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-13`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Week`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Clicks`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Impr.`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Pos.`})]})}),(0,Q.jsxs)(`tbody`,{children:[f.length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`py-3 text-secondary`,children:(r===`queries`?c:l).isPending?`Loading…`:`No weeks in this window.`})}),f.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tabular-nums`,children:Yr(e.date)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums`,children:e.clicks.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.impressions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Yd(e.avgImpressionPosition)})]},e.date))]})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`mb-1.5 flex items-baseline gap-2 text-label-13-strong text-strong`,children:[h,` for this `,r===`queries`?`query`:`page`,p.isSuccess&&(0,Q.jsx)(`span`,{className:`text-label-12 text-secondary`,children:`from Bing, by week`})]}),!o&&(K()?(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Not available here.`}):(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>s(!0),children:[(0,Q.jsx)(k,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Load `,h.toLowerCase(),` from Bing`]}),(0,Q.jsx)(X,{label:`Live`,text:qd})]})),o&&p.isPending&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Asking Bing…`}),o&&p.isError&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(X,{tone:`caution`,label:`Bing refused this read`,text:`${ws(p.error)} Nothing was stored.`}),(0,Q.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>void p.refetch(),children:[(0,Q.jsx)(_,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Retry`]})]}),o&&p.isSuccess&&(m.length===0?(0,Q.jsxs)(`p`,{className:`text-copy-13 text-secondary`,children:[`Bing named no `,h.toLowerCase(),` for this `,r===`queries`?`query`:`page`,`.`]}):(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-13`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Week`}),(0,Q.jsx)(`th`,{className:`text-left`,children:r===`queries`?`Page`:`Query`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Clicks`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Impr.`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Pos.`})]})}),(0,Q.jsx)(`tbody`,{children:m.map((e,n)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.date?Yr(e.date):`—`}),(0,Q.jsx)(`td`,{className:`max-w-xs`,children:r===`queries`?(0,Q.jsx)(Ql,{value:Qd(e.key,t),title:e.key,className:`font-mono`}):(0,Q.jsx)(`span`,{className:`block truncate`,title:e.key,children:e.key})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums`,children:e.clicks.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.impressions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Yd(e.avgImpressionPosition)})]},`${e.date}:${e.key}:${n}`))})]}))]})]})}function hf({projectName:e}){let t=W({...ta({client:Y,path:{name:e}}),staleTime:di}),[n,r]=(0,Z.useState)(null),i=t.data?.market,a=t.data?.rows??[];return(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`h3`,{children:`Search demand`}),i&&(0,Q.jsx)(X,{label:`${i.country.toUpperCase()} · ${i.language}`,text:`Exact-match Bing searches per week for your tracked queries, averaged over the weeks stored. This is demand, not your traffic. Refreshed weekly.`})]}),t.isError?(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load search demand: `,ws(t.error)]}):(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`w-7`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Tracked query`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Searches / week`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Latest week`})]})}),(0,Q.jsxs)(`tbody`,{children:[a.length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`py-6 text-center text-secondary`,children:t.isPending?`Loading…`:`No search demand stored yet. It is read weekly for tracked queries.`})}),a.map(t=>{let i=n===t.query;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":i,"aria-label":`${i?`Hide`:`Show`} weekly searches for ${t.query}`,className:`rounded p-0.5 text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>r(i?null:t.query),children:i?(0,Q.jsx)(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(m,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})}),(0,Q.jsx)(`td`,{className:`text-strong`,children:t.query}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:Xd(t.avgWeeklyImpressions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Xd(t.latestImpressions)})]}),i&&(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{colSpan:3,className:`pb-4`,children:(0,Q.jsx)(gf,{projectName:e,query:t.query})})]})]},t.query)})]})]})})]})}function gf({projectName:e,query:t}){let n=W({...ta({client:Y,path:{name:e},query:{query:t}}),staleTime:di}),r=n.data?.history??[];return n.isPending?(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Loading…`}):r.length===0?(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`No weeks stored.`}):(0,Q.jsxs)(`table`,{className:`data-table w-full max-w-md text-label-13`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Week`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Exact`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Broad`})]})}),(0,Q.jsx)(`tbody`,{children:r.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tabular-nums`,children:Yr(e.date)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums`,children:e.impressions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.broadImpressions.toLocaleString()})]},e.date))})]})}function _f({projectName:e,siteUrl:t,snapshots:n}){let r=z(),i=rt(),a={name:e},o=W({...fa({client:Y,path:a}),staleTime:di}),s=W({...Ei({client:Y,path:a}),staleTime:di}),c=W({...Oi({client:Y,path:a,query:{days:`30`}}),staleTime:di,enabled:!i}),[l,u]=(0,Z.useState)(`not-indexed`),d=(0,Z.useId)(),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),b=ef($d(n,`url-submission-quota`)),x=o.data?.summary,S=c.data?.rows[0],C=o.data?.notIndexed??[],w=o.data?.unknown??[],T=o.data?.indexed??[],E=s.data??[];async function D(t,n){p(!0),y(null);try{let{succeeded:i,failed:a,total:o}=(await yn(e,t)).summary;li({title:a===0?`Sent to Bing`:`Some URLs were not sent`,detail:a===0?`${i} of ${o} URL${o===1?``:`s`} submitted.`:`${i} of ${o} submitted, ${a} not sent.`,tone:a===0?`positive`:`caution`,dedupeKey:`bing:indexing:${e}:${n}`,dedupeMode:`replace`}),await ui(r,`bing`)}catch(t){let r=ws(t);y(r),li({title:`Bing submission failed`,detail:r,tone:`negative`,dedupeKey:`bing:indexing:${e}:${n}`,dedupeMode:`replace`})}finally{p(!1)}}async function O(){if(m.trim()){y(null);try{let t=await G(e,m.trim());_(t),await ui(r,`bing`)}catch(e){y(ws(e))}}}let k=x?[{label:`Indexed`,value:x.indexed.toLocaleString()},{label:`Not in index`,value:(x.notIndexed+(x.unknown??0)).toLocaleString(),tooltip:`Pages Bing has not confirmed in its index, including those with an unknown status.`},{label:`Status unknown`,value:(x.unknown??0).toLocaleString()},{label:`Coverage`,value:Ut(x.percentage,Je.percent)}]:[],A=$l({rows:l===`not-indexed`?C:l===`unknown`?w:l===`indexed`?T:[],pageSize:Ud}),j=$l({rows:E,pageSize:Ud}),M=$l({rows:c.data?.rows??[],pageSize:Ud}),N=[{key:`not-indexed`,label:`Not indexed (${C.length})`},{key:`unknown`,label:`Status unknown (${w.length})`},{key:`indexed`,label:`Indexed (${T.length})`},{key:`inspections`,label:`Inspections (${E.length})`}];i||N.push({key:`crawl`,label:`Crawl by day`});let P=!K()&&!i&&(l===`not-indexed`||l===`unknown`)&&(l===`not-indexed`?C.length:w.length)>0;return(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,Q.jsx)(`h3`,{children:i?`Index coverage`:`Index and crawl`}),i&&(0,Q.jsx)(X,{text:`This demo includes saved index coverage and URL inspections.`}),S&&S.crawlErrors>0&&(0,Q.jsx)(X,{tone:`caution`,label:`${S.crawlErrors.toLocaleString()} crawl error${S.crawlErrors===1?``:`s`}`,text:`Bingbot got errors from ${S.crawlErrors===1?`one URL`:`${S.crawlErrors.toLocaleString()} URLs`} on ${Yr(S.date)}. Crawl by day has the codes.`})]}),(0,Q.jsx)(`p`,{className:`text-copy-13 text-muted`,children:o.data?.lastInspectedAt?`Last inspected ${Jr(o.data.lastInspectedAt)}`:`No inspection history yet`})]}),(0,Q.jsx)(`div`,{className:`space-y-4`,children:k.length>0?(0,Q.jsx)(nd,{label:`Bing index coverage`,items:k}):(0,Q.jsx)(`p`,{className:`text-copy-13 text-muted`,children:i?`No saved coverage data.`:`No coverage data yet. Inspect URLs to build coverage data.`})}),(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-end justify-between gap-3 border-b border-base`,children:[(0,Q.jsx)(vl,{id:d,label:`Bing index and crawl lists`,value:l,onChange:e=>{u(e),A.setPage(1)},className:`flex flex-wrap gap-1`,tabClassName:`border-b-2 px-3 py-1.5 text-button-14 transition-colors`,activeTabClassName:`border-mono-200 text-strong`,inactiveTabClassName:`border-transparent text-muted hover:text-neutral`,options:N.map(e=>[e.key,e.label])}),P&&(0,Q.jsxs)(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[b&&(0,Q.jsxs)(`span`,{className:`text-label-13 text-secondary`,children:[b.dailyQuota.toLocaleString(),` submissions left today`]}),(0,Q.jsx)(fs,{size:`sm`,variant:`outline`,disabled:f,onClick:ci(()=>D({allUnindexed:!0},`all`)),children:f?`Submitting…`:`Submit all to Bing`})]})]}),v&&(0,Q.jsx)(`p`,{className:`mt-2 text-copy-13 text-negative`,children:v}),(0,Q.jsxs)(`div`,{id:`${d}-panel`,role:`tabpanel`,"aria-labelledby":`${d}-${l}`,tabIndex:0,className:`mt-2 overflow-x-auto`,children:[(l===`not-indexed`||l===`unknown`||l===`indexed`)&&(()=>{let e=l!==`indexed`&&!K()&&!i;return(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,Q.jsx)(`th`,{className:`text-right`,children:l===`not-indexed`?`HTTP`:`Last crawled`}),e&&(0,Q.jsx)(`th`,{className:`text-right`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Action`})})]})}),(0,Q.jsxs)(`tbody`,{children:[A.totalRows===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:e?3:2,className:`py-6 text-center text-secondary`,children:o.isPending?`Loading…`:`None.`})}),A.rows.map(n=>(0,Q.jsxs)(`tr`,{className:`group`,children:[(0,Q.jsx)(`td`,{className:`max-w-lg`,children:(0,Q.jsx)(Ql,{value:Qd(n.url,t),title:n.url,className:`font-mono text-label-13 text-neutral`})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:l===`not-indexed`?n.httpCode??`—`:n.lastCrawledDate?Jr(n.lastCrawledDate):`—`}),e&&(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsx)(`div`,{className:`opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 pointer-coarse:opacity-100`,children:(0,Q.jsx)(fs,{size:`sm`,variant:`ghost`,disabled:f,onClick:ci(()=>D({urls:[n.url]},n.url)),children:`Submit`})})})]},n.id))]})]})})(),(l===`not-indexed`||l===`unknown`||l===`indexed`)&&(0,Q.jsx)(tu,{page:A.page,pageSize:Ud,visibleRows:A.rows.length,totalRows:A.totalRows,onPageChange:A.setPage,itemLabel:`URLs`}),l===`inspections`&&(0,Q.jsxs)(`div`,{className:`space-y-3 pt-2`,children:[!K()&&!i&&(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 lg:flex-row`,children:[(0,Q.jsx)(`input`,{type:`text`,"aria-label":`URL to inspect`,className:`flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,placeholder:`URL to inspect`,value:m,onChange:e=>h(e.target.value),onKeyDown:e=>{e.key===`Enter`&&O()}}),(0,Q.jsx)(fs,{size:`sm`,disabled:!m.trim(),onClick:ci(O),children:`Inspect`})]}),g&&(0,Q.jsxs)(`div`,{className:`space-y-1 text-label-13`,children:[(0,Q.jsx)(`div`,{className:`text-label-13-strong text-strong`,children:g.url}),(0,Q.jsxs)(`div`,{className:`text-secondary`,children:[`In index: `,(0,Q.jsx)(`span`,{className:g.inIndex?`text-positive`:`text-negative`,children:g.inIndex?`Yes`:`No`}),` · `,`HTTP: `,g.httpCode??`—`,` · `,`Crawled: `,g.lastCrawledDate??`—`]})]}),(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Index`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`HTTP`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Inspected`})]})}),(0,Q.jsxs)(`tbody`,{children:[E.length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`py-6 text-center text-secondary`,children:s.isPending?`Loading…`:`No inspections yet.`})}),j.rows.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-lg`,children:(0,Q.jsx)(Ql,{value:Qd(e.url,t),title:e.url,className:`font-mono text-label-13 text-neutral`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:e.inIndex?`positive`:`negative`,children:e.inIndex?`Yes`:`No`})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.httpCode??`—`}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Jr(e.inspectedAt)})]},e.id))]})]}),(0,Q.jsx)(tu,{page:j.page,pageSize:Ud,visibleRows:j.rows.length,totalRows:j.totalRows,onPageChange:j.setPage,itemLabel:`inspections`})]}),l===`crawl`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-13`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Day`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Crawled`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Errors`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`In index`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`2xx`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`301`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`302`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`4xx`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`5xx`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Other`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Robots.txt`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Timeouts`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`DNS`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Malware`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Inbound links`})]})}),(0,Q.jsxs)(`tbody`,{children:[(c.data?.rows??[]).length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:15,className:`py-6 text-center text-secondary`,children:c.isPending?`Loading…`:`No crawl stats stored yet.`})}),M.rows.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tabular-nums`,children:Yr(e.date)}),[e.crawledPages,e.crawlErrors,e.inIndex,e.code2xx,e.code301,e.code302,e.code4xx,e.code5xx,e.allOtherCodes,e.blockedByRobotsTxt,e.connectionTimeout,e.dnsFailures,e.containsMalware,e.inLinks].map((e,t)=>(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.toLocaleString()},t))]},e.date))]})]}),(0,Q.jsx)(tu,{page:M.page,pageSize:Ud,visibleRows:M.rows.length,totalRows:M.totalRows,onPageChange:M.setPage,itemLabel:`days`})]})]})]})}function vf({projectName:e,siteUrl:t}){let{canWrite:n}=si(),r=W({...So({client:Y,path:{name:e}}),staleTime:di}),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1);async function c(t){a(!0);let n=[];try{for(let r of t)await Gt(e,r),n.push(r);let r=n.length;li({title:r===1?`Sent to Bing`:`${r} sitemaps sent to Bing`,detail:`Bing reads it soon. A new sitemap shows in the list after the next Bing sync.`,tone:`positive`,dedupeKey:`bing:submit-sitemap:${e}`,dedupeMode:`replace`})}catch(r){li({title:n.length>0?`Bing took ${n.length} of ${t.length}`:`Bing did not take the sitemap`,detail:ws(r),tone:`negative`,dedupeKey:`bing:submit-sitemap:${e}`,dedupeMode:`replace`})}finally{a(!1)}return n}async function l(t){s(!0);try{await vt(e,{sitemapUrl:t}),li({title:`Checking sitemap URLs in Bing`,detail:`Coverage updates when the check finishes.`,tone:`neutral`,dedupeKey:`bing:inspect-sitemap:${e}`,dedupeMode:`replace`})}catch(t){li({title:`Sitemap check could not start`,detail:ws(t),tone:`negative`,dedupeKey:`bing:inspect-sitemap:${e}`,dedupeMode:`replace`})}finally{s(!1)}}return(0,Q.jsx)(Dd,{engine:`Bing`,data:r.isError?null:r.isPending?void 0:r.data.bing,loadError:r.isError?ws(r.error):null,label:e=>Qd(e,t),canSubmit:n,onSubmit:c,submitting:i,onInspect:e=>void l(e),inspecting:o,notRead:(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Bing's sitemap list arrives with the next Bing sync.`}),readOnly:K()})}var yf=`Bing shows this only to the site owner key. Not a failure.`;function bf({siteUrl:e,snapshots:t}){let n=ef($d(t,`url-submission-quota`)),r=ef($d(t,`content-submission-quota`)),i=tf($d(t,`crawl-settings`)),a=[{kind:`blocked-urls`,label:`Blocked URLs`,columns:[{key:`url`,label:`URL`},{key:`entityType`,label:`Type`},{key:`requestType`,label:`Removal`},{key:`daysToExpire`,label:`Days left`},{key:`date`,label:`Added`}]},{kind:`page-preview-blocks`,label:`Preview blocks`,columns:[]},{kind:`deep-link-blocks`,label:`Sitelink blocks`,columns:[]},{kind:`query-parameters`,label:`URL parameters`,columns:[{key:`parameter`,label:`Parameter`},{key:`isEnabled`,label:`Enabled`},{key:`source`,label:`Source`},{key:`date`,label:`Added`}]},{kind:`country-region-settings`,label:`Geo-targeting`,columns:[{key:`url`,label:`URL`},{key:`countryCode`,label:`Country`},{key:`type`,label:`Applies to`},{key:`date`,label:`Added`}]},{kind:`crawl-issues`,label:`Crawl issues`,columns:[{key:`url`,label:`URL`},{key:`httpCode`,label:`HTTP`},{key:`issues`,label:`Issues`},{key:`inLinks`,label:`Inbound links`}]},{kind:`fetched-urls`,label:`Fetch as Bingbot`,columns:[{key:`url`,label:`URL`},{key:`fetched`,label:`Fetched`},{key:`expired`,label:`Expired`},{key:`date`,label:`Requested`}]},{kind:`connected-pages`,label:`Connected pages`,columns:[]},{kind:`site-roles`,label:`Users and roles`,columns:[{key:`email`,label:`User`},{key:`role`,label:`Role`},{key:`expired`,label:`Expired`},{key:`date`,label:`Added`}]}];function o(e,t){if(!e)return{value:`—`,help:`Not read yet.`};if(e.status===`unauthorized`)return{value:`Owner key needed`,help:yf};if(e.status===`failed`&&t===null)return{value:`—`,help:`The last read failed: ${e.error??`no detail`}`};let n=t?.length??0;return{value:n===0?`None`:n.toLocaleString()}}let s=a.map(({kind:n,label:r,columns:i})=>{let a=$d(t,n),s=nf(a),{value:c,help:l}=o(a,s),u=a?.status===`failed`&&s!==null,d=i.length>0||!s?i:[...new Set(s.flatMap(e=>Object.keys(e)))].filter(e=>e!==`__type`).map(e=>({key:e,label:e}));return(0,Q.jsx)(xf,{label:r,value:c,help:l,note:u?`from an earlier sync`:void 0,children:s&&s.length>0?(0,Q.jsxs)(`div`,{className:`overflow-x-auto`,children:[u&&(0,Q.jsxs)(`p`,{className:`mb-2 text-copy-13 text-caution`,children:[`The last read failed, so these rows are from an earlier sync: `,a?.error??`no detail`]}),(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-13`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsx)(`tr`,{children:d.map(e=>(0,Q.jsx)(`th`,{className:`text-left`,children:e.label},e.key))})}),(0,Q.jsx)(`tbody`,{children:s.map((t,n)=>(0,Q.jsx)(`tr`,{children:d.map(n=>{let r=t[n.key]??t[n.key.charAt(0).toUpperCase()+n.key.slice(1)];return(0,Q.jsx)(`td`,{className:n.key.toLowerCase()===`url`?`max-w-md`:`text-secondary`,children:n.key.toLowerCase()===`url`&&typeof r==`string`?(0,Q.jsx)(Ql,{value:Qd(r,e),title:r,className:`font-mono text-neutral`}):af(r,n.key)},n.key)})},n))})]})]}):void 0},n)}),c=e=>s[a.findIndex(t=>t.kind===e)],l=e=>e?`${e.dailyQuota.toLocaleString()} today \u00b7 ${e.monthlyQuota.toLocaleString()} this month`:`—`;return(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsx)(`h3`,{children:`Site settings`})}),(0,Q.jsxs)(`div`,{role:`list`,"aria-label":`Bing site settings`,children:[c(`blocked-urls`),c(`crawl-issues`),(0,Q.jsx)(xf,{label:`URL submissions left`,value:l(n),help:`URL submissions Bing will still accept, as of the last sync.`}),(0,Q.jsx)(xf,{label:`Content submissions left`,value:l(r)}),(0,Q.jsx)(xf,{label:`Crawl boost`,value:i?i.crawlBoostEnabled?`On`:i.crawlBoostAvailable?`Off`:`Not offered`:`—`}),i&&i.crawlRate.length===24&&(0,Q.jsx)(xf,{label:`Crawl rate by hour`,value:`24 hours`,children:(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table text-label-13`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsx)(`tr`,{children:i.crawlRate.map((e,t)=>(0,Q.jsx)(`th`,{className:`text-right`,children:t},t))})}),(0,Q.jsx)(`tbody`,{children:(0,Q.jsx)(`tr`,{children:i.crawlRate.map((e,t)=>(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e},t))})})]})})}),c(`fetched-urls`),c(`query-parameters`),c(`country-region-settings`),c(`page-preview-blocks`),c(`deep-link-blocks`),c(`connected-pages`),c(`site-roles`)]})]})}function xf({label:e,value:t,help:n,note:r,children:i}){let[a,o]=(0,Z.useState)(!1),s=(0,Q.jsx)(`span`,{className:`flex-1 text-label-14 text-strong`,children:e}),c=(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5 text-label-14 tabular-nums text-secondary`,children:[r&&(0,Q.jsx)(`span`,{className:`text-label-12 text-caution`,children:r}),t]});return i?(0,Q.jsx)(`div`,{role:`listitem`,className:`border-t border-default first:border-t-0`,children:(0,Q.jsxs)(`details`,{className:`group`,onToggle:e=>o(e.currentTarget.open),children:[(0,Q.jsxs)(`summary`,{className:`flex cursor-pointer list-none items-center gap-2 py-2.5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(m,{className:`h-3.5 w-3.5 shrink-0 text-secondary transition-transform group-open:rotate-90`,"aria-hidden":`true`}),s,c]}),a&&(0,Q.jsx)(`div`,{className:`pb-4 pl-5.5`,children:i})]})}):(0,Q.jsxs)(`div`,{role:`listitem`,className:`flex items-center gap-2 border-t border-default py-2.5 first:border-t-0`,children:[(0,Q.jsx)(`span`,{className:`w-3.5 shrink-0`,"aria-hidden":`true`}),s,c,n&&(0,Q.jsx)(X,{text:n})]})}var Sf=zr[0],Cf=zr[1],wf=zr[2],Tf=zr[3],Ef=zr[4],Df=[`both`,`server`,`ga4`],Of=[`days`,`months`],kf={serverLoading:`Loading monthly server visits…`,gaLoading:`Loading monthly GA4 visits…`,gaStatusLoading:`Checking the GA4 connection…`,serverError:`Could not load monthly server visits.`,gaError:`Could not load monthly GA4 visits.`,gaStatusError:`Could not check the GA4 connection.`,retryServer:`Retry monthly server visits`,retryGa:`Retry monthly GA4 visits`,retryGaStatus:`Retry GA4 connection check`,connectGa:`Connect Google Analytics 4 to see monthly visits.`,emptyMonths:`No monthly visits recorded yet.`},Af=e=>new Date(`${e}-01T00:00:00.000Z`),jf=e=>Af(e).toLocaleDateString(void 0,{month:`short`,timeZone:`UTC`}),Mf=e=>Af(String(e)).toLocaleDateString(void 0,{month:`long`,year:`numeric`,timeZone:`UTC`}),Nf=e=>Number(e.slice(0,4))*12+Number(e.slice(5,7)),Pf={fontSize:12,paddingTop:6},Ff={top:4,right:8,left:0,bottom:0},If=44,Lf=.4,Rf=`ai-visits`,zf=e=>typeof e==`number`?Pt(Math.round(e)):String(e),Bf=`Page fetches`,Vf={pageFetches:`AI page fetches`,pageFetchesDetail:`reading a page to answer`,pageFetchesOlderDetail:`older days counted differently`,pageFetchesTooltip:e=>`An AI engine fetching a page live while answering someone, rather than crawling it for an index. A browser agent (Google-Agent, Claude-Agent) counts its page loads only, not the files its pages load.`+(e===null?``:` Days through ${Yr(e)} were counted under older rules, which counted some of those files and missed some page loads, so they can read high or low. They were not recounted.`),pageFetchesSeries:Bf,olderPageFetchesSeries:`${Bf} (older count)`,visitors:`AI visitors`,visitorsDetail:`arrived from an AI answer`,visitorsOlderDetail:`older days may read high`},Hf=`Visits, server`,Uf=`Visits, GA4`,Wf=`${Hf} (older count)`,Gf=`${Hf} (part month)`,Kf=`${Hf} (part month, older count)`,qf=`Visits, GA4 (part month)`,Jf=e=>typeof e==`number`&&Number.isFinite(e)?e:0;function Yf(e,t){if(!e||t<2)return Array(t).fill(null);let n=e.endIndex-e.startIndex;if(n<=0)return Array(t).fill(null);let r=(e.end-e.start)/n;return Array.from({length:t},(t,n)=>n<e.startIndex||n>e.endIndex?null:e.start+(n-e.startIndex)*r)}function Xf(e,t){if(!e||t<e.startMonth||t>e.endMonth)return null;let n=Nf(e.endMonth)-Nf(e.startMonth);return n<=0?null:e.start+(e.end-e.start)*((Nf(t)-Nf(e.startMonth))/n)}function Zf(e,t){if(!e||t<e.startDate||t>e.endDate)return null;let n=Date.parse(`${e.startDate}T00:00:00.000Z`),r=Date.parse(`${e.endDate}T00:00:00.000Z`)-n;return r<=0?null:e.start+(e.end-e.start)*((Date.parse(`${t}T00:00:00.000Z`)-n)/r)}function Qf(e){let t=[],n=null;return e.forEach((r,i)=>{r.measured===!1&&(n??=r.bucket,e[i+1]?.measured!==!1&&(t.push({from:n,to:r.bucket}),n=null))}),t}function $f(e){return e.filter(e=>e.from!==e.to).map(e=>(0,Q.jsx)(de,{x1:e.from,x2:e.to,fill:`var(--color-overlay-hover)`,fillOpacity:.5,stroke:`none`,label:{value:`not measured`,position:`insideTop`,fontSize:12,fill:`var(--chart-neutral-text-dim, #a1a1a1)`}},e.from))}function ep(e,t){if(!t)return null;let n=e.find(e=>e.measured!==!1),r=e[e.length-1]?.bucket;return!n||!r||t<n.bucket?null:{from:n.bucket,to:t<r?t:r}}function tp(e){let t=e===null?NaN:Date.parse(e);return Number.isFinite(t)?new Date(t-1).toISOString().slice(0,10):void 0}function np(e,t,n=!1,r=1){return i=>{let{cx:a,cy:o,index:s,key:c}=i,l=s??-1,u=e[l]!=null&&e[l-1]==null&&e[l+1]==null;return e[l]==null||!n&&!u||a===void 0||o===void 0?(0,Q.jsx)(`g`,{},c):n?(0,Q.jsx)(`circle`,{cx:a,cy:o,r:3.2,fill:`none`,stroke:t,strokeOpacity:r,strokeWidth:1.6},c):(0,Q.jsx)(`circle`,{cx:a,cy:o,r:2.6,fill:t,fillOpacity:r,stroke:`none`},c)}}function rp({color:e,opacity:t=1}){return(0,Q.jsx)(`svg`,{width:`14`,height:`8`,"aria-hidden":`true`,className:`shrink-0`,children:(0,Q.jsx)(`line`,{x1:`1`,y1:`4`,x2:`13`,y2:`4`,stroke:e,strokeOpacity:t,strokeWidth:2,strokeLinecap:`round`})})}function ip({source:e,rows:t,monthly:n,height:r,showXAxis:i,showTrend:a,unmeasured:o,older:s}){let c=e===`server`,l=c?wf:Tf,u=e=>t.map(t=>t[e]??null),d=c&&s!==null&&t.some(e=>e.serverOlder!=null||e.serverOlderPartial!=null);return(0,Q.jsxs)(`div`,{role:`group`,"aria-label":c?Hf:Uf,children:[(0,Q.jsxs)(`div`,{className:`mb-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-label-12 text-secondary`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(rp,{color:l}),c?Hf:Uf]}),d&&(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(rp,{color:l,opacity:Lf}),`Older count, may read high`]})]}),(0,Q.jsx)(le,{width:`100%`,height:r,children:(0,Q.jsxs)(ve,{data:t,syncId:Rf,margin:i?Ff:{...Ff,bottom:10},children:[(0,Q.jsx)(oe,{stroke:ei,vertical:!1}),(0,Q.jsx)(ue,{dataKey:`bucket`,hide:!i,tick:Zr,stroke:ni,tickFormatter:n?jf:Hr,minTickGap:n?8:28}),(0,Q.jsx)(ge,{tick:Zr,stroke:ni,width:If,allowDecimals:!1,tickFormatter:jt,tickCount:r<150?3:5}),(0,Q.jsx)(he,{contentStyle:ti.contentStyle,labelStyle:ti.labelStyle,itemStyle:ti.itemStyle,labelFormatter:n?Mf:Yr,formatter:zf}),$f(o),s&&(0,Q.jsx)(de,{x1:s.from,x2:s.to,fill:`var(--color-overlay-hover)`,fillOpacity:.3,stroke:`none`}),s&&(0,Q.jsx)(ye,{x:s.to,stroke:Ef,strokeDasharray:`4 4`,strokeWidth:1.5}),c&&(0,Q.jsx)(_e,{type:`monotone`,dataKey:`aiReferralLandedHits`,name:Hf,stroke:l,strokeWidth:2,connectNulls:!1,dot:np(u(`aiReferralLandedHits`),l)}),d&&(0,Q.jsx)(_e,{type:`monotone`,dataKey:`serverOlder`,name:Wf,stroke:l,strokeOpacity:Lf,strokeWidth:2,connectNulls:!1,dot:np(u(`serverOlder`),l,!1,Lf)}),c&&n&&(0,Q.jsx)(_e,{type:`monotone`,dataKey:`serverPartial`,name:Gf,legendType:`none`,connectNulls:!1,stroke:l,strokeWidth:0,activeDot:!1,dot:np(u(`serverPartial`),l,!0)}),d&&n&&(0,Q.jsx)(_e,{type:`monotone`,dataKey:`serverOlderPartial`,name:Kf,legendType:`none`,connectNulls:!1,stroke:l,strokeWidth:0,activeDot:!1,dot:np(u(`serverOlderPartial`),l,!0,Lf)}),c&&a&&(0,Q.jsx)(_e,{type:`linear`,dataKey:`visitTrend`,legendType:`none`,name:`Visits trend`,dot:!1,tooltipType:`none`,stroke:l,strokeWidth:1.3,strokeDasharray:`5 4`,connectNulls:!0}),!c&&(0,Q.jsx)(_e,{type:`monotone`,dataKey:`ga4Visits`,name:Uf,connectNulls:!1,stroke:l,strokeWidth:2,dot:np(u(`ga4Visits`),l)}),!c&&n&&(0,Q.jsx)(_e,{type:`monotone`,dataKey:`ga4Partial`,name:qf,legendType:`none`,connectNulls:!1,stroke:l,strokeWidth:0,activeDot:!1,dot:np(u(`ga4Partial`),l,!0)}),!c&&a&&(0,Q.jsx)(_e,{type:`linear`,dataKey:`ga4Trend`,legendType:`none`,name:`GA4 visits trend`,dot:!1,tooltipType:`none`,stroke:l,strokeWidth:1.3,strokeDasharray:`5 4`,connectNulls:!0})]})})]})}function ap({projectName:e,sinceMinutes:t}){let[n,r]=(0,Z.useState)(!0),[i,a]=(0,Z.useState)(!0),[o,s]=(0,Z.useState)(`both`),[c,l]=(0,Z.useState)(`days`),u=c===`months`,d=(0,Z.useMemo)(()=>{let e=new Date;return{since:new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()-11,1)).toISOString(),until:e.toISOString()}},[]),f=$c(e,{range:d,granularity:`month`,limit:1},{enabled:u}),p=$c(e,{sinceMinutes:t,granularity:`day`,limit:1}),m=tl(e),h=W({...uo({client:Y,path:{name:e}}),enabled:!!e,staleTime:pi}),g=h.data?.connected===!0,_=W({...ma({client:Y,path:{name:e},query:{window:t>=259200?`180d`:t>=129600?`90d`:t>=43200?`30d`:`7d`}}),enabled:!!e&&g,staleTime:pi}),v=W({...ma({client:Y,path:{name:e},query:{startDate:d.since.slice(0,10)}}),enabled:!!e&&g&&u,staleTime:pi}),y=(0,Z.useMemo)(()=>p.data?.series?.points??[],[p.data]),b=(0,Z.useMemo)(()=>{let e=_.data;return new Map((e?.days??[]).map(e=>[e.date,e.sessions]))},[_.data]),x=_.data?.trend??null,S=(0,Z.useMemo)(()=>Qf(y),[y]),C=p.data?.series?.coverageStart??null,w=p.data?.series?.recordedThrough??null,T=w!==null&&y.at(-1)?.measured===!1?Yr(w.slice(0,10)):null,E=p.data?.series?.aiReferralCountingChangedAt??null,D=(0,Z.useMemo)(()=>ep(y,E?.slice(0,10)),[E,y]),O=p.data?.series?.aiUserFetchCountingChangedAt??null,k=(0,Z.useMemo)(()=>ep(y,tp(O)),[O,y]),A=(e,t,n)=>{let r=n.payload?.bucket;return k&&t===Bf&&r!==void 0&&r<=k.to?[zf(e),Vf.olderPageFetchesSeries]:zf(e)},j=p.data?.series?.trends,M=(0,Z.useMemo)(()=>{let e=Yf(j?.crawlerContentHits,y.length),t=Yf(j?.aiUserFetchHits,y.length),n=Yf(j?.aiReferralLandedHits,y.length);return y.map((r,i)=>({...r,crawlerContentHits:r.measured===!1?null:Jf(r.crawlerContentHits),aiUserFetchHits:r.measured===!1?null:Jf(r.aiUserFetchHits),aiReferralLandedHits:r.measured===!1?null:Jf(r.aiReferralLandedHits),ga4Visits:b.get(r.bucket)??null,ga4Trend:Zf(x,r.bucket),crawlTrend:e[i],fetchTrend:t[i],visitTrend:n[i]}))},[y,b,x,j]),N=f.data?.series,P=v.data,F=(0,Z.useMemo)(()=>N?.points??[],[N]),I=(0,Z.useMemo)(()=>{let e=new Set(N?.partialBuckets??[]),t=new Map((P?.months??[]).map(e=>[e.month,e])),n=Yf(N?.trends?.aiReferralLandedHits,F.length),r=new Map(F.map((e,t)=>[e.bucket,{point:e,trend:n[t]}])),i=[...new Set([...r.keys(),...t.keys()])].sort().map(n=>{let i=r.get(n),a=i?.point,o=a&&a.measured!==!1?Jf(a.aiReferralLandedHits):null,s=t.get(n);return{bucket:n,aiReferralLandedHits:e.has(n)?null:o,serverPartial:e.has(n)?o:null,ga4Visits:s?.complete?s.sessions:null,ga4Partial:s&&!s.complete?s.sessions:null,visitTrend:i?.trend??null,ga4Trend:Xf(P?.monthlyTrend,n),recorded:o!==null||(s?.sessions??null)!==null}}),a=i.findIndex(e=>e.recorded);return a>0?i.slice(a):i},[F,N,P]),ee=(0,Z.useMemo)(()=>{if(o===`ga4`)return[];if(!u)return S;let e=new Set(I.map(e=>e.bucket));return Qf(F.filter(t=>e.has(t.bucket)))},[o,u,F,I,S]),L=(0,Z.useMemo)(()=>u?ep(F,N?.aiReferralCountingChangedAt?.slice(0,7)):D,[u,F,N,D]),R=L!==null&&o!==`ga4`,z=(0,Z.useMemo)(()=>(u?I:M).map(e=>{let t=e.aiReferralLandedHits??null,n=`serverPartial`in e?e.serverPartial:null,r=L!==null&&e.bucket<=L.to;return{...e,aiReferralLandedHits:r?null:t,serverOlder:r?t:null,serverPartial:r?null:n,serverOlderPartial:r?n:null}}),[u,I,M,L]),te=[`server`,`ga4`].filter(e=>z.some(t=>e===`server`?t.aiReferralLandedHits!=null||t.serverOlder!=null||t.serverPartial!=null||t.serverOlderPartial!=null:t.ga4Visits!=null||t.ga4Partial!=null)),ne=o===`both`?te.length>0?te:[`server`,`ga4`]:[o],B=(P?.months??[]).filter(e=>e.complete&&e.sessions!==null).at(-1)??null,V=I.filter(e=>e.aiReferralLandedHits!==null).at(-1)??null,H=o===`server`?V?.bucket??null:o===`ga4`?B?.month??null:B?.month??V?.bucket??null,re=H?I.find(e=>e.bucket===H)?.aiReferralLandedHits??null:null,U=P?.monthlyTrend??null,ie=u&&o!==`ga4`,ae=u&&o!==`server`,se=ae&&g,ce=ie&&f.isSuccess||se&&v.isSuccess,de=(!ie||f.isSuccess)&&(!ae||h.isSuccess&&(!g||v.isSuccess)),pe=I.some(e=>ie&&(e.aiReferralLandedHits!==null||e.serverPartial!==null)||se&&(e.ga4Visits!==null||e.ga4Partial!==null)),be=I.find(e=>e.bucket===d.until.slice(0,7)),xe=se?be?.ga4Partial??null:null,Se=ie?be?.serverPartial??null:null,Ce=xe!==null||Se!==null,we=p.data?.totals,Te=we&&{crawlers:Jf(we.crawlerContentHits),fetches:Jf(we.aiUserFetchHits),visits:Jf(we.aiReferralLandedHits)},Ee=(0,Z.useMemo)(()=>y.reduce((e,t)=>({crawlers:e.crawlers+Jf(t.crawlerContentHits),fetches:e.fetches+Jf(t.aiUserFetchHits),visits:e.visits+Jf(t.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[y]),De=Te??Ee,Oe=De.crawlers>0||De.fetches>0||De.visits>0,G=null;if(p.isLoading)G=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Loading AI traffic history…`});else if(p.isError)G=(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:`Could not load AI traffic history.`}),(0,Q.jsx)(X,{text:`The request failed, so this is not a reading of zero activity. Retry, or check the traffic source.`})]});else if(!Oe){let e=m.data?.sources,t=e!==void 0&&e.length===0,n=!t&&C===null;G=(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:t?`No server-side traffic source connected yet.`:n?`No AI activity recorded yet.`:T?`No AI activity recorded, and no new data since ${T}.`:`No AI activity recorded in this period.`}),(0,Q.jsx)(X,{text:t?`Connect a traffic source to see how AI engines read this site over time.`:n?`The source is connected but has not reported anything yet. A new source can take a few hours to appear.`:T?`The traffic source has not synced since ${T}, so the days after it were not measured. They are not a reading of zero. Check the source.`:`The window was measured and nothing was recorded. Try a longer range.`})]})}return(0,Q.jsxs)(`div`,{children:[G??(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mb-5`,children:(0,Q.jsx)(nd,{label:`AI traffic totals`,items:[{label:`AI crawlers`,value:Pt(De.crawlers),detail:`pages crawled`,tooltip:`Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read.`},{label:Vf.pageFetches,value:Pt(De.fetches),detail:k?Vf.pageFetchesOlderDetail:Vf.pageFetchesDetail,tooltip:Vf.pageFetchesTooltip(k?.to??null)},{label:Vf.visitors,value:Pt(De.visits),detail:D?Vf.visitorsOlderDetail:Vf.visitorsDetail,tooltip:`Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival.`+(D?` Days through ${Yr(D.to)} were counted by an older rule that also counted a visitor's later pages, so they can read high and cannot be recounted.`:``)}]})}),y.length>0&&T&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-label-12 text-muted`,children:[(0,Q.jsx)(`span`,{className:`text-secondary text-label-12-strong`,children:`Latest day (UTC)`}),(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5 text-label-13 text-secondary`,children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-13-strong`,children:`Not measured.`}),`No new data since `,T,`.`,(0,Q.jsx)(X,{text:`The traffic source has not synced since ${T}, so the days after it are shaded as not measured rather than drawn as zero. Check the source; a backfill can recover the missing days while the provider still keeps them.`})]})]}),y.length>0&&!T&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-label-12 text-muted`,children:[(0,Q.jsx)(`span`,{className:`text-secondary text-label-12-strong`,children:`Latest day (UTC)`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:Jf(y[y.length-1].crawlerContentHits).toLocaleString()}),`pages crawled`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:Jf(y[y.length-1].aiUserFetchHits).toLocaleString()}),`page fetches`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:Jf(y[y.length-1].aiReferralLandedHits).toLocaleString()}),`visits, server`]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:b.get(y[y.length-1].bucket)?.toLocaleString()??`—`}),`visits, GA4`]}),(0,Q.jsx)(`span`,{className:`text-faint`,children:`still filling`})]}),(0,Q.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-14 text-heading`,children:`Machines reading your site`}),(0,Q.jsx)(X,{text:`Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people.`})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,Q.jsxs)(`label`,{className:`flex items-center gap-1.5 text-label-12 text-secondary cursor-pointer`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:n,onChange:e=>r(e.target.checked),className:`accent-current`}),Vf.pageFetchesSeries]}),(0,Q.jsxs)(`label`,{className:`flex items-center gap-1.5 text-label-12 text-secondary cursor-pointer`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked),className:`accent-current`}),`Trend line`]})]})]}),(0,Q.jsx)(le,{width:`100%`,height:206,children:(0,Q.jsxs)(ve,{data:M,margin:Ff,children:[(0,Q.jsx)(oe,{stroke:`var(--chart-grid, #2e2e2e)`,vertical:!1}),(0,Q.jsx)(ue,{dataKey:`bucket`,tick:Zr,stroke:`var(--chart-axis, #2e2e2e)`,tickFormatter:Hr,minTickGap:28}),(0,Q.jsx)(ge,{tick:Zr,stroke:`var(--chart-axis, #2e2e2e)`,width:If,allowDecimals:!1,tickFormatter:jt}),(0,Q.jsx)(he,{contentStyle:ti.contentStyle,labelStyle:ti.labelStyle,itemStyle:ti.itemStyle,labelFormatter:Yr,formatter:A}),$f(S),n&&k&&(0,Q.jsx)(ye,{x:k.to,stroke:Ef,strokeDasharray:`4 4`,strokeWidth:1.5}),(0,Q.jsx)(fe,{wrapperStyle:Pf,iconType:`plainline`,iconSize:14}),(0,Q.jsx)(me,{type:`monotone`,dataKey:`crawlerContentHits`,name:`Pages crawled`,stroke:Sf,fill:Sf,fillOpacity:.22,strokeWidth:1.8}),n&&(0,Q.jsx)(me,{type:`monotone`,dataKey:`aiUserFetchHits`,name:Bf,stroke:Cf,fill:Cf,fillOpacity:.18,strokeWidth:1.6}),i&&(0,Q.jsx)(_e,{type:`linear`,dataKey:`crawlTrend`,legendType:`none`,name:`Pages crawled trend`,dot:!1,tooltipType:`none`,stroke:Sf,strokeWidth:1.4,strokeDasharray:`5 4`,connectNulls:!0}),i&&n&&(0,Q.jsx)(_e,{type:`linear`,dataKey:`fetchTrend`,legendType:`none`,name:`Page fetches trend`,dot:!1,tooltipType:`none`,stroke:Cf,strokeWidth:1.3,strokeDasharray:`5 4`,connectNulls:!0})]})})]}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3 mt-5 mb-2`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-14 text-heading`,children:`People arriving from AI`}),(0,Q.jsx)(X,{text:`Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other.`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[(0,Q.jsx)(Tu,{windows:Of,value:c,onChange:l,label:`Visits by day or month`,formatOption:e=>e===`months`?`Months`:`Days`}),(0,Q.jsx)(Tu,{windows:Df,value:o,onChange:s,label:`Visit measurement source`,formatOption:e=>e===`ga4`?`GA4`:e===`both`?`Both`:`Server`})]})]}),ie&&f.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:kf.serverLoading}),se&&v.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:kf.gaLoading}),ae&&h.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:kf.gaStatusLoading}),ae&&h.isError&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:kf.gaStatusError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":kf.retryGaStatus,disabled:h.isFetching,onClick:()=>{h.refetch()},children:`Retry`})]}),ie&&f.isError&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:kf.serverError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":kf.retryServer,disabled:f.isFetching,onClick:()=>{f.refetch()},children:`Retry`})]}),se&&v.isError&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:kf.gaError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":kf.retryGa,disabled:v.isFetching,onClick:()=>{v.refetch()},children:`Retry`})]}),u&&o===`ga4`&&h.isSuccess&&!g&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:kf.connectGa}),ce&&de&&!pe&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:kf.emptyMonths}),u&&H&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-3 text-label-12 text-muted`,children:[(0,Q.jsx)(`span`,{className:`text-secondary text-label-12-strong`,children:Mf(H)}),o!==`server`&&B?.month===H&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:Pt(B.sessions??0)}),`visits, GA4`]}),o!==`ga4`&&re!==null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:Pt(re)}),`visits, server`]}),o!==`server`&&U?.changePct!=null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:[U.changePct>0?`▲`:U.changePct<0?`▼`:``,Ut(Math.abs(U.changePct),Je.percent)]}),`trend since `,jf(U.startMonth)]}),o!==`server`&&B?.month===H&&B.engines[0]&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:Pt(B.engines[0].sessions)}),`from `,B.engines[0].label]})]}),Ce&&be&&(0,Q.jsxs)(`div`,{role:`group`,"aria-label":`Month so far`,className:`flex flex-wrap items-center gap-x-5 gap-y-1 mb-3 text-label-13 text-secondary`,children:[(0,Q.jsxs)(`span`,{className:`text-label-13-strong`,children:[Mf(be.bucket),` so far`]}),xe!==null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-13-strong tabular-nums mr-1`,children:Pt(xe)}),`visits, GA4`]}),Se!==null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-13-strong tabular-nums mr-1`,children:Pt(Se)}),`visits, server`]}),(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[`Hollow dots: partial months`,(0,Q.jsx)(X,{text:`Hollow dots show part-month totals. The current month is still filling; earlier partial months have incomplete coverage. Partial months are kept off the connecting line and out of the trend.`})]})]}),(u?ce&&pe:!G)&&(0,Q.jsx)(`div`,{className:`flex flex-col gap-3`,children:ne.map((e,t)=>{let n=t===ne.length-1;return(0,Q.jsx)(ip,{source:e,rows:z,monthly:u,height:ne.length===1?176:n?134:104,showXAxis:n,showTrend:i,unmeasured:e===`server`?ee:[],older:e===`server`&&R?L:null},e)})})]})}function op(e){return e.replace(/\+/g,` `)}var sp=cn,cp={"7d":10080,"30d":43200,"90d":129600,"180d":259200};function lp(e){return Xl(e.landingPage)}var up=25,dp=10,fp={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0,byEngine:{series:[],otherCount:0,days:[]}},pp={siteTrafficTooltip:`GA4's own figures for the complete days ending yesterday, as GA4 counts them, each against the period of the same length before it. Pick a figure in any slot to chart it by day.`,siteTrafficFallbackTooltip:`Sessions, Google organic search sessions and distinct users from GA4. Distinct users are unavailable when the selected range has no stored GA4 aggregate.`,channelTooltip:`GA4 sessions split into five channels that do not overlap. AI sessions are taken out of the channel GA4 filed them under before the rest is counted.`,organicTooltip:`Sessions from Google organic search, after AI sessions are taken out.`,socialTooltip:`Organic Social and Paid Social sessions, after AI sessions are taken out.`,directTooltip:`Sessions with no source: bookmarks, typed URLs, untagged email and in-app browsers. AI visits that send no referrer land here too.`,aiTooltip:`Sessions in GA4's AI Assistant channel or from a known AI source. Paid AI comes from paid UTM values or a GA4 paid channel group. AI visits that send no referrer count as Direct, so this is a floor.`,otherTooltip:`Every other GA4 channel, such as Referral, Email, Paid Search, Display and Video.`,aiEnginesTooltip:`AI referral sessions by engine. Open an engine to see the sources GA4 reported. Unattributed AI is AI traffic whose source names no engine.`,aiChartLabel:`AI sessions by engine`,socialTooltip2:`Sessions GA4 classifies as Organic Social or Paid Social, grouped by platform. Open a platform to see the sources GA4 reported for it.`,platformsTooltip:`Platforms with sessions in this period. A source no platform matches counts as its own platform.`,paidSocialTooltip:`Sessions in GA4's Paid Social channel.`,socialChartLabel:`Social sessions by platform`,socialPlatformTooltip:`Sessions from social and creator platforms in every GA4 channel, grouped by platform. Tagged ads and creator links count under their platform even when GA4 files them elsewhere, such as fb_ads under Paid Other, so this can be more than the Social channel above. Open a platform to see its sources.`,platformPaidTooltip:`Platform sessions with a paid signal: a GA4 paid channel group, or a paid source or medium such as fb_ads, cpc or paid.`,bestConvertingTooltip:`The ranked platform with the most conversions per 1,000 sessions.`,conversionsHelp:e=>e.length>0?`Counted GA4 events: ${e.join(`, `)}. Each is credited to the source of the session it happened in.`:`No conversion events are measured for this project.`,perThousandHelp:e=>`Conversions for every 1,000 sessions: what a visit from the platform is worth, before you know its cost per click. Platforms with fewer than ${e.toLocaleString()} sessions are shown but not ranked. Whole site counts every channel.`,rankHelp:e=>`Platforms ordered by conversions per 1,000 sessions, then by conversions. Only platforms with at least ${e.toLocaleString()} sessions are ranked.`,tooFewSessions:e=>`Fewer than ${e.toLocaleString()} sessions, so not ranked`,notRanked:`Too few sessions`,notMeasured:`Not measured`,siteLabel:`Whole site`,siteScope:`every channel`,paidClassTitle:`A GA4 paid channel group, or a paid source or medium`,organicClassTitle:`No paid signal in the channel group, source or medium`,noneRanked:`None ranked`,rateReasons:{"no-data":`No conversion events are measured for this project yet, so platforms are not ranked.`,"sync-not-ready":`The latest GA4 sessions or conversions sync did not finish, so rates are hidden until both are current.`,"channel-leads-unfiltered":`Conversions cannot follow the host or path filter here, so rates are hidden.`,"paid-split-needs-landing-page":`The paid and organic split needs landing pages GA4 did not report here, so rates are hidden.`,"sessions-behind-leads":`Conversions run past the last stored sessions, so rates are hidden until the GA4 sync catches up.`,"sessions-missing-on-lead-days":`Some days in this period have conversions but no stored sessions, so rates are hidden.`,"sessions-before-leads":`This period starts before conversions were first stored, so rates are hidden. Pick a shorter period.`},noAiReferrals:`No AI referrals in this period.`,noAiLandingPages:`No AI landing pages in this period.`,noSocial:`No social sessions in this period.`,noneInPeriod:`None in this period`,aiHistoryTooltip:`Daily AI crawls, page fetches and visits from connected traffic sources, with GA4 visits beside server visits.`};function mp(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return`just now`;if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function hp(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function gp(e,t){return!e||!t?null:`${new Date(`${e}T00:00:00`).toLocaleDateString(void 0,{month:`short`,day:`numeric`})} to ${new Date(`${t}T00:00:00`).toLocaleDateString(void 0,{month:`short`,day:`numeric`,year:`numeric`})}`}function _p({projectName:e}){let{data:t,isLoading:n,isError:r}=el(e),i=t?.sources??[];return(0,Q.jsxs)(`section`,{"aria-labelledby":`server-activity-heading`,children:[(0,Q.jsx)(Qu,{id:`server-activity-heading`,title:`Server activity`,tooltip:`Crawler, AI fetch and AI referral activity from connected traffic sources over the last 24 hours.`,meta:`Last 24 hours`,actions:!K()&&i.length>0?(0,Q.jsx)(U,{to:`/projects/$projectName/traffic`,params:{projectName:e},className:`text-label-14 text-link hover:underline`,children:`Manage sources`}):void 0}),n?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Loading server activity…`}):r?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:`Could not load server activity.`}):i.length===0?(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`No traffic source connected.`,` `,!K()&&(0,Q.jsx)(U,{to:`/projects/$projectName/traffic`,params:{projectName:e},className:`text-link hover:underline`,children:`Connect a source`})]}):(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`w-full min-w-[36rem] text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,Q.jsx)(id,{label:`Source`,align:`left`}),(0,Q.jsx)(id,{label:`Status`,align:`left`}),(0,Q.jsx)(id,{label:`Crawler hits`,align:`right`}),(0,Q.jsx)(id,{label:`AI hits`,align:`right`}),(0,Q.jsx)(id,{label:`AI sessions`,align:`right`}),(0,Q.jsx)(id,{label:`Last sync`,align:`right`}),(0,Q.jsx)(`th`,{className:`py-2`,"aria-label":`Detail`})]})}),(0,Q.jsx)(`tbody`,{children:i.map(t=>(0,Q.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,Q.jsx)(`td`,{className:`py-2 pr-3 text-strong`,children:t.displayName}),(0,Q.jsx)(`td`,{className:`py-2 pr-3`,children:(0,Q.jsx)(J,{tone:nl(t.status),children:t.status})}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right tabular-nums text-primary`,children:t.totals24h.crawlerHits.toLocaleString(`en-US`)}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right tabular-nums text-primary`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[t.totals24h.aiUserFetchHits.toLocaleString(`en-US`),t.totals24h.aiUserFetchLikelyFakeHits>0&&(0,Q.jsx)(X,{text:al(t.totals24h.aiUserFetchLikelyFakeHits)})]})}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right tabular-nums text-primary`,children:t.totals24h.aiReferralLandedHits.toLocaleString(`en-US`)}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-secondary`,children:t.lastSyncedAt?mp(t.lastSyncedAt):`never`}),(0,Q.jsx)(`td`,{className:`py-2 pl-3 text-right`,children:!K()&&(0,Q.jsx)(U,{to:`/traffic/$projectName/$sourceId`,params:{projectName:e,sourceId:t.id},className:`text-link hover:underline`,"aria-label":`${t.displayName} detail`,children:`Detail`})})]},t.id))})]})})]})}function vp({projectName:e}){let[t,n]=(0,Z.useState)(`30d`);return(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(_p,{projectName:e}),(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsx)(Np,{projectName:e,window:t,periodControl:(0,Q.jsx)(Tu,{windows:sp,value:t,onChange:n,label:`Traffic time period`}),between:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsxs)(`section`,{"aria-labelledby":`ai-traffic-history-heading`,children:[(0,Q.jsx)(Qu,{id:`ai-traffic-history-heading`,title:`AI traffic history`,tooltip:pp.aiHistoryTooltip}),(0,Q.jsx)(ap,{projectName:e,sinceMinutes:cp[t]})]})]})})]})}var yp={session:`Session`,first_user:`First visit`,manual_utm:`UTM`},bp={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)`},xp=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Class`,align:`left`},{label:`Attribution`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}],Sp=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Channel`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}];function Cp(e){return e.engine===null}function wp({row:e}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`td`,{className:`max-w-[220px] truncate py-1.5 pr-3 text-strong`,title:e.source,children:e.source}),(0,Q.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:e.medium}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-secondary`,title:e.trafficClass===`paid`?`Paid AI traffic, from paid UTM values or a GA4 paid channel group`:`AI traffic without a paid attribution signal`,children:e.trafficClass===`paid`?`Paid`:`Organic`}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-secondary`,title:bp[e.sourceDimension]??``,children:yp[e.sourceDimension]??e.sourceDimension}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:Ut(e.share)})]})}function Tp({row:e}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`td`,{className:`max-w-[240px] truncate py-1.5 pr-3 text-strong`,title:e.source,children:op(e.source)}),(0,Q.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:op(e.medium)}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-secondary`,title:`GA4 channel group: ${e.channelGroup}`,children:e.channelGroup===`Paid Social`?`Paid social`:`Organic social`}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:Ut(e.share)})]})}var Ep=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Class`,align:`left`},{label:`Channel`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`},{label:`Conversions`,align:`right`},{label:`Per 1,000`,align:`right`}],Dp=`—`;function Op({label:e}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted`,title:e,children:Dp}),(0,Q.jsx)(`span`,{className:`sr-only`,children:e})]})}function kp({row:e}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`td`,{className:`max-w-[240px] truncate py-1.5 pr-3 text-strong`,title:e.source,children:op(e.source)}),(0,Q.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:op(e.medium)}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-secondary`,title:e.trafficClass===`paid`?pp.paidClassTitle:pp.organicClassTitle,children:e.trafficClass===`paid`?`Paid`:`Organic`}),(0,Q.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:`GA4 channel group: ${e.channelGroup}`,children:e.channelGroup}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:Ut(e.share)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.conversions===null?(0,Q.jsx)(Op,{label:pp.notMeasured}):e.conversions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.conversionsPerThousandSessionsDisplay})]})}function Ap({performance:e}){let t=(0,Z.useMemo)(()=>[{key:`conversions`,label:`Conversions`,help:pp.conversionsHelp(e.countedEventNames),sortValue:e=>e.conversions,render:e=>(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-primary tabular-nums`,children:e.conversions===null?(0,Q.jsx)(Op,{label:pp.notMeasured}):e.conversions.toLocaleString()})},{key:`perThousand`,label:`Per 1,000 sessions`,help:pp.perThousandHelp(e.minSessions),sortValue:e=>e.enoughSessions?e.conversionsPerThousandSessions:null,render:t=>(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right tabular-nums ${t.enoughSessions?`text-primary`:`text-muted`}`,title:t.enoughSessions?void 0:pp.tooFewSessions(e.minSessions),children:t.conversionsPerThousandSessionsDisplay})},{key:`rank`,label:`Rank`,help:pp.rankHelp(e.minSessions),sortValue:e=>e.rank,firstDir:`asc`,render:t=>(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right tabular-nums`,children:t.rank===null?e.conversionRateAvailable?(0,Q.jsx)(`span`,{className:`text-label-13 text-muted`,title:pp.tooFewSessions(e.minSessions),children:pp.notRanked}):(0,Q.jsx)(Op,{label:pp.notMeasured}):(0,Q.jsx)(`span`,{className:`text-primary`,children:t.rank})})}],[e]),n=e.site,r=e.conversionRateUnavailableReason;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(cd,{groups:e.platforms,groupLabel:`Platform`,caption:`Social and creator platforms by sessions and conversions`,childColumns:Ep,childRowKey:e=>`${e.source}:${e.medium}:${e.channelGroup}`,renderChildCells:e=>(0,Q.jsx)(kp,{row:e}),extraColumns:t,defaultSort:e.conversionRateAvailable?{key:`rank`,dir:`asc`}:void 0,referenceRow:(0,Q.jsxs)(`tr`,{className:`border-t border-subtle text-label-14-strong`,"data-testid":`social-site-average`,children:[(0,Q.jsxs)(`td`,{className:`py-2 pr-3 text-primary`,children:[pp.siteLabel,` `,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:pp.siteScope})]}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-primary tabular-nums`,children:n.sessions===null?(0,Q.jsx)(Op,{label:pp.notMeasured}):n.sessions.toLocaleString()}),(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-primary tabular-nums`,children:n.conversions===null?(0,Q.jsx)(Op,{label:pp.notMeasured}):n.conversions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-primary tabular-nums`,children:n.conversionsPerThousandSessionsDisplay}),(0,Q.jsx)(`td`,{})]})}),r&&(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-secondary`,children:pp.rateReasons[r]})]})}function jp({performance:e}){let t=e.platforms,n=t[0]??null,r=t.find(e=>e.rank===1)??null,i=t.reduce((e,t)=>e+t.sources.length,0);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(nd,{label:`Social sessions`,items:[{label:`Social sessions`,value:e.sessions.toLocaleString(),detail:`${e.sharePctDisplay} of all sessions`},{label:`Platforms`,value:String(t.length),detail:Ip(i,`source`),tooltip:pp.platformsTooltip},{label:`Paid social`,value:e.paidSessions.toLocaleString(),detail:`${Ut(e.paidShare)} of social`,tooltip:pp.platformPaidTooltip},{label:`Top platform`,value:n?.label??`None`,detail:n?Ip(n.sessions,`session`):void 0},{label:`Best converting`,value:r?.label??(e.conversionRateAvailable?pp.noneRanked:pp.notMeasured),detail:r?`${r.conversionsPerThousandSessionsDisplay} per 1,000 sessions`:void 0,tooltip:pp.bestConvertingTooltip}]}),(0,Q.jsxs)($u,{children:[(0,Q.jsx)(ed,{label:pp.socialChartLabel,meta:t.length>0?Ip(e.sessions,`session`):pp.noneInPeriod,children:t.length>0?(0,Q.jsx)(ud,{input:e.daily,label:pp.socialChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:pp.noSocial})}),(0,Q.jsx)(ed,{label:`Social platforms`,meta:t.length>0?`${Ip(t.length,`platform`)} · ${Ip(i,`source`)}`:pp.noneInPeriod,children:t.length>0?(0,Q.jsx)(Ap,{performance:e}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:pp.noSocial})})]})]})}function Mp(e,t){let n=z(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!0),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(fp),[y,b]=(0,Z.useState)([]),[x,S]=(0,Z.useState)(null);async function C(r){c(!0),m(null);try{let a=await n.fetchQuery({...uo({client:Y,path:{name:e}}),staleTime:pi});if(r.current)return;if(i(a),!a.connected){o(null),v(fp),b([]),S(null),c(!1);return}let s=t===`all`?void 0:t,[l,u,d,f]=await Promise.all([n.fetchQuery({...Hi({client:Y,path:{name:e},query:s?{window:s}:void 0}),staleTime:pi}),n.fetchQuery({...ma({client:Y,path:{name:e},query:s?{window:s}:void 0}),staleTime:pi}).catch(()=>fp),n.fetchQuery({...Gi({client:Y,path:{name:e},query:s?{window:s}:void 0}),staleTime:pi}).catch(()=>[]),n.fetchQuery({...va({client:Y,path:{name:e},query:{window:vr(t)?t:`30d`}}),staleTime:pi}).catch(()=>null)]);if(r.current)return;o(l),v(u),b(d),S(f),c(!1)}catch(e){if(r.current)return;m(e instanceof Error?e.message:`Failed to load GA4 data`),c(!1)}}(0,Z.useEffect)(()=>{let e={current:!1};return C(e),()=>{e.current=!0}},[e,t,n]);async function w(){u(!0),m(null),g(null);try{let r=await gr(e,vr(t)?mn[t]:void 0);g(`Synced ${r.rowCount.toLocaleString()} page rows, ${r.aiReferralCount.toLocaleString()} AI and ${r.socialReferralCount.toLocaleString()} social referral rows (${r.days} days)`),await ui(n,`ga`),await C({current:!1})}catch(e){m(e instanceof Error?e.message:`Sync failed`)}finally{u(!1)}}async function T(){f(!0),m(null),g(null);try{await He(e),await ui(n,`ga`),i({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),o(null),S(null),g(`GA4 disconnected`)}catch(e){m(e instanceof Error?e.message:`Disconnect failed`)}finally{f(!1)}}async function E(){await ui(n,`ga`),await C({current:!1})}return{status:r,traffic:a,loading:s,syncing:l,disconnecting:d,error:p,notice:h,aiDaily:_,sessionHistory:y,overview:x,handleSync:w,handleDisconnect:T,handleConnected:E}}function Np({projectName:e,window:t,periodControl:n,between:r}){let i=Mp(e,t??`30d`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Pp,{ga:i,projectName:e,periodControl:n}),r,(0,Q.jsx)(Fp,{ga:i,projectName:e})]})}function Pp({ga:e,projectName:t,periodControl:n}){let{status:r,traffic:i,syncing:a,disconnecting:o,handleSync:s,handleDisconnect:c}=e,l=r?.connected===!0,u=l&&!K()&&!rt(),d=i?gp(i.windowStart,i.windowEnd):null,f;return f=e.loading&&!r?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Loading traffic data…`}):l?i&&e.overview?(0,Q.jsx)(_d,{overview:e.overview,refreshing:e.loading}):i?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(nd,{label:`Site traffic`,items:[{label:`Total sessions`,value:hp(i.totalSessions),detail:i.totalSessions.toLocaleString()},{label:`Organic sessions`,value:hp(i.totalOrganicSessions),detail:`${i.organicSharePctDisplay} of total`},{label:`Total users`,value:i.totalUsers===null?`n/a`:hp(i.totalUsers),detail:i.totalUsers===null?`Unavailable for this range`:i.totalUsers.toLocaleString()}]})}):(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-y border-default py-4`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No traffic data yet.`}),!K()&&!rt()&&(0,Q.jsxs)(q,{variant:`outline`,size:`sm`,disabled:a,onClick:ci(s),children:[(0,Q.jsx)(_,{className:`mr-1.5 size-3.5 ${a?`animate-spin`:``}`}),`Sync from GA4`]})]}):K()||rt()?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No Google Analytics 4 property connected.`}):(0,Q.jsx)(Wp,{projectName:t,onConnected:()=>{e.handleConnected()}}),(0,Q.jsxs)(`section`,{"aria-labelledby":`site-traffic-heading`,children:[(0,Q.jsx)(Qu,{id:`site-traffic-heading`,title:`Site traffic`,tooltip:e.overview?pp.siteTrafficTooltip:d?`${pp.siteTrafficFallbackTooltip} Data covers ${d}.`:pp.siteTrafficFallbackTooltip,meta:l?(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`inline-block size-2 rounded-full bg-positive-500`}),`GA4 property `,(0,Q.jsx)(`span`,{className:`text-strong`,children:r.propertyId}),r.clientEmail&&(0,Q.jsxs)(`span`,{className:`text-muted`,children:[`· `,r.clientEmail]})]}):void 0,actions:n||u?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n,u&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(q,{variant:`outline`,size:`sm`,disabled:a,onClick:ci(s),children:[(0,Q.jsx)(_,{className:`mr-1.5 size-3.5 ${a?`animate-spin`:``}`}),a?`Syncing…`:`Sync`]}),(0,Q.jsxs)(q,{variant:`ghost`,size:`sm`,className:`text-negative-400 hover:text-negative`,disabled:o,onClick:ci(c),children:[(0,Q.jsx)(g,{className:`mr-1.5 size-3.5`}),`Disconnect`]})]})]}):void 0}),e.error&&(0,Q.jsx)(`div`,{role:`alert`,className:`mb-4 rounded-md border border-negative-800/60 bg-negative-900/20 px-4 py-2 text-label-14 text-negative`,children:e.error}),e.notice&&(0,Q.jsx)(`div`,{role:`status`,className:`mb-4 rounded-md border border-positive-800/60 bg-positive-900/20 px-4 py-2 text-label-14 text-positive`,children:e.notice}),f]})}function Fp({ga:e,projectName:t}){let{traffic:n,aiDaily:r,sessionHistory:i}=e,[a,o]=(0,Z.useState)({key:`sessions`,dir:`desc`}),[s,c]=(0,Z.useState)({key:`sessions`,dir:`desc`}),l=$l({rows:(0,Z.useMemo)(()=>{if(!n?.topPages)return[];let{key:e,dir:t}=a;return[...n.topPages].sort((n,r)=>{let i=n[e],a=r[e],o=typeof i==`string`&&typeof a==`string`?i.localeCompare(a):Number(i)-Number(a);return t===`asc`?o:-o})},[n?.topPages,a]),getSearchText:e=>Xl(e.landingPage),pageSize:dp}),u=$l({rows:(0,Z.useMemo)(()=>{if(!n?.aiReferralLandingPages)return[];let{key:e,dir:t}=s;return[...n.aiReferralLandingPages].sort((n,r)=>{let i=n[e],a=r[e],o=typeof i==`string`&&typeof a==`string`?i.localeCompare(a):Number(i)-Number(a);return t===`asc`?o:-o})},[n?.aiReferralLandingPages,s]),getSearchText:lp,pageSize:up}),d=(0,Z.useMemo)(()=>i.map(e=>({date:e.date,value:e.sessions})),[i]);function f(e){l.setPage(1),o(t=>t.key===e?{key:e,dir:t.dir===`desc`?`asc`:`desc`}:{key:e,dir:`desc`})}function p(e){u.setPage(1),c(t=>t.key===e?{key:e,dir:t.dir===`desc`?`asc`:`desc`}:{key:e,dir:`desc`})}if(!e.status?.connected)return null;let m=n?gp(n.windowStart,n.windowEnd):null,h=n?.channelBreakdown,g=n?.paidAiSessionsBySession??0,_=n?.aiEngines??[],v=n?.socialPlatforms??[],y=v[0]??null,b=n?.socialPlatformPerformance?.status===`ready`?n.socialPlatformPerformance:null,x=u.totalRows>0?`${u.totalRows.toLocaleString()} ${u.hasQuery?u.totalRows===1?`match`:`matches`:u.totalRows===1?`row`:`rows`}`:u.hasQuery&&(n?.aiReferralLandingPages.length??0)>0?`0 matches`:null;return(0,Q.jsxs)(Q.Fragment,{children:[n&&h&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsxs)(`section`,{"aria-labelledby":`traffic-by-channel-heading`,children:[(0,Q.jsx)(Qu,{id:`traffic-by-channel-heading`,title:`Traffic by channel`,tooltip:pp.channelTooltip,meta:m}),(0,Q.jsx)(nd,{label:`Sessions by channel`,items:[{label:`Organic search`,value:h.organic.sharePctDisplay,detail:`${h.organic.sessions.toLocaleString()} sessions`,tooltip:pp.organicTooltip},{label:`Social`,value:h.social.sharePctDisplay,detail:`${h.social.sessions.toLocaleString()} sessions`,tooltip:pp.socialTooltip},{label:`Direct`,value:h.direct.sharePctDisplay,detail:`${h.direct.sessions.toLocaleString()} sessions`,tooltip:pp.directTooltip},{label:`AI (at least)`,value:h.ai.sharePctDisplay,detail:g>0?`${h.ai.sessions.toLocaleString()} sessions · ${g.toLocaleString()} paid`:`${h.ai.sessions.toLocaleString()} sessions`,tooltip:pp.aiTooltip},{label:`Other channels`,value:h.other.sharePctDisplay,detail:`${h.other.sessions.toLocaleString()} sessions`,tooltip:pp.otherTooltip}]}),(0,Q.jsxs)($u,{children:[(0,Q.jsx)(ed,{label:pp.aiChartLabel,meta:r.days.length>0?Ip(r.totalSessions,`session`):pp.noneInPeriod,children:r.days.length>0?(0,Q.jsx)(ud,{input:r.byEngine,baseline:d,baselineLabel:`Total sessions`,label:pp.aiChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:pp.noAiReferrals})}),(0,Q.jsx)(ed,{label:`Where AI visitors came from`,meta:_.length>0?`${Ip(_.filter(e=>e.engine!==null).length,`engine`)} · ${Ip(n.aiReferrals.length,`source`)}`:pp.noneInPeriod,children:_.length>0?(0,Q.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Q.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Q.jsx)(cd,{groups:_,groupLabel:`Engine`,caption:`AI referral sessions by engine`,childColumns:xp,childRowKey:e=>`${e.source}:${e.medium}:${e.sourceDimension}:${e.trafficClass}`,renderChildCells:e=>(0,Q.jsx)(wp,{row:e}),pinLast:Cp})}),(0,Q.jsx)(X,{text:pp.aiEnginesTooltip})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:pp.noAiReferrals})}),(0,Q.jsx)(ed,{label:`Pages AI visitors landed on`,meta:x??pp.noneInPeriod,children:n.aiReferralLandingPages.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(eu,{value:u.query,onChange:u.setQuery,label:`Filter landing page URLs or query parameters`,placeholder:`Filter URL or query parameters`,className:`mb-4 max-w-md`}),u.totalRows>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`w-full min-w-[36rem] text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,Q.jsx)(rd,{label:`Landing page`,sortKey:`landingPage`,current:s.key,dir:s.dir,onSort:p,align:`left`}),(0,Q.jsx)(rd,{label:`Source`,sortKey:`source`,current:s.key,dir:s.dir,onSort:p,align:`left`}),(0,Q.jsx)(id,{label:`Attribution`,align:`left`}),(0,Q.jsx)(rd,{label:`Sessions`,sortKey:`sessions`,current:s.key,dir:s.dir,onSort:p,align:`right`})]})}),(0,Q.jsx)(`tbody`,{children:u.rows.map(e=>(0,Q.jsx)(Kp,{row:e},`${e.landingPage}:${e.source}:${e.medium}:${e.sourceDimension}`))})]})}),(0,Q.jsx)(tu,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,onPageChange:u.setPage,itemLabel:u.hasQuery?`matches`:`rows`})]}):(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 py-4`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No landing pages match this filter`}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,onClick:()=>u.setQuery(``),children:`Clear filter`})]})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:pp.noAiLandingPages})})]})]}),(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsxs)(`section`,{"aria-labelledby":`social-heading`,children:[(0,Q.jsx)(Qu,{id:`social-heading`,title:`Social`,tooltip:b?pp.socialPlatformTooltip:pp.socialTooltip2,meta:m}),b?(0,Q.jsx)(jp,{performance:b}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(nd,{label:`Social sessions`,items:[{label:`Social sessions`,value:n.socialSessions.toLocaleString(),detail:`${n.socialSharePctDisplay} of all sessions`},{label:`Platforms`,value:String(v.length),detail:`${n.socialReferrals.length} sources`,tooltip:pp.platformsTooltip},{label:`Paid social`,value:(n.paidSocialSessions??0).toLocaleString(),detail:`${Ut(n.paidSocialShare??0)} of social`,tooltip:pp.paidSocialTooltip},{label:`Top platform`,value:y?.label??`None`,detail:y?`${y.sessions.toLocaleString()} sessions`:void 0}]}),(0,Q.jsxs)($u,{children:[(0,Q.jsx)(ed,{label:pp.socialChartLabel,meta:v.length>0?Ip(n.socialSessions,`session`):pp.noneInPeriod,children:v.length>0?(0,Q.jsx)(ud,{input:n.socialPlatformDaily,label:pp.socialChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:pp.noSocial})}),(0,Q.jsx)(ed,{label:`Social platforms`,meta:v.length>0?`${Ip(v.length,`platform`)} · ${Ip(n.socialReferrals.length,`source`)}`:pp.noneInPeriod,children:v.length>0?(0,Q.jsx)(cd,{groups:v,groupLabel:`Platform`,caption:`Social sessions by platform`,childColumns:Sp,childRowKey:e=>`${e.source}:${e.medium}:${e.channelGroup}`,renderChildCells:e=>(0,Q.jsx)(Tp,{row:e})}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:pp.noSocial})})]})]})]})]}),n&&n.topPages.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsxs)(`section`,{"aria-labelledby":`top-landing-pages-heading`,children:[(0,Q.jsx)(Qu,{id:`top-landing-pages-heading`,title:`Top landing pages`,tooltip:`Landing pages by sessions. Organic share is the share of a page's sessions that came from Google organic search.`}),(0,Q.jsx)(eu,{value:l.query,onChange:l.setQuery,label:`Filter landing page URLs`,placeholder:`Filter landing pages`,className:`mb-4 max-w-md`}),(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`w-full min-w-[36rem] text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,Q.jsx)(rd,{label:`Landing page`,sortKey:`landingPage`,current:a.key,dir:a.dir,onSort:f,align:`left`}),(0,Q.jsx)(rd,{label:`Sessions`,sortKey:`sessions`,current:a.key,dir:a.dir,onSort:f,align:`right`}),(0,Q.jsx)(rd,{label:`Organic`,sortKey:`organicSessions`,current:a.key,dir:a.dir,onSort:f,align:`right`}),(0,Q.jsx)(id,{label:`Organic share`,align:`right`})]})}),(0,Q.jsx)(`tbody`,{children:l.rows.map(e=>(0,Q.jsx)(Gp,{page:e},e.landingPage))})]})}),l.totalRows===0&&l.hasQuery&&(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:`No landing pages match this filter`}),(0,Q.jsx)(tu,{page:l.page,pageSize:l.pageSize,visibleRows:l.rows.length,totalRows:l.totalRows,onPageChange:l.setPage,itemLabel:l.hasQuery?`matches`:`pages`})]})]}),(0,Q.jsx)(Up,{projectName:t}),(0,Q.jsx)(`p`,{className:`mt-6 text-copy-13 text-secondary`,children:n?.lastSyncedAt?`Last synced ${mp(n.lastSyncedAt)}`:`Never synced`})]})}function Ip(e,t){return`${e.toLocaleString()} ${e===1?t:`${t}s`}`}var Lp=25,Rp=`n/a`,zp={heading:`Google organic search traffic`,tooltip:`GA4's "Google organic search traffic: Landing page + query string" report, from the property's Search Console link. Each window ends yesterday in the property time zone, as GA4's own date ranges do. The Total row is GA4's own total for all pages, not a sum of the rows, and it does not change with the filter. Search Console data arrives about two days late.`,windowLabel:`Google organic search time period`,loading:`Loading Google organic search pages…`,loadError:`Could not load Google organic search pages.`,neverSynced:`No Google organic search data has been synced yet.`,neverSyncedAction:`Sync GA4 to load the Search Console landing-page report.`,unavailable:`GA4 did not return Search Console data for this property.`,unavailableAction:`Link Search Console to this GA4 property (Admin, Product links, Search Console links), then sync GA4 again.`,refreshFailed:`The last refresh failed.`,noSearchTraffic:`No landing pages had Google organic search traffic in this window.`,noSearchTrafficAction:`If this property should have some, check its Search Console link in GA4 (Admin, Product links, Search Console links).`,noSearchTrafficConfirmed:`Search Console also recorded no impressions for these days.`,notLinkedBadge:`Search Console not linked`,notLinked:e=>`GA4 has no Search Console data for this site, but Search Console recorded ${e.toLocaleString()} impressions in this window. Link the site's Search Console property in GA4 (Admin, Product links, Search Console links).`,thresholded:`GA4 applied thresholding to this report, so it may withhold some rows.`,retry:`Retry`,refreshFailedBadge:`Last refresh failed`,unavailableBadge:`Search Console unavailable`,thresholdedBadge:`Thresholded`,previousSnapshot:`Showing the last good snapshot, synced`,totalLabel:`Total`,totalScope:`all pages`,noFilterMatch:`No landing pages match this filter`,noFilterMatchInLoaded:e=>`No landing pages in the top ${e.toLocaleString()} by clicks match this filter. The filter searches only the pages loaded here.`};function Bp(e,t){switch(t){case`landingPage`:return e.landingPage;case`clicks`:return e.organicGoogleSearchClicks;case`impressions`:return e.organicGoogleSearchImpressions;case`ctr`:return e.organicGoogleSearchClickThroughRate;case`position`:return e.organicGoogleSearchAveragePosition;case`activeUsers`:return e.activeUsers}}function Vp(e){return e===null?Rp:e.toFixed(1)}function Hp(e){return e===null?Rp:Ut(e)}function Up({projectName:e}){let[t,n]=(0,Z.useState)(`28d`),[r,i]=(0,Z.useState)(`clicks`),[a,o]=(0,Z.useState)(`desc`),s=W({...Ni({client:Y,path:{name:e},query:{window:t,limit:Hn}}),staleTime:pi}),c=s.data,l=$l({rows:(0,Z.useMemo)(()=>[...c?.rows??[]].sort((e,t)=>{let n=Bp(e,r),i=Bp(t,r);return n===null||i===null?n===i?0:n===null?1:-1:typeof n==`string`&&typeof i==`string`?a===`asc`?n.localeCompare(i):i.localeCompare(n):a===`asc`?n-i:i-n}),[c?.rows,r,a]),getSearchText:e=>Xl(tn(e.landingPage)),pageSize:Lp});function u(e){l.setPage(1),r===e?o(e=>e===`desc`?`asc`:`desc`):(i(e),o(e===`landingPage`?`asc`:`desc`))}let d=c?.total??null,f=c?.searchConsoleLink?.state===`not-linked`,p=!K()&&!rt();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsxs)(`section`,{"aria-labelledby":`ga-search-landing-heading`,children:[(0,Q.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-start justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h2`,{id:`ga-search-landing-heading`,className:`text-heading-16 text-primary`,children:zp.heading}),(0,Q.jsx)(X,{text:zp.tooltip})]}),c?.windowStart&&c.windowEnd&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:[Xe(c.windowStart),` to `,Xe(c.windowEnd),c.timeZone?` (${c.timeZone})`:``]})]}),(0,Q.jsx)(Tu,{windows:Nn,value:t,onChange:e=>{l.setPage(1),n(e)},label:zp.windowLabel})]}),s.isPending?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary py-6 text-center`,children:zp.loading}):s.isError||!c?(0,Q.jsxs)(`div`,{role:`alert`,className:`flex flex-wrap items-center gap-3 px-4 py-2 rounded-md bg-negative-900/20 border border-negative-800/60 text-label-14 text-negative`,children:[(0,Q.jsx)(`span`,{children:zp.loadError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,onClick:()=>{s.refetch()},children:zp.retry})]}):(0,Q.jsxs)(Q.Fragment,{children:[(c.status===`error`||c.status===`unavailable`||c.subjectToThresholding||f)&&(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-2`,"data-testid":`ga-search-landing-status`,children:[f&&(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,"data-testid":`ga-search-landing-not-linked`,children:[(0,Q.jsx)(J,{tone:`caution`,children:zp.notLinkedBadge}),(0,Q.jsx)(X,{text:zp.notLinked(c.searchConsoleLink?.searchConsoleImpressions??0)})]}),c.status===`error`&&(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Q.jsx)(J,{tone:`negative`,children:zp.refreshFailedBadge}),c.error&&(0,Q.jsx)(X,{text:c.error})]}),c.status===`unavailable`&&(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Q.jsx)(J,{tone:`caution`,children:zp.unavailableBadge}),c.error&&(0,Q.jsx)(X,{text:c.error})]}),c.subjectToThresholding&&(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Q.jsx)(J,{tone:`caution`,children:zp.thresholdedBadge}),(0,Q.jsx)(X,{text:zp.thresholded})]}),c.status!==`ready`&&d&&c.syncedAt&&(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[zp.previousSnapshot,` `,mp(c.syncedAt),`.`]}),c.status===`unavailable`&&d&&(0,Q.jsx)(`p`,{className:`w-full text-copy-14 text-secondary`,children:zp.unavailableAction})]}),d?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(eu,{value:l.query,onChange:l.setQuery,label:`Filter Google organic search landing pages`,placeholder:`Filter landing pages`,className:`mb-4 max-w-md`}),(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`w-full min-w-[40rem] text-label-14`,"aria-labelledby":`ga-search-landing-heading`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,Q.jsx)(rd,{label:`Landing page`,sortKey:`landingPage`,current:r,dir:a,onSort:u,align:`left`}),(0,Q.jsx)(rd,{label:`Clicks`,sortKey:`clicks`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(rd,{label:`Impressions`,sortKey:`impressions`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(rd,{label:`CTR`,sortKey:`ctr`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(rd,{label:`Avg. position`,sortKey:`position`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(rd,{label:`Active users`,sortKey:`activeUsers`,current:r,dir:a,onSort:u,align:`right`})]})}),(0,Q.jsxs)(`tbody`,{children:[(0,Q.jsxs)(`tr`,{className:`border-t border-subtle text-label-14-strong`,"data-testid":`ga-search-landing-total`,children:[(0,Q.jsxs)(`td`,{className:`py-1.5 text-primary`,children:[zp.totalLabel,` `,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:zp.totalScope})]}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:d.organicGoogleSearchClicks.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:d.organicGoogleSearchImpressions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:Hp(d.organicGoogleSearchClickThroughRate)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:Vp(d.organicGoogleSearchAveragePosition)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:d.activeUsers.toLocaleString()})]}),l.rows.map(e=>(0,Q.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,Q.jsx)(`td`,{className:`py-1.5 text-neutral max-w-[400px] truncate`,title:tn(e.landingPage),children:tn(e.landingPage)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-strong tabular-nums`,children:e.organicGoogleSearchClicks.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.organicGoogleSearchImpressions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:Hp(e.organicGoogleSearchClickThroughRate)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:Vp(e.organicGoogleSearchAveragePosition)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.activeUsers.toLocaleString()})]},e.landingPage))]})]})}),!xr(d)&&!f&&(0,Q.jsxs)(`div`,{className:`text-label-14 text-secondary mt-3 space-y-1`,children:[(0,Q.jsx)(`p`,{children:zp.noSearchTraffic}),(0,Q.jsx)(`p`,{children:c.searchConsoleLink?.state===`no-search-data`?zp.noSearchTrafficConfirmed:zp.noSearchTrafficAction})]}),l.totalRows===0&&l.hasQuery&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary mt-3`,children:c.totalRows>c.rows.length?zp.noFilterMatchInLoaded(c.rows.length):zp.noFilterMatch}),(0,Q.jsx)(tu,{page:l.page,pageSize:l.pageSize,visibleRows:l.rows.length,totalRows:l.totalRows,onPageChange:l.setPage,itemLabel:l.hasQuery?`matches`:`pages`}),(c.totalRows>c.rows.length||c.rowsCapped)&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary mt-3`,children:[c.totalRows>c.rows.length?`Showing the top ${c.rows.length.toLocaleString()} of ${c.totalRows.toLocaleString()} stored pages by clicks.`:``,c.totalRows>c.rows.length&&c.rowsCapped?` `:``,c.rowsCapped&&c.reportRowCount!==null?`GA4 reported ${c.reportRowCount.toLocaleString()} pages; the ${c.totalRows.toLocaleString()} with the most clicks are stored.`:``]}),c.syncedAt&&(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Synced `,mp(c.syncedAt)]})]}):(0,Q.jsx)(Cs,{className:`p-5`,children:c.status===`unavailable`?(0,Q.jsxs)(`div`,{className:`text-label-14 text-secondary space-y-1`,children:[(0,Q.jsx)(`p`,{className:`text-neutral`,children:zp.unavailable}),(0,Q.jsx)(`p`,{children:zp.unavailableAction})]}):c.status===`error`?(0,Q.jsxs)(`div`,{className:`text-label-14 text-secondary space-y-1`,children:[(0,Q.jsx)(`p`,{className:`text-neutral`,children:zp.refreshFailed}),c.error&&(0,Q.jsx)(`p`,{children:c.error})]}):(0,Q.jsxs)(`div`,{className:`text-label-14 text-secondary space-y-1`,children:[(0,Q.jsx)(`p`,{className:`text-neutral`,children:zp.neverSynced}),p&&(0,Q.jsx)(`p`,{children:zp.neverSyncedAction})]})})]})]})]})}function Wp({projectName:e,onConnected:t}){let[n,r]=(0,Z.useState)(``),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(null),p=(0,Z.useCallback)(e=>{let t=e.target.files?.[0];if(!t)return;d(null),a(t.name);let n=new FileReader;n.onload=()=>{let e=n.result;try{let t=JSON.parse(e);if(!t.client_email||!t.private_key){d(`JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client).`),s(null);return}s(e)}catch{d(`File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console.`),s(null)}},n.onerror=()=>{d(`Failed to read file.`),s(null)},n.readAsText(t)},[]);async function m(){if(d(null),!n.trim())d(`Property ID is required.`);else if(!o)d(`Please upload a service account key file.`);else{l(!0);try{await dr(e,{propertyId:n.trim(),keyJson:o});try{await gr(e)}catch{}t()}catch(e){d(e instanceof Error?e.message:`Failed to connect GA4`)}finally{l(!1)}}}return(0,Q.jsxs)(Cs,{className:`surface-card p-6`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-primary mb-1`,children:`Connect Google Analytics 4`}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary mb-5`,children:`Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console.`}),u&&(0,Q.jsx)(`div`,{className:`mb-4 px-4 py-2 rounded-md bg-negative-900/20 border border-negative-800/60 text-label-14 text-negative`,children:u}),(0,Q.jsxs)(`div`,{className:`mb-4`,children:[(0,Q.jsx)(`label`,{htmlFor:`ga4-property-id`,className:`block text-label-12-strong text-secondary mb-1.5`,children:`GA4 Property ID`}),(0,Q.jsx)(`input`,{id:`ga4-property-id`,type:`text`,placeholder:`e.g. 123456789`,value:n,onChange:e=>r(e.target.value),className:`w-full rounded-md bg-bg-elevated/60 border border-default px-3 py-2 text-label-14 text-strong placeholder-mono-400 focus:outline-none focus:ring-1 focus:ring-mono-600`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:`Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX).`})]}),(0,Q.jsxs)(`div`,{className:`mb-5`,children:[(0,Q.jsx)(`label`,{className:`block text-label-12-strong text-secondary mb-1.5`,children:`Service Account Key File`}),(0,Q.jsx)(`input`,{ref:f,type:`file`,accept:`.json,application/json`,onChange:p,className:`hidden`}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>f.current?.click(),className:`flex items-center gap-2 w-full rounded-md bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-button-14 text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer`,children:[(0,Q.jsx)(S,{className:`w-4 h-4 shrink-0`}),i?(0,Q.jsx)(`span`,{className:`text-strong truncate`,children:i}):(0,Q.jsx)(`span`,{children:`Upload .json key file`})]}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[`Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have `,(0,Q.jsx)(`span`,{className:`text-secondary`,children:`Viewer`}),` access on the GA4 property.`]})]}),(0,Q.jsx)(q,{variant:`default`,size:`sm`,disabled:c||!n.trim()||!o,onClick:ci(m),children:c?`Connecting & syncing…`:`Connect GA4`})]})}function Gp({page:e}){return(0,Q.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,Q.jsx)(`td`,{className:`max-w-[400px] truncate py-1.5 pr-3 text-strong`,title:e.landingPage,children:e.landingPage}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.organicSessions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:Ut(e.organicShare)})]})}function Kp({row:e}){return(0,Q.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,Q.jsx)(`td`,{className:`max-w-[400px] py-1.5 pr-3 text-strong`,children:(0,Q.jsx)(Ql,{value:e.landingPage,className:`whitespace-nowrap`})}),(0,Q.jsx)(`td`,{className:`max-w-[220px] truncate py-1.5 pr-3 text-secondary`,title:e.source,children:e.source}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-secondary`,title:bp[e.sourceDimension]??``,children:yp[e.sourceDimension]??e.sourceDimension}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()})]})}var qp=new Set([`gbp-listing-discrepancy`,`gbp-lodging-gap`,`gbp-cta-gap`,`gbp-metric-drop`,`gbp-keyword-drop`]),Jp={connect:`Connect Google Business Profile`,connecting:`Opening Google…`,waiting:`Finish the Google consent flow in the popup. This section refreshes when it closes.`,refreshing:`Refreshing the Business Profile connection…`,credentialsMissing:`Google OAuth app credentials are not configured yet. Set them on the Settings page first.`},Yp=`Google Business Profile is not connected yet. Your Canonry team can set this up.`,Xp={accountLabel:`Business Profile account`,loadingAccounts:`Loading accounts…`,noAccounts:`No Business Profile accounts are visible to this Google user. It needs manager or owner access on the profile.`,trackNew:`Track new locations`,discover:`Discover locations`,discovering:`Discovering…`,refresh:`Refresh locations`,noneDiscovered:`No locations discovered yet. Choose the account and discover its locations.`,noneDiscoveredDefaultAccount:`No locations discovered yet. Discover them from the connection's account.`,noneDiscoveredManaged:`No locations discovered yet. Your Canonry team can discover them.`},Zp={disconnect:`Disconnect`,confirmTitle:`Disconnect Google Business Profile?`,confirmBody:`This removes the connection and this project's locations and all synced Business Profile data. Reconnecting starts from discovery again.`,confirm:`Disconnect and clear data`,disconnecting:`Disconnecting…`,cancel:`Cancel`};function Qp({projectName:e,projectId:t}){let n=z(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(!1),{canWrite:_,isAdmin:v}=si(),y=!K()&&!rt(),b=y&&v,x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=(0,Z.useRef)(!1),T=W(oo({client:Y,path:{name:e}})),E=T.data?.find(e=>e.connectionType===`gbp`),D=!!E,O=r?{locationName:r}:void 0,k=W({...wa({client:Y,path:{name:e}}),enabled:D}),A=W({...xo({client:Y,path:{name:e},query:O}),enabled:D}),j=W({...ba({client:Y,path:{name:e},query:O}),enabled:D}),M=W({...aa({client:Y,path:{name:e},query:O}),enabled:D}),N=W({...gi({client:Y,path:{name:e},query:O}),enabled:D}),P=W({...Ra({client:Y,path:{name:e},query:O}),enabled:D}),F=W({queryKey:[`gbp-section-insights`,e],queryFn:()=>Wn(e),enabled:D});function I(){ui(n,`gbp`)}let ee=ie({...Ya(),onSuccess:n=>{Fs({id:n.runId,projectId:t,kind:Qt[`gbp-sync`],projectLabel:e,sourceAction:`gbp-sync`}),li({title:`Business Profile sync started`,detail:`${e} will refresh when the sync completes.`,tone:`neutral`,dedupeKey:`gbp-sync:${e}`,dedupeMode:`replace`})}}),L=(0,Z.useSyncExternalStore)(Qs,js,js),R=Object.values(L.runs).some(e=>e.kind===Qt[`gbp-sync`]&&e.projectId===t),te=ee.isPending||R,ne=ie({...ya(),onSuccess:()=>I()}),B=W({...ki({client:Y}),enabled:!T.isLoading&&!D&&b}),V=!!B.data?.google?.configured,H=D&&k.data!==void 0&&k.data.locations.length===0,re=H&&b,U=W({...Sa({client:Y,path:{name:e}}),enabled:re,retry:!1}),ae=ie({...yi(),onSuccess:t=>{c(!0),li({title:`Business Profile locations discovered`,detail:`${t.totalDiscovered} ${t.totalDiscovered===1?`location`:`locations`} found, ${t.totalSelected} tracked.`,tone:`neutral`,dedupeKey:`gbp-discover:${e}`,dedupeMode:`replace`})}}),oe=ie({...yo(),meta:{skipGlobalErrorToast:!0},onSuccess:()=>{g(!1),i(null),o(null),c(!1),w.current=!0}});(0,Z.useEffect)(()=>{if(D||!w.current)return;let e=S.current;if(e?.disabled&&B.isLoading)return;let t=e&&!e.disabled?e:C.current;t&&(w.current=!1,t.focus())});function se(){oe.reset(),g(!1),x.current?.focus()}(0,Z.useEffect)(()=>{H&&c(!0)},[H]);async function ce(){if(!V)m(Jp.credentialsMissing);else{u(!0),m(null),f(null);try{await jd(e,`gbp`,()=>{f(Jp.refreshing),Promise.all([ui(n,`google`),ui(n,`gbp`)]).finally(()=>f(null))})===`popup`&&f(Jp.waiting)}catch(e){m(be(e))}finally{u(!1)}}}if((0,Z.useEffect)(()=>{if(!r||!k.data)return;let e=k.data.locations.filter(e=>e.selected);(e.length<=1||!e.some(e=>e.locationName===r))&&i(null)},[r,k.data]),(0,Z.useEffect)(()=>{a&&k.data&&((r?[r]:k.data.locations.filter(e=>e.selected).map(e=>e.locationName)).includes(a)||o(null))},[a,k.data,r]),T.isLoading)return null;if(!E){let t=[{title:`Connect your Google account`,command:`canonry gbp connect ${e}`,note:`Opens Google OAuth. Grant Business Profile (business.manage) access.`},{title:`Choose the account`,command:`canonry gbp accounts ${e}`,note:`Pick which Business Profile account this project tracks.`},{title:`Select locations`,command:`canonry gbp locations discover ${e}`,note:(0,Q.jsxs)(Q.Fragment,{children:[`Then adopt the ones to sync: `,(0,Q.jsxs)(`code`,{className:`rounded bg-bg-elevated/80 px-1 py-0.5 text-label-12-mono text-secondary`,children:[`canonry gbp locations select `,e,` <location>`]})]})},{title:`Sync, and keep it fresh`,command:`canonry gbp sync ${e}`,note:(0,Q.jsxs)(Q.Fragment,{children:[`Schedule it: `,(0,Q.jsxs)(`code`,{className:`rounded bg-bg-elevated/80 px-1 py-0.5 text-label-12-mono text-secondary`,children:[`canonry schedule set `,e,` --kind gbp-sync --preset daily`]})]})}],n=(0,Q.jsx)(`ol`,{className:`mt-4 space-y-4`,children:t.map((e,t)=>(0,Q.jsxs)(`li`,{className:`grid grid-cols-[1.5rem_1fr] gap-x-3`,children:[(0,Q.jsx)(`span`,{className:`mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full bg-mono-800 text-label-12-strong tabular-nums text-neutral`,"aria-hidden":`true`,children:t+1}),(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:e.title}),(0,Q.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 text-label-12-mono text-neutral`,children:e.command}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:e.note})]})]},e.title))});return(0,Q.jsx)(`section`,{className:`page-section`,children:(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsx)(`h2`,{ref:C,tabIndex:-1,className:`focus:outline-none`,children:`Connect Google Business Profile`}),(0,Q.jsx)(`p`,{className:`mt-2 max-w-2xl text-copy-14 text-secondary`,children:`Track your Google Business Profile and local search performance.`}),b?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(fs,{ref:S,type:`button`,disabled:l||B.isLoading,onClick:()=>void ce(),children:l?Jp.connecting:Jp.connect}),!B.isLoading&&!V?(0,Q.jsx)(J,{tone:`negative`,children:`App credentials missing`}):null]}),d?(0,Q.jsx)(`p`,{role:`status`,className:`mt-3 text-copy-13 text-secondary`,children:d}):null,p?(0,Q.jsx)(`p`,{role:`alert`,className:`mt-3 text-copy-13 text-negative-400`,children:p}):null]}):y?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:Yp}):null,(0,Q.jsxs)(`details`,{className:`mt-4`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-label-14 text-secondary hover:text-primary`,children:`Connect using the CLI`}),n]})]})})}let le=A.data,ue=k.data?.locations??[],de=ue.filter(e=>e.selected),fe=j.data?.keywords??[],pe=M.data?.lodging??[],me=N.data?.placeActions??[],he=P.data?.places??[],ge=ue.length>0?ue[0].accountName:E.domain,_e=r?ue.find(e=>e.locationName===r)?.displayName??null:null,ve=r?ue.filter(e=>e.locationName===r):de,ye=new Set(ve.map(e=>e.locationName)),xe=pe.filter(e=>ye.has(e.locationName)),Se=me.filter(e=>ye.has(e.locationName)),Ce=he.filter(e=>ye.has(e.locationName)),we=new Set(de.map(e=>e.locationName)),Te=r?fe:fe.filter(e=>we.has(e.locationName)),Ee=!r&&de.length>1,De=(F.data??[]).filter(e=>!e.dismissed&&qp.has(e.type)&&(!_e||e.query===_e||e.query===r||e.title.startsWith(_e)));return(0,Q.jsx)(`section`,{className:`page-section`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`h2`,{children:`Google Business Profile`}),(0,Q.jsx)(X,{text:`How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control.`})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(J,{tone:`positive`,children:`Connected`}),!K()&&(0,Q.jsx)(fs,{type:`button`,variant:`outline`,size:`sm`,disabled:te,onClick:()=>ee.mutate({client:Y,path:{name:e},body:{}}),children:te?`Syncing…`:`Sync`}),y&&(0,Q.jsx)(fs,{ref:x,type:`button`,variant:`ghost`,size:`sm`,"aria-expanded":h,"aria-controls":`gbp-disconnect-confirm`,disabled:oe.isPending,onClick:()=>{h?se():g(!0)},children:Zp.disconnect})]})]}),y&&h&&(0,Q.jsxs)(`div`,{id:`gbp-disconnect-confirm`,role:`group`,"aria-labelledby":`gbp-disconnect-title`,className:`mb-4 rounded-md border border-base bg-bg-elevated/60 p-3`,children:[(0,Q.jsx)(`p`,{id:`gbp-disconnect-title`,className:`text-copy-14-strong text-strong`,children:Zp.confirmTitle}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:Zp.confirmBody}),oe.isError&&(0,Q.jsx)(`p`,{role:`alert`,className:`mt-2 text-copy-14 text-negative break-words`,children:ws(oe.error)}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,Q.jsx)(fs,{type:`button`,variant:`destructive`,size:`sm`,disabled:oe.isPending,onClick:()=>oe.mutate({client:Y,path:{name:e}}),children:oe.isPending?Zp.disconnecting:Zp.confirm}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:oe.isPending,onClick:se,children:Zp.cancel})]})]}),(0,Q.jsxs)(`p`,{className:`mb-4 text-copy-13 text-muted`,children:[ge?(0,Q.jsxs)(Q.Fragment,{children:[`Account `,(0,Q.jsx)(`span`,{className:`font-mono text-secondary`,children:ge}),` · `]}):null,k.data?`${k.data.totalSelected} of ${k.data.totalDiscovered} locations tracked`:`Loading locations…`]}),de.length>1&&(0,Q.jsxs)(`div`,{className:`mb-5 max-w-xs`,children:[(0,Q.jsx)(`label`,{htmlFor:`local-presence-location`,className:`mb-1 block text-label-14-strong text-secondary`,children:`Location`}),(0,Q.jsxs)(`select`,{id:`local-presence-location`,value:r??``,onChange:e=>i(e.target.value||null),className:`w-full rounded-md border border-base bg-bg px-3 py-2 text-label-14 text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60`,children:[(0,Q.jsx)(`option`,{value:``,children:`All locations`}),de.map(e=>(0,Q.jsx)(`option`,{value:e.locationName,children:e.displayName},e.id))]})]}),de.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:H?re?Xp.noneDiscovered:y&&_?Xp.noneDiscoveredDefaultAccount:Xp.noneDiscoveredManaged:(0,Q.jsxs)(Q.Fragment,{children:[`No locations are tracked yet. Open `,(0,Q.jsx)(`span`,{className:`text-copy-14-strong text-neutral`,children:`Manage locations`}),` below to track the one(s) for this business.`]})}):(0,Q.jsxs)(Q.Fragment,{children:[De.length>0&&(0,Q.jsxs)(`div`,{className:`mb-6 grid gap-2`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Needs attention`}),De.map(e=>(0,Q.jsx)(`div`,{className:[`surface-card insight-card`,_m(e.severity),`p-3`].filter(Boolean).join(` `),children:(0,Q.jsxs)(`p`,{className:`flex items-center gap-2 text-copy-14-strong text-strong`,children:[e.title,e.recommendation?.reason&&(0,Q.jsx)(X,{text:e.recommendation.reason})]})},e.id))]}),le&&(0,Q.jsx)(Tm,{performance:le.performance,freshness:le.freshness,timeseries:le.timeseries}),le?.profileCompleteness&&(0,Q.jsx)(tm,{summary:le.profileCompleteness}),ve.length>0&&(0,Q.jsx)(nm,{locations:ve,lodging:xe,places:Ce,placeActions:Se,expandedLocation:a,onToggleExpanded:e=>{o(t=>t===e?null:e)}}),(0,Q.jsxs)(`div`,{className:`mb-2`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline mb-2`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Search terms`}),j.data&&j.data.total>0&&(0,Q.jsxs)(`span`,{className:`text-label-12 text-faint`,children:[Ut(j.data.thresholdedPct,Je.percent),` privacy-thresholded`]})]}),Te.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No keyword impressions stored yet.`}):(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Search term`}),Ee&&(0,Q.jsx)(`th`,{className:`text-left`,children:`Location`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Impressions`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Window`})]})}),(0,Q.jsx)(`tbody`,{children:Te.slice(0,25).map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-neutral`,children:e.keyword}),Ee&&(0,Q.jsx)(`td`,{className:`text-muted`,children:ue.find(t=>t.locationName===e.locationName)?.displayName??e.locationName}),(0,Q.jsx)(`td`,{className:`text-right font-mono text-strong`,children:e.valueCount===null?(0,Q.jsxs)(`span`,{className:`text-muted`,title:`Privacy floor — Google withheld the exact count`,children:[`<`,e.valueThreshold]}):e.valueCount.toLocaleString()}),(0,Q.jsxs)(`td`,{className:`text-right text-label-12-mono text-faint`,children:[e.periodStart,`–`,e.periodEnd]})]},`${e.locationName}:${e.keyword}`))})]})]})]}),(0,Q.jsxs)(`div`,{className:`mt-6 border-t border-default pt-4`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`flex items-center gap-1.5 text-button-14 text-secondary hover:text-strong`,onClick:()=>c(e=>!e),"aria-expanded":s,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:s?`▾`:`▸`}),` Manage locations (`,ue.length,`)`]}),s&&(0,Q.jsxs)(`div`,{className:`mt-3`,children:[y&&(0,Q.jsx)(em,{firstDiscovery:H,chooseAccount:re,accounts:U.data?.accounts??null,accountsLoading:U.isLoading,accountsError:U.error?be(U.error):null,pending:ae.isPending,onDiscover:t=>ae.mutate({client:Y,path:{name:e},body:t})}),ue.length===0?y?null:(0,Q.jsxs)(`p`,{className:`text-copy-14 text-muted`,children:[`No locations discovered. Run `,(0,Q.jsx)(`span`,{className:`font-mono`,children:`canonry gbp locations discover`}),`.`]}):(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Location`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Address`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Status`}),!K()&&(0,Q.jsx)(`th`,{className:`text-right`,children:`Action`})]})}),(0,Q.jsx)(`tbody`,{children:ue.map(t=>(0,Q.jsx)($p,{location:t,showAction:!K(),columnCount:K()?3:4,disabled:ne.isPending,onSetSelected:async n=>{await ne.mutateAsync({client:Y,path:{name:e,locationName:t.locationName},body:{selected:n}})}},t.id))})]})]})]})]})})}function $p({location:e,showAction:t,columnCount:n,disabled:r,onSetSelected:i}){let[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(!1),m=e.websiteMatchesProject===!1,h=e.selected;(0,Z.useEffect)(()=>{let e=p.current;p.current=a,a?f.current?.focus():e&&d.current?.focus()},[a]);async function g(){c(!0),u(null);try{await i(!e.selected),o(!1)}catch(e){u(be(e))}finally{c(!1)}}function _(){h||m?(u(null),o(!0)):g()}function v(){u(null),o(!1)}let y=h?`Untrack ${e.displayName}?`:`Track ${e.displayName} in this project?`,b=h?`Its stored reviews, rating history and stats are removed from this project. Tracking it again fetches current data only; removed history does not come back.`:`Its website${e.websiteDomain?`, ${e.websiteDomain},`:``} is not one of this project's domains. Its reviews, review alerts and stats would count in this project.`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`span`,{className:`text-strong`,children:e.displayName}),m&&(0,Q.jsxs)(`span`,{className:`mt-1 flex flex-wrap items-center gap-1.5`,children:[(0,Q.jsx)(J,{tone:`caution`,children:`Other website`}),e.websiteDomain&&(0,Q.jsx)(`span`,{className:`text-copy-13 text-secondary`,children:e.websiteDomain})]})]}),(0,Q.jsx)(`td`,{className:`text-muted`,children:e.storefrontAddress??`—`}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:e.selected?`positive`:`neutral`,children:e.selected?`Tracked`:`Not tracked`})}),t&&(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsx)(fs,{ref:d,type:`button`,variant:`outline`,size:`sm`,"aria-expanded":h||m?a:void 0,disabled:r||s||a,onClick:_,children:e.selected?`Untrack`:`Track`})})]}),t&&(a||l)&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:n,children:a?(0,Q.jsxs)(`div`,{role:`group`,"aria-label":y,className:`max-w-2xl py-1`,onKeyDown:e=>{e.key===`Escape`&&!s&&v()},children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:y}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:b}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,Q.jsx)(q,{ref:f,type:`button`,variant:`outline`,size:`sm`,disabled:s,onClick:v,children:h?`Keep tracking`:`Cancel`}),(0,Q.jsx)(fs,{type:`button`,variant:h?`destructive`:`default`,size:`sm`,disabled:r||s,onClick:()=>void g(),children:s?h?`Untracking…`:`Tracking…`:h?`Untrack`:`Track anyway`})]}),l&&(0,Q.jsx)(`p`,{role:`alert`,className:`mt-2 text-copy-14 text-negative`,children:l})]}):(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:l}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>u(null),children:`Dismiss`})]})})})]})}function em({firstDiscovery:e,chooseAccount:t,accounts:n,accountsLoading:r,accountsError:i,pending:a,onDiscover:o}){let[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(!0),d=s||n?.[0]?.name||``,f=t&&!d;return(0,Q.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-end gap-3`,children:[t&&(0,Q.jsxs)(`div`,{className:`min-w-0 max-w-xs flex-1`,children:[(0,Q.jsx)(`label`,{htmlFor:`gbp-discover-account`,className:`mb-1 block text-label-14-strong text-secondary`,children:Xp.accountLabel}),i?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-13 text-negative-400`,children:i}):n&&n.length===0?(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:Xp.noAccounts}):(0,Q.jsxs)(`select`,{id:`gbp-discover-account`,value:d,disabled:r||!n,onChange:e=>c(e.target.value),className:`w-full rounded-md border border-base bg-bg px-3 py-2 text-label-14 text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60`,children:[r||!n?(0,Q.jsx)(`option`,{value:``,children:Xp.loadingAccounts}):null,(n??[]).map(e=>(0,Q.jsx)(`option`,{value:e.name,children:e.accountName?`${e.accountName} (${e.name})`:e.name},e.name))]})]}),(0,Q.jsxs)(`label`,{className:`flex min-h-9 items-center gap-2 text-label-14 text-secondary`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked)}),Xp.trackNew]}),(0,Q.jsx)(fs,{type:`button`,variant:e?`default`:`outline`,size:`sm`,disabled:a||f,onClick:()=>o(t?{accountName:d,selectAllNew:l}:{selectAllNew:l}),children:a?Xp.discovering:e?Xp.discover:Xp.refresh})]})}function tm({summary:e}){if(e.locationCount===0)return null;let t=e.locationCount,n=[{label:`Description`,value:`${e.withDescription}/${t}`,tone:hm(e.withDescription,t,`caution`)},{label:`Hours`,value:`${e.withHours}/${t}`,tone:hm(e.withHours,t,`caution`)},{label:`Phone`,value:`${e.withPrimaryPhone}/${t}`,tone:hm(e.withPrimaryPhone,t,`caution`)},{label:`Service area`,value:`${e.withServiceArea}/${t}`,tone:hm(e.withServiceArea,t,`neutral`)},{label:`Secondary categories`,value:`${e.withSecondaryCategories}/${t}`,detail:`${e.secondaryCategoryTotal} total`,tone:hm(e.withSecondaryCategories,t,`caution`)},{label:`Closed`,value:String(e.permanentlyClosed+e.temporarilyClosed),detail:e.permanentlyClosed||e.temporarilyClosed?`${e.permanentlyClosed} permanent, ${e.temporarilyClosed} temporary`:`reported open`,tone:e.permanentlyClosed>0?`negative`:e.temporarilyClosed>0?`caution`:`positive`}];return(0,Q.jsxs)(`div`,{className:`mb-6 border-y border-default py-3`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Owner profile · Business Information`}),(0,Q.jsx)(X,{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.`})]}),(0,Q.jsx)(`div`,{className:`grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3`,children:n.map(e=>(0,Q.jsxs)(`div`,{className:`grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3`,children:[(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:e.label}),(0,Q.jsx)(`span`,{className:`text-label-14-mono tabular-nums ${gm(e.tone)}`,children:e.value}),e.detail&&(0,Q.jsx)(`span`,{className:`col-span-2 text-label-12 text-faint`,children:e.detail})]},e.label))})]})}function nm({locations:e,lodging:t,places:n,placeActions:r,expandedLocation:i,onToggleExpanded:a}){let o=new Map(t.map(e=>[e.locationName,e])),s=new Map(n.map(e=>[e.locationName,e])),c=new Map;for(let e of r){let t=c.get(e.locationName)??[];t.push(e),c.set(e.locationName,t)}return(0,Q.jsxs)(`div`,{className:`mb-6`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline mb-2`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Source evidence`}),(0,Q.jsx)(X,{text:K()?`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.`})]}),(0,Q.jsxs)(`span`,{className:`text-label-12 text-faint`,children:[e.length,` location`,e.length===1?``:`s`]})]}),(0,Q.jsx)(`div`,{className:`data-table-wrapper`,children:(0,Q.jsxs)(`table`,{className:`data-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`min-w-[14rem]`,children:`Location`}),(0,Q.jsx)(`th`,{className:`min-w-[15rem]`,children:`Owner profile`}),(0,Q.jsx)(`th`,{className:`min-w-[11rem]`,children:`Hotel data`}),(0,Q.jsx)(`th`,{className:`min-w-[11rem]`,children:`Public Maps`}),(0,Q.jsx)(`th`,{className:`min-w-[10rem]`,children:`CTAs`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Detail`})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let t=o.get(e.locationName)??null,n=s.get(e.locationName)??null,r=c.get(e.locationName)??[],l=i===e.locationName;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:e.displayName}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-faint`,children:e.primaryCategoryDisplayName??`Primary category not returned`}),(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:[(0,Q.jsx)(J,{tone:e.selected?`positive`:`neutral`,children:e.selected?`Tracked`:`Not tracked`}),e.openStatus&&e.openStatus!==`OPEN`&&(0,Q.jsx)(J,{tone:e.openStatus===`CLOSED_PERMANENTLY`?`negative`:`caution`,children:ym(e.openStatus)})]})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(im,{location:e})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(am,{lodging:t})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(sm,{place:n,mapsUri:e.mapsUri})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(lm,{actions:r})}),(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>a(e.locationName),children:l?`Hide`:`Details`})})]}),l&&(0,Q.jsx)(`tr`,{className:`bg-mono-950/35 hover:bg-mono-950/35`,children:(0,Q.jsx)(`td`,{colSpan:6,className:`px-4 py-4`,children:(0,Q.jsx)(fm,{location:e,lodging:t,place:n,placeActions:r})})})]},e.id)})})]})})]})}function rm(e){return[{label:`Description`,tone:vm(e.description)?`positive`:`neutral`,value:vm(e.description)?`set`:`not returned`},{label:`Hours`,tone:e.regularHours?`positive`:`neutral`,value:e.regularHours?`set`:`not returned`},{label:`Phone`,tone:vm(e.primaryPhone)?`positive`:`neutral`,value:vm(e.primaryPhone)?`set`:`not returned`},{label:`Website`,tone:vm(e.websiteUri)?`positive`:`neutral`,value:vm(e.websiteUri)?`set`:`not returned`},{label:`Secondary`,tone:e.additionalCategories.length>0?`positive`:`neutral`,value:e.additionalCategories.length>0?String(e.additionalCategories.length):`not returned`},{label:`Service area`,tone:e.serviceArea?`positive`:`neutral`,value:e.serviceArea?`set`:`not returned`}]}function im({location:e}){let t=rm(e);return(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(e=>(0,Q.jsxs)(J,{tone:e.tone,children:[e.label,` `,e.value]},e.label))})}function am({lodging:e}){return(0,Q.jsx)(dm,{...om(e)})}function om(e){return e?e.populatedGroupCount===0?{tone:`neutral`,label:`0 groups returned`,detail:`Lodging API returned no readable groups; verify Hotel details.`}:{tone:`positive`,label:`${e.populatedGroupCount} group${e.populatedGroupCount===1?``:`s`} returned`,detail:`Owner lodging attributes.`}:{tone:`neutral`,label:`No Lodging API snapshot`,detail:`Not returned for this scoped location.`}}function sm({place:e,mapsUri:t}){return(0,Q.jsx)(dm,{...cm(e,t)})}function cm(e,t){if(!e)return{tone:`neutral`,label:`Public listing not checked`,detail:t?`Maps link available.`:`No Places snapshot.`};let n=e.amenities.length;return{tone:n>0?`positive`:`neutral`,label:n>0?`${n} signal${n===1?``:`s`} detected`:`0 supported signals detected`,detail:`Places tier: ${e.tier}`}}function lm({actions:e}){return(0,Q.jsx)(dm,{...um(e)})}function um(e){if(e.length===0)return{tone:`neutral`,label:`No CTAs stored`,detail:`No placeActionLinks returned.`};let t=e.filter(e=>e.providerType===`MERCHANT`).length;return t===0?{tone:`neutral`,label:`${e.length} aggregator CTA${e.length===1?``:`s`}`,detail:`No merchant-owned CTA returned.`}:{tone:`positive`,label:`${t} merchant CTA${t===1?``:`s`}`,detail:`${e.length} total returned.`}}function dm({tone:e,label:t,detail:n}){return(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(J,{tone:e,children:t}),(0,Q.jsx)(`p`,{className:`mt-1.5 text-copy-13 text-faint`,children:n})]})}function fm({location:e,lodging:t,place:n,placeActions:r}){let i=t?Cm(t.attributes):[];return(0,Q.jsxs)(`div`,{className:`grid gap-5 text-label-12 lg:grid-cols-3`,children:[(0,Q.jsxs)(pm,{title:`Owner profile · Business Information`,children:[(0,Q.jsx)(mm,{label:`Primary category`,value:e.primaryCategoryDisplayName??`Not returned`}),(0,Q.jsx)(mm,{label:`Secondary categories`,value:e.additionalCategories.length>0?e.additionalCategories.join(`, `):`Not returned`}),(0,Q.jsx)(mm,{label:`Description`,value:vm(e.description)?e.description:`Not returned`}),(0,Q.jsx)(mm,{label:`Hours`,value:e.regularHours?`Returned by Google`:`Not returned`}),(0,Q.jsx)(mm,{label:`Service area`,value:e.serviceArea?`Returned by Google`:`Not returned`}),(0,Q.jsx)(mm,{label:`Phone`,value:e.primaryPhone??`Not returned`}),(0,Q.jsx)(mm,{label:`Website`,value:e.websiteUri??`Not returned`}),(0,Q.jsx)(mm,{label:`Open status`,value:ym(e.openStatus)}),(0,Q.jsx)(mm,{label:`Opening date`,value:e.openingDate??`Not returned`})]}),(0,Q.jsx)(pm,{title:`Hotel data · Lodging API`,children:t?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(mm,{label:`Last checked`,value:Sm(t.syncedAt)}),(0,Q.jsx)(mm,{label:`Groups returned`,value:String(t.populatedGroupCount)}),(0,Q.jsx)(mm,{label:`Populated groups`,value:i.length>0?i.join(`, `):`None returned`})]}):(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`No Lodging API snapshot was stored for this location.`})}),(0,Q.jsxs)(pm,{title:`Public listing + CTAs`,children:[n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(mm,{label:`Places tier`,value:n.tier}),(0,Q.jsx)(mm,{label:`Last checked`,value:Sm(n.syncedAt)}),(0,Q.jsx)(mm,{label:`Public signals`,value:n.amenities.length>0?n.amenities.join(`, `):`No supported signals detected`})]}):(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`No Places Details snapshot was stored for this location.`}),e.mapsUri&&(0,Q.jsx)(`a`,{href:e.mapsUri,target:`_blank`,rel:`noopener noreferrer`,className:`inline-block text-muted hover:text-neutral`,children:`View on Google Maps →`}),(0,Q.jsx)(`div`,{className:`mt-3 border-t border-default pt-3`,children:r.length===0?(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`No placeActionLinks returned.`}):(0,Q.jsx)(`div`,{className:`grid gap-2`,children:r.map(e=>(0,Q.jsxs)(`div`,{className:`grid gap-0.5`,children:[(0,Q.jsxs)(`span`,{className:`text-label-12-strong text-neutral`,children:[bm(e.placeActionType),e.isPreferred?` · preferred`:``]}),(0,Q.jsxs)(`span`,{className:`text-faint`,children:[bm(e.providerType),e.uri?` · ${xm(e.uri)}`:``]})]},e.placeActionLinkName))})})]})]})}function pm({title:e,children:t}){return(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`mb-2 text-label-12-strong normal-case text-muted`,children:e}),(0,Q.jsx)(`div`,{className:`grid gap-2`,children:t})]})}function mm({label:e,value:t}){return(0,Q.jsxs)(`div`,{className:`grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3`,children:[(0,Q.jsx)(`span`,{className:`text-faint`,children:e}),(0,Q.jsx)(`span`,{className:`min-w-0 break-words text-secondary`,children:t})]})}function hm(e,t,n){return e===t?`positive`:e===0?n:`caution`}function gm(e){switch(e){case`positive`:return`text-positive`;case`caution`:return`text-caution`;case`negative`:return`text-negative`;case`neutral`:return`text-neutral`}}function _m(e){return e===`critical`||e===`high`?`insight-card-negative`:e===`medium`?`insight-card-caution`:``}function vm(e){return typeof e==`string`&&e.trim().length>0}function ym(e){return e?bm(e):`Not returned`}function bm(e){return e?e.toLowerCase().split(`_`).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `):`Unknown`}function xm(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function Sm(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:`short`,day:`numeric`,year:`numeric`})}function Cm(e){return Object.entries(e).filter(([e,t])=>e!==`name`&&e!==`metadata`&&wm(t)).map(([e])=>bm(e.replace(/([a-z])([A-Z])/g,`$1_$2`)))}function wm(e){return e==null?!1:Array.isArray(e)?e.length>0:typeof e!=`object`||Object.keys(e).length>0}function Tm({performance:e,freshness:t,timeseries:n}){let r=e.totals,i=Ee.filter(e=>(r[e]??0)>0),a=Et.filter(e=>(r[e]??0)>0),o=Object.keys(r).filter(e=>(r[e]??0)>0&&Re(e)===`other`).sort((e,t)=>(r[t]??0)-(r[e]??0)),s=Object.keys(r).filter(e=>(r[e]??0)===0).sort(),c=n.map(e=>{let t={date:e.date};for(let[n,r]of Object.entries(e.metrics))t[n]=r;return t}),l=n.find(e=>e.pending)?.date,u=n.length>0?n[n.length-1].date:void 0,d=c.length>0,f=t.dataThroughDate?`Data through ${Yr(t.dataThroughDate)}${t.pendingDays>0?` · ${t.pendingDays}d pending`:``}`:null,p=[...i,...o];return(0,Q.jsxs)(`div`,{className:`mb-6 grid gap-6`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Profile actions · daily`}),f&&(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:f})]}),!d||i.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No profile action activity yet — run a sync.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Em,{data:c,metrics:i,kind:`line`,firstPending:l,lastDate:u}),(0,Q.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-x-5 gap-y-1`,children:p.map(e=>(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[xt(e),` `,(0,Q.jsx)(`span`,{className:`font-mono text-heading`,children:(r[e]??0).toLocaleString()})]},e))})]})]}),d&&a.length>0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft mb-2`,children:`Reach · impressions, daily`}),(0,Q.jsx)(Em,{data:c,metrics:a,kind:`area`,firstPending:l,lastDate:u})]}),s.length>0&&(0,Q.jsxs)(`p`,{className:`text-copy-13 text-faint`,children:[`Not active: `,s.map(e=>xt(e)).join(`, `)]})]})}function Em({data:e,metrics:t,kind:n,firstPending:r,lastDate:i}){return(0,Q.jsx)(`div`,{className:`h-48 w-full`,children:(0,Q.jsx)(le,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(ve,{data:e,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(oe,{stroke:ei,vertical:!1}),(0,Q.jsx)(ue,{dataKey:`date`,tick:Zr,tickLine:!1,axisLine:{stroke:ni},tickFormatter:Hr,minTickGap:24}),(0,Q.jsx)(ge,{tick:Zr,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,Q.jsx)(he,{...ti,labelFormatter:Yr,formatter:(e,t)=>[typeof e==`number`?e.toLocaleString():String(e??0),xt(String(t??``))]}),(0,Q.jsx)(fe,{wrapperStyle:{fontSize:12,color:Kr.text},formatter:e=>xt(e)}),r&&i&&(0,Q.jsx)(de,{x1:r,x2:i,fill:Kr.surface,fillOpacity:.55,stroke:`none`,label:{value:`pending`,position:`insideTopRight`,fill:Kr.textDim,fontSize:12}}),t.map((e,t)=>n===`line`?(0,Q.jsx)(_e,{type:`monotone`,dataKey:e,stroke:zr[t%zr.length],strokeWidth:2,dot:!1,isAnimationActive:!1},e):(0,Q.jsx)(me,{type:`monotone`,dataKey:e,stackId:`reach`,stroke:zr[t%zr.length],fill:zr[t%zr.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},e))]})})})}var Dm=25;function Om(e){return typeof window>`u`?e:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,``)??``}${e}`}function km(e){return e.toLocaleString()}function Am(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return`just now`;if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function jm(e){let t=e.filter(e=>e.kind===Qt[`backlink-extract`]&&!Rc(e.status));return t.length===0?null:t.reduce((e,t)=>e.createdAt>t.createdAt?e:t)}function Mm(e,t){let n=new Date(e??t).getTime(),r=Math.max(0,Math.floor((Date.now()-n)/1e3));if(r<60)return`${r}s`;let i=Math.floor(r/60),a=r%60;return a===0?`${i}m`:`${i}m ${a}s`}function Nm({projectName:e}){let t=rt(),[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(null),[o,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(Date.now()),[b,x]=(0,Z.useState)(0),[S,C]=(0,Z.useState)(!0),[w,T]=(0,Z.useState)(!1),[E,D]=(0,Z.useState)(null),O=(0,Z.useCallback)(async()=>{C(!0),D(null);try{let[t,n,i,o,s]=await Promise.all([Ft().catch(()=>null),Le(e,{excludeCrawlers:!0}).catch(()=>null),Tt(e,{limit:Dm,offset:b,excludeCrawlers:!0}).catch(e=>{if(e instanceof Ln&&e.code===`NOT_FOUND`)return null;throw e}),ln(e,{surface:Bn.backlinks}).catch(()=>null),Bt(e).catch(()=>[])]);f(t),r(n),a(i),u(o);let c=jm(s);h(c)}catch(e){D(e instanceof Error?e.message:`Failed to load backlinks`)}finally{C(!1)}},[e,b]);(0,Z.useEffect)(()=>{O()},[O]),(0,Z.useEffect)(()=>{if(!m)return;let e=m.id,t=!1,n=async()=>{try{let n=await nr(e);if(t)return;Rc(n.status)?(h(null),_(n),await O()):h(e=>e?.id===n.id?{...e,...n}:e)}catch{}},r=window.setInterval(()=>{n()},3e3);return()=>{t=!0,window.clearInterval(r)}},[m,O]),(0,Z.useEffect)(()=>{if(!m)return;let e=window.setInterval(()=>y(Date.now()),1e3);return()=>window.clearInterval(e)},[m]),(0,Z.useEffect)(()=>{if(!g||g.status===`failed`)return;let e=window.setTimeout(()=>_(null),1e4);return()=>window.clearTimeout(e)},[g]);async function k(){T(!0),D(null);try{let t=await sr(e);h(t)}catch(e){e instanceof Ln&&e.code===`MISSING_DEPENDENCY`?D(`DuckDB is not installed. Visit the Backlinks admin page to install it.`):D(e instanceof Error?e.message:`Failed to trigger extract`)}finally{T(!1)}}let A=i?.rows??[],M=i?.total??0,N=n?.excludedLinkingDomains??0,P=Math.floor(b/Dm)+1;return(0,Z.useEffect)(()=>{b>0&&b>=M&&x(0)},[b,M]),(0,Q.jsxs)(`section`,{className:`page-section`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Backlinks`}),(0,Q.jsx)(`h2`,{children:`Referring domains`})]})}),E&&(0,Q.jsx)(Cs,{className:`surface-card p-4 mb-4 bg-negative-soft`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative`,children:E})}),m&&(0,Q.jsx)(Cs,{className:`surface-card p-4 mb-4 bg-info-soft`,children:(0,Q.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Q.jsx)(s,{className:`h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5`,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:`Extract running`}),(0,Q.jsx)(J,{tone:`neutral`,children:m.status}),(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary tabular-nums`,children:[Mm(m.startedAt??null,m.createdAt),` elapsed · refreshing every 3s`]}),(0,Q.jsxs)(`span`,{className:`sr-only`,children:[`now=`,v]})]}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:`Refreshing this project from the current Common Crawl release.`})]})]})}),g&&!m&&(0,Q.jsx)(Cs,{className:`surface-card p-4 mb-4 ${g.status===`failed`?`bg-negative-soft`:`bg-positive-soft`}`,children:(0,Q.jsxs)(`div`,{className:`flex items-start gap-3`,children:[g.status===`failed`?(0,Q.jsx)(`span`,{className:`h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-label-18`,"aria-hidden":!0,children:`!`}):(0,Q.jsx)(l,{className:`h-5 w-5 text-positive-400 shrink-0 mt-0.5`,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{className:`flex-1`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong ${g.status===`failed`?`text-negative`:`text-positive`}`,children:g.status===`failed`?`Extract failed`:`Extract complete`}),g.error?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:Or(g.error)}):g.status===`failed`?null:(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:`Backlinks refreshed from the cached release.`})]})]})}),F()]});function F(){return S?(0,Q.jsx)(Cs,{className:`surface-card p-6`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading backlinks…`})}):I()}function I(){let e=n!==null&&n.totalLinkingDomains>0,r=g?.status===`failed`,i=n!==null&&n.totalLinkingDomains===0&&!r,a=d?.status===`ready`,o=d?.status===`failed`,s=d&&(d.status===`downloading`||d.status===`querying`||d.status===`queued`);return e?ee((0,Q.jsxs)(Q.Fragment,{children:[!K()&&!t&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:w||m!==null,onClick:ci(k),children:[(0,Q.jsx)(p,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),m?`Extract running…`:w?`Queuing…`:`Re-run extract`]}),(0,Q.jsx)(Uc,{label:`About re-running`,children:`Re-queries the current release for this project without downloading it again.`})]}),!K()&&!t&&(0,Q.jsx)(q,{asChild:!0,type:`button`,variant:`outline`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Om(`/backlinks`),children:`Open admin`})})]})):(0,Q.jsx)(Cs,{className:`surface-card p-6`,children:(0,Q.jsxs)(`div`,{className:`flex items-start gap-4`,children:[(0,Q.jsx)(`div`,{className:`flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-bg-elevated text-secondary`,children:(0,Q.jsx)(c,{className:`h-5 w-5`,"aria-hidden":!0})}),(0,Q.jsxs)(`div`,{className:`flex-1`,children:[!d&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`No release sync yet`}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted mt-1`,children:`Run a workspace release sync to populate backlinks for every project in this workspace.`}),!K()&&!t&&(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(q,{asChild:!0,type:`button`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Om(`/backlinks`),children:`Set up backlinks`})})})]}),s&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Sync in progress`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-muted mt-1`,children:[`A workspace release sync is running (`,d.status,d.phaseDetail?` — ${d.phaseDetail}`:``,`). Backlinks will appear here once it finishes.`]}),!K()&&!t&&(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(q,{asChild:!0,type:`button`,variant:`outline`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Om(`/backlinks`),children:`View sync status`})})})]}),o&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Last sync failed`}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted mt-1`,children:d.error??`The workspace release sync failed. Retry from the Backlinks admin page.`}),!K()&&!t&&(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(q,{asChild:!0,type:`button`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Om(`/backlinks`),children:`Go to Backlinks admin`})})})]}),a&&!s&&!i&&!r&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`No backlinks yet for this project`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:[`Release `,(0,Q.jsx)(`code`,{className:`text-neutral`,children:d.release}),` is ready. Run an extract for this project.`]}),!K()&&!t&&(0,Q.jsxs)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:[(0,Q.jsxs)(q,{type:`button`,size:`sm`,disabled:w||m!==null,onClick:ci(k),children:[(0,Q.jsx)(j,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),m?`Extract running…`:w?`Queuing…`:`Run extract`]}),(0,Q.jsx)(Uc,{label:`About extraction`,children:`Queries the current release for this project without downloading it again.`})]})]}),r&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Last extract failed`}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:`See the error above, then check the workspace source before retrying.`}),!K()&&!t&&(0,Q.jsx)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:(0,Q.jsx)(q,{asChild:!0,type:`button`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Om(`/backlinks`),children:`Go to Backlinks admin`})})})]}),i&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`No referring domains found`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:[`The latest release found no referring domains for `,n.targetDomain,`. Try a newer release or re-run this extract.`]}),!K()&&!t&&(0,Q.jsxs)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:[(0,Q.jsx)(q,{asChild:!0,type:`button`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Om(`/backlinks`),children:`Go to Backlinks admin`})}),(0,Q.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:w||m!==null,onClick:ci(k),children:[(0,Q.jsx)(j,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),m?`Extract running…`:w?`Queuing…`:`Re-run extract`]}),(0,Q.jsxs)(Uc,{label:`What does Re-run extract do?`,children:[(0,Q.jsxs)(`span`,{className:`block`,children:[`Re-queries the cached release for `,(0,Q.jsx)(`span`,{className:`text-strong`,children:n.targetDomain}),`. Only useful if the cache files were incomplete last time.`]}),(0,Q.jsx)(`span`,{className:`mt-2 block text-secondary`,children:`No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead.`})]})]})]})]})]})})}function ee(e){if(!n)return null;let t=`release`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Pm,{summary:n,trend:o}),(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted mt-2`,children:[(0,Q.jsx)(`span`,{className:`text-secondary`,children:`Common Crawl`}),` · `,t,` `,(0,Q.jsx)(`code`,{className:`text-secondary`,children:n.release}),` · queried `,Am(n.queriedAt),N>0&&(0,Q.jsxs)(Q.Fragment,{children:[` · `,N,` excluded domain`,N===1?``:`s`]})]}),(0,Q.jsxs)(`div`,{className:`mt-4`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft mb-2`,children:`Top referring domains`}),(0,Q.jsx)(Cs,{className:`surface-card overflow-hidden`,children:(0,Q.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`border-b border-base text-left text-label-12 normal-case text-faint`,children:[(0,Q.jsx)(`th`,{className:`px-4 py-2 text-label-12-strong`,children:`Domain`}),(0,Q.jsx)(`th`,{className:`px-4 py-2 text-right text-label-12-strong`,children:`Linking hosts`})]})}),(0,Q.jsxs)(`tbody`,{children:[A.map(e=>(0,Q.jsxs)(`tr`,{className:`border-b border-mono-900 last:border-0`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2 text-strong`,children:e.linkingDomain}),(0,Q.jsx)(`td`,{className:`px-4 py-2 text-right text-secondary tabular-nums`,children:km(e.numHosts)})]},e.linkingDomain)),A.length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{className:`px-4 py-4 text-label-14 text-muted`,colSpan:2,children:N>0&&M===0?`Every referring domain in this ${t} was a crawler/proxy host (${N} hidden).`:`No referring domains in this ${t}.`})})]})]})}),(0,Q.jsx)(tu,{page:P,pageSize:Dm,visibleRows:A.length,totalRows:M,onPageChange:e=>x((e-1)*Dm)})]}),(0,Q.jsx)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:e})]})}}function Pm({summary:e,trend:t}){let[n,r]=(0,Z.useState)(`referring-domains`),i=t?.groups.find(e=>e.key===`backlinks`),a=new Map(i?.figures.map(e=>[e.key,e])),o=(e,t,n,r,i)=>{let o=a.get(e);return{key:e,label:t,help:n,value:i(r),change:o?zu(o.change,o.unit):void 0,series:o?Vu(o):void 0,formatValue:i,allowDecimals:o?.unit===`fraction`}},s=[o(`referring-domains`,`Referring domains`,`Unique domains linking to ${e.targetDomain}.`,e.totalLinkingDomains,km),o(`hosts`,`Total linking hosts`,`Aggregate linking hosts across referring domains.`,e.totalHosts,km),o(`top-10-concentration`,`Top-10 concentration`,`Share of linking hosts from the 10 largest linking domains.`,Number(e.top10HostsShare),e=>Ut(e))],c=s.some(Mu),l=a.get(`referring-domains`)?.series??[],u=l[0],d=l.at(-1);return(0,Q.jsx)(qu,{name:`Backlinks figures`,groups:[{key:`backlinks`,label:`Every release`,basis:i?Bu(i.figures):void 0,figures:s}],selected:c?[n]:[],onSelect:r,cadence:`release`,span:c&&u&&d?Hu(u,d):void 0,emptyChartMessage:t?`One release so far. The trend starts with the next one.`:`Release history could not be loaded.`})}var Fm={[Cr[`keyword-metrics`]]:`Search demand`,[Cr[`domain-intelligence`]]:`Domain comparison`,[Cr[`ranked-keywords`]]:`Searches you rank for`,[Cr[`market-rankings`]]:`Market rankings`,[Cr[`competitor-discovery`]]:`Organic competitors`,[Cr[`keyword-gaps`]]:`Search gaps`},Im={[Ot.shared]:`Shared`,[Ot.missing]:`Missing`,[Ot.outranked]:`Competitor ahead`},Lm=`Your organic position minus the competitor’s position. Positive means the competitor ranks higher; negative means you rank higher. No gap is calculated when either position is unavailable.`,Rm={[Ge.queued]:`Queued`,[Ge.running]:`Refreshing`,[Ge.completed]:`Completed`,[Ge.partial]:`Partial results`,[Ge.failed]:`Failed`,[Ge.cancelled]:`Cancelled`,[Ge[`reconciliation-required`]]:`Needs review`},zm=25,Bm=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:1}),Vm=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:2}),Hm=Intl.DateTimeFormat().resolvedOptions().timeZone,Um=new Intl.DisplayNames([`en`],{type:`language`,fallback:`none`}),Wm=`min-h-11 w-full rounded-md border border-default bg-bg px-3 py-2 text-label-14 text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,Gm=`px-4 py-3 text-right align-top tabular-nums whitespace-nowrap`,Km=`min-w-56 px-4 py-3 text-left align-top text-label-14`,qm=`Position on the page, counting maps and other blocks`,Jm={overview:`Overview`,"latest-rankings":`Latest rankings`,...Fm},Ym=[Cr[`market-rankings`],Cr[`ranked-keywords`],Cr[`keyword-metrics`],Cr[`domain-intelligence`],Cr[`competitor-discovery`],Cr[`keyword-gaps`]];function Xm(e){return e?.status===Ge.queued||e?.status===Ge.running}function Zm(e){return e.status===Ge.completed||e.status===Ge.partial}function Qm({value:e,currency:t=!1}){return e===null?(0,Q.jsx)(`span`,{className:`text-muted`,"aria-label":`Not supplied`,children:`—`}):(0,Q.jsx)(Q.Fragment,{children:t?Vm.format(e):Bm.format(e)})}function $m({status:e}){let t=e===Ge.completed?`positive`:e===Ge.failed?`negative`:e===Ge.partial||e===Ge[`reconciliation-required`]?`caution`:`neutral`;return(0,Q.jsx)(J,{tone:t,children:Rm[e]})}function eh(e){let t=xe(e).split(`/`).at(-1)??e,n=ct.safeParse(t.replaceAll(`_`,`-`));return n.success?Fm[n.data]:t.replaceAll(/[-_]/g,` `)}function th(e){return e===`mobile`?`phone results`:e===`desktop`?`computer results`:`device not specified by source`}function nh(e){return e.capabilities.includes(Cr[`market-rankings`])?`Market locations`:`Location ${e.locationCode}`}function rh(e){try{return Um.of(e)??e}catch{return e}}function ih(e){return e.capabilities.includes(Cr[`market-rankings`])?`searches`:`tasks`}function ah(e){return e.capability!==Cr[`market-rankings`]||![Ge.queued,Ge.running,Ge.completed].includes(e.status)}function oh(e,t){let n=e.capabilities.includes(Cr[`market-rankings`]);return`${t} ${t===1?n?`search`:`task`:ih(e)}`}function sh(e,t){return Number.isFinite(Date.parse(e))?Fe(Ke(e,t)):null}var ch={[Ge.failed]:`Latest refresh failed`,[Ge.cancelled]:`Latest refresh cancelled`,[Ge[`reconciliation-required`]]:`Latest refresh needs review`};function lh(e,t){let n=e&&e.id!==t?.id?ch[e.status]:void 0;if(e&&n)return{label:n,text:`${n}. ${e.error??`Open Refresh history for details.`}${t?` Showing the refresh before it.`:``}`};if(!t)return null;if(t.failedTasks>0){let e=`${oh(t,t.failedTasks)} failed`,n=t.capabilities.includes(Cr[`market-rankings`])?`Their queries show as Failed.`:`Open Refresh history for details.`;return{label:e,text:`${e}: ${t.failedTasks} of ${oh(t,t.taskCount)} in this refresh returned no results. ${n}`}}return t.status===Ge.partial?{label:`Partial results`,text:`Partial results: ${t.error??`some ${ih(t)} returned only part of their results or did not run. Open Refresh history for details.`}`}:null}function uh({source:e}){return(0,Q.jsxs)(`dl`,{className:`grid gap-x-8 gap-y-2 text-label-13 sm:grid-cols-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Dataset`}),(0,Q.jsx)(`dd`,{children:eh(e.dataset)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Search engine`}),(0,Q.jsxs)(`dd`,{children:[`Google · `,th(e.device)]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Provider geography`}),(0,Q.jsxs)(`dd`,{children:[`Location `,e.locationCode,` · `,e.languageCode]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Collected`}),(0,Q.jsx)(`dd`,{children:un(e.collectedAt,Hm)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Source updated`}),(0,Q.jsx)(`dd`,{children:e.sourceUpdatedAt?Xe(e.sourceUpdatedAt):`Not supplied`})]})]})}function dh({label:e,source:t,children:n}){return(0,Q.jsxs)(`details`,{className:`group/seo-evidence text-left`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-13 text-secondary hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(m,{className:`size-3.5 shrink-0 transition-transform group-open/seo-evidence:rotate-90`,"aria-hidden":`true`}),`Details`,(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` for `,e]})]}),(0,Q.jsxs)(`div`,{className:`min-w-56 space-y-4 pb-3 text-label-13 text-secondary`,children:[n,t&&(0,Q.jsx)(uh,{source:t})]})]})}function fh({error:e,retry:t}){return(0,Q.jsxs)(`div`,{role:`alert`,className:`flex flex-wrap items-center justify-between gap-3 rounded-md border border-default p-4 text-label-14`,children:[(0,Q.jsx)(`p`,{children:ws(e)}),(0,Q.jsx)(q,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:t,children:`Retry`})]})}function ph({title:e,children:t,action:n}){return(0,Q.jsxs)(`div`,{className:`py-12 text-center`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-14 text-heading`,children:e}),(0,Q.jsx)(`p`,{className:`mx-auto mt-2 max-w-lg text-copy-14 text-secondary`,children:t}),n&&(0,Q.jsx)(`div`,{className:`mt-4`,children:n})]})}function mh(e,t){return!e||!t?.supported?[]:Ym.filter(n=>e.capabilities.includes(n)&&(t.capabilities?.includes(n)??!0))}function hh({projectName:e}){let{isAdmin:t}=si(),n=V({strict:!1}),r=B(),i=W(xa({client:Y,path:{name:e}})),a=W(ho({client:Y,path:{name:e}})),s=W({...Oa({client:Y,path:{name:e,id:n.seoRunId??``}}),enabled:!!n.seoRunId}),[c,l]=(0,Z.useState)(null),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(null),h=n.seoProfileId??s.data?.profileId,g=h?a.data?.profiles.find(e=>e.id===h):n.seoRunId?void 0:a.data?.profiles[0],_=(t,n=!1)=>{n&&(m.current=t),l(null),r({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoProfileId:t,seoRunId:void 0,seoView:void 0,seoRegion:void 0,seoMarket:void 0,seoShow:void 0,seoSort:void 0,seoQ:void 0,seoTrendDays:void 0,seoTrendMetric:void 0,seoTrendKeyword:void 0})})},v=i.data?.access.canWrite===!0&&!K()&&!rt(),y=()=>{l(null),u.current?.focus()};if((0,Z.useEffect)(()=>{!n.seoProfileId&&g&&r({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoProfileId:g.id}),replace:!0})},[r,e,n.seoProfileId,g]),(0,Z.useLayoutEffect)(()=>{m.current===null||g?.id!==m.current||n.seoRunId||c||(m.current=null,(d.current??f.current)?.focus())},[c,n.seoRunId,g]),i.error)return(0,Q.jsx)(fh,{error:i.error,retry:()=>{i.refetch()}});if(a.error)return(0,Q.jsx)(fh,{error:a.error,retry:()=>{a.refetch()}});if(!i.data||!a.data)return(0,Q.jsx)(`p`,{role:`status`,className:`py-10 text-copy-14 text-secondary`,children:`Loading SEO data…`});let b=i.data.available&&i.data.connections.some(e=>e.capabilities.length>0),x=new Set(i.data.scopes.flatMap(e=>i.data.connections.flatMap(t=>mh(t,e)))),S=Cr[`market-rankings`],C=b&&[...x].some(e=>e!==S),w=b&&x.has(S),T=g&&(C||g.rankings&&w),E=t&&!K()&&!rt()?(0,Q.jsx)(q,{asChild:!0,variant:`secondary`,children:(0,Q.jsx)(`a`,{href:`https://github.com/Canonry/canonry/blob/main/docs/seo-data.md#host-configuration`,target:`_blank`,rel:`noopener noreferrer`,children:`SEO setup guide`})}):void 0,D=g&&i.data.scopes.find(e=>e.kind===g.scope.kind&&e.key===(g.scope.key??null)),O=g&&(!n.seoRunId||s.data?.profileId===g.id&&!s.error),k=a.data.profiles.length>1||!O,A=(e,t)=>{u.current=e,l({profile:t,id:t?.id??crypto.randomUUID()})},j=a.data.profiles.length>0&&(0,Q.jsxs)(`div`,{className:`flex w-full min-w-0 flex-wrap items-center gap-x-3 gap-y-1 sm:w-auto`,children:[k?(0,Q.jsxs)(`label`,{className:`flex min-w-0 basis-full items-center gap-2 sm:basis-auto sm:max-w-64`,children:[(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:`Profile`}),(0,Q.jsxs)(`select`,{ref:d,"aria-label":`SEO profile`,value:g?.id??``,onChange:e=>_(e.currentTarget.value,document.activeElement===e.currentTarget),className:`${Wm} min-w-0 sm:min-h-9`,children:[!g&&(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Profile unavailable`}),a.data.profiles.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}):(0,Q.jsxs)(`span`,{ref:f,tabIndex:-1,className:`min-w-0 flex-1 break-words rounded-sm text-copy-14-strong text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:`SEO profile: `}),g?.name]}),v&&(C||T)&&(0,Q.jsx)(`div`,{className:`ml-auto sm:ml-0`,children:(0,Q.jsx)(Od,{label:`Manage profiles`,menuLabel:`SEO profile actions`,triggerRef:p,items:[...T?[{key:`edit`,label:`Edit profile`,onSelect:()=>A(p.current,g)}]:[],...C?[{key:`new`,label:`New profile`,onSelect:()=>A(p.current)}]:[]]})}),g&&g.scope.kind!==Rt.project&&(0,Q.jsx)(`span`,{className:`w-full break-words text-copy-13 text-secondary md:w-auto`,children:D?.label??g.scope.key??g.scope.kind})]});return(0,Q.jsxs)(`section`,{"aria-label":`SEO`,className:`min-w-0 space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-20 text-heading`,children:`SEO`}),j,a.data.profiles.length===0&&v&&C&&(0,Q.jsxs)(q,{variant:`secondary`,className:`ml-auto`,onClick:e=>A(e.currentTarget),children:[(0,Q.jsx)(o,{"aria-hidden":`true`,className:`size-4`}),`New profile`]})]}),c&&(0,Q.jsx)(pg,{projectName:e,context:i.data,profile:c.profile,id:c.id,onClose:y,onSaved:e=>_(e,!0)},c.id),!rt()&&!i.data.available&&a.data.profiles.length>0&&(0,Q.jsx)(`p`,{role:`status`,className:`rounded-md border border-default px-4 py-3 text-copy-14 text-secondary`,children:i.data.reason??`Configure an SEO data provider to refresh saved profiles.`}),n.seoRunId&&s.error?(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsx)(fh,{error:s.error,retry:()=>{s.refetch()}}),g?(0,Q.jsx)(q,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:()=>_(g.id),children:`View latest data`}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Select a profile to view its latest data.`})]}):n.seoRunId&&s.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`py-10 text-copy-14 text-secondary`,children:`Loading refresh…`}):g&&s.data&&s.data.profileId!==g.id?(0,Q.jsxs)(ph,{title:`Refresh belongs to another profile`,children:[`Choose the refresh’s profile, or return to the selected profile’s latest data.`,(0,Q.jsx)(q,{variant:`secondary`,className:`mt-4 pointer-coarse:min-h-11`,onClick:()=>_(g.id),children:`View latest data`})]}):g?(0,Q.jsx)(gh,{projectName:e,profile:g,context:i.data,selectedRunId:n.seoRunId,onLatest:()=>_(g.id)},`${g.id}:${g.revision}:${n.seoRunId??``}`):!C&&a.data.profiles.length===0?b?w?(0,Q.jsx)(ph,{title:`No SEO profiles yet`,children:`Set up market rankings with the CLI or API.`}):(0,Q.jsx)(ph,{title:`SEO scope unavailable`,children:i.data.scopes.find(e=>e.reason)?.reason??`No datasets are available for this project’s measurement scopes.`}):(0,Q.jsx)(ph,{title:`Configure an SEO data provider`,action:E,children:E?`SEO sources are configured on the Canonry server.`:`Ask your Canonry administrator to connect an SEO data source.`}):h?(0,Q.jsx)(ph,{title:`Profile unavailable`,children:`This saved profile is no longer available. Select another profile to view its data.`}):!c&&(0,Q.jsx)(ph,{title:`No SEO data yet`,children:v?`Create a profile to choose the scope, source, and searches to measure.`:`An SEO profile is needed before data can be collected.`})]})}function gh({projectName:e,profile:t,context:n,selectedRunId:r,onLatest:i}){let a=z(),o=V({strict:!1}),c=B(),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),[d,f]=(0,Z.useState)(!1),[p,h]=(0,Z.useState)(null),g=(0,Z.useRef)(null),v=(0,Z.useRef)(null),y={name:e},b=ro({client:Y,path:y,query:{profileId:t.id,runId:r}}),x=W({...b,refetchInterval:e=>Xm(e.state.data?.latestRun)?2e3:!1}),S=ie({...Si({client:Y}),meta:{skipGlobalErrorToast:!0}}),C=ie({...Li({client:Y}),meta:{skipGlobalErrorToast:!0}}),w=x.data?.latestRun,T=x.data?.evidenceRun,E=x.data?.evidenceRun?.capabilities??t.capabilities,D=[`overview`,...Ym.filter(e=>E.includes(e))],O=o.seoRegion||o.seoMarket||o.seoShow||o.seoSort||o.seoQ,k=!r&&O&&E.includes(Cr[`market-rankings`])?Cr[`market-rankings`]:`overview`,j=o.seoView===`latest-rankings`?o.seoView:D.find(e=>e===o.seoView),M=j??k,N=o.seoView===`activity`||!(!r||j),P=d||N,F=()=>{f(!1),N&&r?i():N&&c({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoView:void 0}),replace:!0})},I=t=>{f(!1),c({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoRunId:t,seoView:`overview`,seoRegion:void 0,seoMarket:void 0,seoShow:void 0,seoSort:void 0,seoQ:void 0,seoTrendDays:void 0,seoTrendMetric:void 0,seoTrendKeyword:void 0})})},ee=(t,n=!1)=>{n&&l.current?.querySelector(`[data-seo-view="${t}"]`)?.focus();let i=t===Cr[`market-rankings`]?{}:{seoRegion:void 0,seoMarket:void 0,seoShow:void 0,seoSort:void 0,seoQ:void 0};c({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,...i,seoView:t===`overview`&&!r?void 0:t})})},L=Xm(w),R=S.isPending||C.isPending,te=n.access.canRun&&!K()&&!rt(),ne=n.connections.find(e=>e.id===t.connectionId),H=n.scopes.find(e=>e.kind===t.scope.kind&&e.key===(t.scope.key??null)),re=W({...qi({client:Y,path:y,query:{kind:Pn[`seo-sync`]}}),retry:!1}),U=!re.isError&&re.data?.enabled&&re.data.nextRunAt?re.data.nextRunAt:null,ae=U?sh(U,re.data?.timezone??`UTC`):null,oe=T?.finishedAt&&Zm(T)?sh(T.finishedAt,Hm):null,se=te&&ne&&(t.capabilities.includes(Cr[`market-rankings`])?`Refresh now runs new Google searches through ${ne.label} for this profile’s tracked queries and markets.`:`Refresh now requests the latest data available from ${ne.label}. The source may return the same readings until its dataset updates.`),ce=[oe&&`Last refresh shows when Canonry saved these results.`,ae&&`Next scheduled refresh ${ae}.`,se].filter(Boolean).join(` `),le=L?null:lh(w,T);return(0,Z.useEffect)(()=>{w&&(Xm(w)?v.current=w.id:v.current===w.id&&(v.current=null,ui(a,`seo`,{projectName:e,profileId:t.id})))},[w,t.id,e,a]),(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-5 gap-y-2 border-t border-subtle pt-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-copy-13 text-secondary`,"aria-live":`polite`,children:[x.data&&(0,Q.jsx)(`p`,{children:oe&&T?.finishedAt?(0,Q.jsxs)(Q.Fragment,{children:[r?`Viewing saved results from`:`Last refresh`,` `,(0,Q.jsx)(`time`,{dateTime:T.finishedAt,title:un(T.finishedAt,Hm)??void 0,children:oe})]}):`No saved results`}),!r&&ce&&(0,Q.jsx)(X,{placement:`bottom`,text:`About refreshes. ${ce}`}),L&&w&&(0,Q.jsxs)(`p`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(s,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),w.cancelRequested?`Cancellation requested`:Rm[w.status],` · `,w.completedTasks,` of `,w.taskCount,` `,ih(w),` completed`]}),le&&(0,Q.jsx)(X,{tone:`caution`,placement:`bottom`,label:le.label,text:le.text})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[w&&(0,Q.jsxs)(q,{ref:u,variant:`ghost`,size:`sm`,"aria-haspopup":`dialog`,"aria-expanded":P,onClick:()=>f(!0),children:[(0,Q.jsx)(A,{className:`size-4`,"aria-hidden":`true`}),`Refresh history`]}),r?(0,Q.jsx)(q,{variant:`secondary`,onClick:i,children:`View latest data`}):te&&(0,Q.jsxs)(q,{disabled:R||L||!x.data||!n.available||!ne,onClick:ci(async()=>{if(!(!te||r||L||R)){h(null);try{if(!g.current){let e=await S.mutateAsync({path:y,body:{profileId:t.id}});if(e.availability!==ft.ready){h(e.reason??`This profile cannot be refreshed. Review its scope and source.`);return}g.current={quoteToken:e.token,idempotencyKey:crypto.randomUUID()}}let n=await C.mutateAsync({path:y,body:g.current});g.current=null,Xm(n)&&(v.current=n.id,Fs({id:n.id,projectId:n.projectId,projectName:e,projectLabel:e,kind:Qt[`seo-sync`],sourceAction:`seo-sync`,lastAnnouncedStatus:n.status})),a.setQueryData(b.queryKey,e=>e&&(!e.latestRun||e.latestRun===w)?{...e,latestRun:n}:e),x.refetch({cancelRefetch:!1})}catch(e){Ts(e).code===`VALIDATION_ERROR`&&(g.current=null),h(ws(e))}}}),children:[(0,Q.jsx)(_,{"aria-hidden":`true`,className:`size-4 ${R?`motion-safe:animate-spin`:``}`}),R?`Starting refresh…`:L?`Refresh in progress`:g.current?`Retry refresh`:`Refresh now`]})]})]}),p&&(0,Q.jsxs)(`p`,{role:`alert`,className:`rounded-md border border-default p-4 text-copy-14 text-secondary`,children:[p,g.current&&` Retry uses the same request, so it will not start a duplicate refresh.`]}),!r&&T&&T.profileRevision!==t.revision&&(0,Q.jsxs)(`p`,{role:`status`,className:`text-copy-13 text-secondary`,children:[`Showing results from earlier profile settings.`,te&&n.available&&ne&&` Refresh to use the current settings.`]}),!rt()&&H&&!H.supported&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:H.reason??`This scope is not supported for domain data.`}),x.isRefetchError&&(0,Q.jsx)(fh,{error:x.error,retry:()=>{x.refetch()}}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`nav`,{ref:l,"aria-label":`SEO reports`,className:`flex min-w-0 flex-wrap gap-x-5 border-b border-subtle`,children:D.map(e=>{let t=M===e||M===`latest-rankings`&&e===`overview`;return(0,Q.jsx)(`button`,{"data-seo-view":e,type:`button`,"aria-pressed":t,className:`min-h-11 shrink-0 border-b-2 whitespace-nowrap text-button-14 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-mono-400 ${t?`border-strong text-primary`:`border-transparent text-secondary hover:text-primary`}`,onClick:()=>ee(e),children:Jm[e]},e)})}),x.isLoadingError?(0,Q.jsx)(`div`,{className:`pt-4`,children:(0,Q.jsx)(fh,{error:x.error,retry:()=>{x.refetch()}})}):x.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`py-8 text-copy-14 text-secondary`,children:`Loading saved data…`}):M===`overview`||M===`latest-rankings`?(0,Q.jsx)(wh,{projectName:e,profileId:t.id,data:x.data,active:L,canRun:te,nextRefresh:ae,snapshot:!!r||M===`latest-rankings`,historical:!!r,onOpen:e=>ee(e,!0)}):(0,Q.jsx)(jh,{projectName:e,profileId:t.id,runId:x.data.evidenceRunId,view:M,active:L,nextRefresh:ae},`${t.id}:${M}:${x.data.evidenceRunId??`empty`}`)]}),(0,Q.jsx)(_c,{title:`Refresh history`,subtitle:t.name,open:P,onClose:F,onCloseAutoFocus:e=>{let t=u.current;t?.isConnected&&!(N&&r)&&(e.preventDefault(),t.focus())},children:P&&(0,Q.jsx)(fg,{projectName:e,profileId:t.id,canRun:te,selectedRunId:r,exactRefresh:N&&!!r,onViewSaved:I,onLatest:i})}),(0,Q.jsxs)(`details`,{className:`group/seo-data border-t border-subtle text-label-14 text-secondary`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(m,{className:`size-3.5 shrink-0 transition-transform group-open/seo-data:rotate-90`,"aria-hidden":`true`}),`Data details`]}),(0,Q.jsxs)(`div`,{className:`space-y-4 pb-3 text-label-13`,children:[(0,Q.jsxs)(`p`,{children:[`Current profile source: `,rt()?`Fictional demo data`:ne?.label??`Source unavailable`,`. Google · `,th(t.rankings?.device??`unspecified`),` · `,t.rankings?`Market locations`:`Location ${t.locationCode}`,` · `,t.languageCode,`.`]}),x.data?.evidenceRun&&(0,Q.jsxs)(`p`,{children:[`Saved evidence: `,x.data.evidenceRun.scope.kind,x.data.evidenceRun.scope.key?` · ${x.data.evidenceRun.scope.key}`:``,x.data.evidenceRun.scope.expectedPlanRevision===void 0?``:` · plan revision ${x.data.evidenceRun.scope.expectedPlanRevision}`,`. `,nh(x.data.evidenceRun),` · `,x.data.evidenceRun.languageCode,` · profile revision `,x.data.evidenceRun.profileRevision,`.`]}),(0,Q.jsx)(`p`,{children:`These are provider estimates and observed search rankings. Missing values are shown as a dash. Difficulty is a source score out of 100.`}),(0,Q.jsx)(`p`,{children:`Current profile targets:`}),(0,Q.jsx)(`ul`,{className:`space-y-1`,children:t.targets.map((e,t)=>(0,Q.jsxs)(`li`,{className:`break-words`,children:[e.value,` · `,e.includeSubdomains?`includes subdomains`:`exact host`]},t))}),t.scope.expectedPlanRevision!==void 0&&(0,Q.jsxs)(`p`,{children:[`Saved measurement plan revision `,t.scope.expectedPlanRevision,`.`]}),x.data?.summary&&(0,Q.jsx)(uh,{source:x.data.summary.provenance})]})]})]})}var _h=6,vh=new Intl.DateTimeFormat(`en-US`,{month:`short`,year:`numeric`,timeZone:`UTC`}),yh=new Intl.DateTimeFormat(`en-US`,{month:`short`,year:`2-digit`,timeZone:`UTC`}),bh=new Intl.NumberFormat(`en-US`,{notation:`compact`,maximumFractionDigits:1}),xh=[{days:180,label:`180 days`},{days:90,label:`90 days`},{days:30,label:`30 days`}],Sh={inTop10:{label:`In the top 10`},organicKeywords:{label:`Ranked searches`},estimatedOrganicTraffic:{label:`Estimated organic traffic`,help:`Modeled search traffic for this target and geography. Site traffic is measured separately.`},page1:{label:`On page 1`,help:`Non-brand tracked queries with a Google organic position from 1 to 10. Each query is counted separately in each of its markets.`},rankOrganic:{label:`Organic position`,help:`Ranks come from the searches returned in each saved refresh. A gap means this search had no position in that refresh’s saved results.`}};function Ch({projectName:e,data:t,days:n,metric:r,keyword:i,selectionPending:a,selectionFailed:o,onRangeChange:s,onMetricChange:c,onKeywordChange:l,refreshing:u,onLatest:d}){let f=t.kind===Ht.market,p=t.kind===Ht.ranked,m=et[t.kind],h=m.map(e=>{let n=t.points.filter(t=>t[e]!=null).at(-1)?.[e]??null;return{...Sh[e],key:e,value:n===null?`—`:Bm.format(n),stateValue:n===null,interactive:!0,change:zu(t.changes[e]??null,$n.count),series:t.points.map(t=>({date:t.observedAt,current:t[e]??null})),formatValue:e=>p?Bm.format(e):bh.format(e),formatExact:e=>Bm.format(e),allowDecimals:e===`estimatedOrganicTraffic`,reverseValueAxis:p}}),g=m.find(e=>t.changes[e]!=null)??m.find(e=>t.points.some(t=>t[e]!=null))??m[0],_=r&&m.includes(r)?r:g,v=f?`Google rankings over time`:p?`Ranked search trends`:`Organic search performance`,y=[t.target&&Dh(t.target),`Google`,f?`Market locations`:null,t.languageCode&&rh(t.languageCode)].filter(Boolean).join(` · `),b=(a?i??t.keyword:t.keyword)??``,x=t.rankedKeywords??[],S=b!==``&&!x.includes(b);bc(e,{view:`seo`,seoProfileId:t.profileId,seoTrend:{days:t.days,metric:_,...p&&t.keyword?{keyword:t.keyword}:{}}});let C=t.points[0]?.observedAt,w=t.points.at(-1)?.observedAt,T=C&&w&&C!==w?Hu({date:C,observedAt:C},{date:w,observedAt:w}):void 0,D=t.points.filter(e=>e[_]!=null),O=D.length,k=D.at(-1),A=k?sh(k.observedAt,Hm):null,j=k&&k!==t.points.at(-1),M=m.length>1?Bu(m.map(e=>({change:t.changes[e]??null}))):void 0,N=[p&&t.keyword?`“${t.keyword}”`:null,`${t.days} days`].filter(Boolean).join(` · `),P=a?`${o?`Showing previous selection`:`Loading selection. Showing`} ${N}.`:void 0,F=[A&&j&&`Data through ${A}.`,T&&`Chart dates ${T}.`,O>=2&&`${Bm.format(O)} comparable refreshes.`,O===1&&A&&!j&&`Reading from ${A}.`,M&&`Change ${M}.`,t.marketQueryCount!==null&&`${Bm.format(t.marketQueryCount)} non-brand queries across markets.`,!f&&t.locationCode!==null&&`Search location code ${t.locationCode}.`].filter(Boolean).join(` `),I=O===1?n<180?`One saved reading in this range. Choose a longer range to see a trend.`:`One saved reading in this range. Trends appear after another comparable refresh.`:n<180?`No comparable readings in this range. Choose a longer range.`:`No comparable readings for this selection.`,ee=e=>{let t=Yn.safeParse(Number(e));t.success&&s(t.data)};return(0,Q.jsxs)(`section`,{"aria-label":v,className:`material-base min-w-0 px-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-x-5 gap-y-1 py-2 sm:py-3`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-20 text-heading`,children:v}),F&&(0,Q.jsx)(X,{placement:`bottom`,text:`About this chart. ${F}`})]}),(0,Q.jsx)(`p`,{className:`break-words text-copy-13 text-secondary`,children:y})]}),p&&(x.length>0||b)&&(0,Q.jsxs)(`label`,{className:`flex w-full min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-label-13 text-secondary sm:w-auto sm:max-w-96`,children:[`Search to chart`,(0,Q.jsxs)(`select`,{className:`${Wm} min-w-0 flex-1 sm:min-h-9`,value:b,"aria-busy":u,onChange:e=>l(e.currentTarget.value),children:[i&&(0,Q.jsx)(`option`,{value:``,children:`Profile default`}),S&&(0,Q.jsx)(`option`,{value:b,children:b}),x.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]})]}),(0,Q.jsx)(`div`,{className:`border-t border-subtle`,children:(0,Q.jsx)(qu,{name:v,groups:[{key:`seo`,figures:h,basis:M}],selected:[_],onSelect:e=>{let t=Zt.safeParse(e);t.success&&c(t.data)},frame:`none`,cadence:`refresh`,compact:!0,instants:!0,chartHeight:180,minimumReadings:2,showChartData:!0,span:T,currentLabel:p&&t.keyword?`“${t.keyword}”`:void 0,hideSpan:!0,basisInNotice:!0,refreshing:u,emptyChartMessage:I,notice:P,controls:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`flex items-center gap-2 text-label-13 text-secondary`,children:[`Range`,(0,Q.jsx)(`select`,{className:`${Wm} min-w-28 sm:min-h-9`,"aria-label":`SEO trend range`,"aria-busy":u,value:n,onChange:e=>ee(e.target.value),children:xh.map(e=>(0,Q.jsx)(`option`,{value:e.days,children:e.label},e.days))})]}),(0,Q.jsxs)(q,{variant:`ghost`,size:`sm`,onClick:d,children:[`Latest rankings`,(0,Q.jsx)(E,{className:`size-4`,"aria-hidden":`true`})]})]})})})]})}function wh({snapshot:e=!1,historical:t=!1,...n}){let r=V({strict:!1}),i=B(),a=r.seoTrendDays??180,o=r.seoTrendKeyword,s=r.seoTrendMetric,c=(0,Z.useRef)(null),{data:l,projectName:u,profileId:d,onOpen:f}=n,p=l.evidenceRun?.capabilities.some(e=>e===Cr[`domain-intelligence`]||e===Cr[`market-rankings`]||e===Cr[`ranked-keywords`])===!0,m=_o({client:Y,path:{name:u},query:{profileId:d,days:a,keyword:o}}),h=(0,Z.useRef)(void 0),g=W({...m,enabled:!e&&p,placeholderData:te});if((0,Z.useEffect)(()=>{g.data&&!g.isPlaceholderData&&(h.current=g.data)},[g.data,g.isPlaceholderData]),(0,Z.useEffect)(()=>{e&&c.current?.focus()},[e]),e)return(0,Q.jsxs)(`div`,{className:`pt-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,Q.jsx)(`h3`,{ref:c,tabIndex:-1,className:`text-heading-16 text-heading focus:outline-none`,children:`Saved rankings and search data`}),!t&&(0,Q.jsx)(q,{variant:`ghost`,size:`sm`,onClick:()=>f(`overview`),children:`Back to overview`})]}),(0,Q.jsx)(kh,{...n},l.evidenceRunId??`empty`)]});if(!p)return(0,Q.jsx)(kh,{...n},l.evidenceRunId??`empty`);let _=g.data??h.current;if(g.error&&!_)return(0,Q.jsx)(`div`,{className:`pt-4`,children:(0,Q.jsx)(fh,{error:g.error,retry:()=>{g.refetch()}})});if(!_)return(0,Q.jsx)(`p`,{role:`status`,className:`py-10 text-copy-14 text-secondary`,children:`Loading SEO trends…`});let{kind:v}=_;if(!v||!(_.hasRankingReadings??et[v].some(e=>_.points.some(t=>t[e]!=null)))&&v!==Ht.market&&!(v===Ht.ranked&&o)&&(l.keywordMetricsCount>0||l.rankedKeywordCount>0))return(0,Q.jsx)(kh,{...n},l.evidenceRunId??`empty`);let y=e=>{i({to:`/projects/$projectName/seo-data`,params:{projectName:u},search:t=>({...t,...e}),replace:!0,resetScroll:!1})};return(0,Q.jsxs)(`div`,{className:`space-y-3 pt-4`,children:[(0,Q.jsx)(Ch,{projectName:u,data:{..._,kind:v},days:a,metric:s,keyword:o,selectionPending:g.isPlaceholderData||!g.data,selectionFailed:g.isError,refreshing:g.isFetching,onLatest:()=>f(`latest-rankings`),onRangeChange:e=>{y({seoTrendDays:e}),ze(`window`)},onMetricChange:e=>{y({seoTrendMetric:e}),ze(`other`)},onKeywordChange:e=>{y({seoTrendKeyword:e||void 0}),ze(`other`)}}),g.error&&(0,Q.jsx)(fh,{error:g.error,retry:()=>{g.refetch()}})]})}function Th({title:e,caption:t,category:n,unit:r,points:i,view:a,onOpen:o,controls:s,monthAxis:c=!1,rankAxis:l=!1}){let u=(0,Z.useId)(),d=(0,Z.useId)(),f=(0,Z.useId)(),[p,m]=(0,Z.useState)(!1),h=i.map(e=>({...e,plotted:e.value??(l||c?null:0),display:e.value===null?`—`:Bm.format(e.value)})),g=new Map(i.map(e=>[e.label,e.tick??e.label])),_=e=>bh.format(e),v=e=>g.get(e)??e,y=(0,Q.jsx)(he,{...ti,labelFormatter:e=>typeof e==`string`?e:``,formatter:(e,t,n)=>{let i=n.payload;return[(i&&typeof i==`object`&&`display`in i&&typeof i.display==`string`?i.display:void 0)??(typeof e==`number`?Bm.format(e):`—`),r]}}),b=zr[1];return(0,Q.jsxs)(`section`,{"aria-labelledby":u,className:`material-base min-w-0 p-4 sm:p-5`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1`,children:[(0,Q.jsx)(`h3`,{id:u,className:`text-heading-20 text-heading`,children:e}),(0,Q.jsx)(`p`,{id:d,className:`break-words text-copy-13 text-secondary`,children:t})]}),s&&(0,Q.jsx)(`div`,{className:`mt-3`,children:s}),(0,Q.jsx)(`p`,{className:`mt-4 text-label-12 text-secondary`,children:r}),(0,Q.jsx)(`div`,{className:`min-w-0 pt-1`,"aria-hidden":`true`,children:(0,Q.jsx)(le,{width:`100%`,height:c?220:i.length*38+34,children:c?(0,Q.jsxs)(pe,{data:h,accessibilityLayer:!1,margin:{top:12,right:12,bottom:2,left:0},children:[(0,Q.jsx)(oe,{stroke:ei,vertical:!1}),(0,Q.jsx)(ue,{dataKey:`label`,tick:Zr,tickFormatter:v,tickLine:!1,axisLine:!1,minTickGap:16}),(0,Q.jsx)(ge,{tick:Zr,tickFormatter:_,tickLine:!1,axisLine:!1,allowDecimals:!1,width:46}),y,(0,Q.jsx)(ae,{dataKey:`plotted`,fill:b,maxBarSize:46,minPointSize:1,radius:[3,3,0,0],isAnimationActive:!1})]}):(0,Q.jsxs)(ve,{data:h,layout:`vertical`,accessibilityLayer:!1,margin:{top:3,right:58,bottom:2,left:0},children:[(0,Q.jsx)(oe,{stroke:ei,horizontal:!1}),(0,Q.jsx)(ge,{type:`category`,dataKey:`label`,tick:Zr,tickFormatter:v,tickLine:!1,axisLine:!1,width:a===Cr[`domain-intelligence`]?48:112,interval:0}),(0,Q.jsx)(ue,{type:`number`,tick:Zr,tickFormatter:e=>l&&e<1?``:_(e),tickLine:!1,axisLine:!1,allowDecimals:!1,domain:l?[1,`auto`]:[0,`auto`]}),y,l?(0,Q.jsx)(_e,{dataKey:`plotted`,stroke:`none`,dot:{r:5,fill:b,stroke:b},activeDot:!1,isAnimationActive:!1,children:(0,Q.jsx)(se,{dataKey:`display`,position:`right`,fill:Zr.fill,fontSize:12})}):(0,Q.jsxs)(ae,{dataKey:`plotted`,fill:b,barSize:18,minPointSize:1,radius:[0,3,3,0],isAnimationActive:!1,children:[h.map((e,t)=>(0,Q.jsx)(ce,{fill:e.value===null?`transparent`:b},`${e.label}:${t}`)),(0,Q.jsx)(se,{dataKey:`display`,position:`right`,fill:Zr.fill,fontSize:12})]})]})})}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-3 border-t border-subtle pt-2`,children:[(0,Q.jsx)(q,{variant:`ghost`,size:`sm`,"aria-expanded":p,"aria-controls":f,onClick:()=>m(e=>!e),children:`Chart data`}),(0,Q.jsxs)(q,{variant:`ghost`,size:`sm`,"aria-label":`Open ${Fm[a]}`,onClick:()=>o(a),children:[Fm[a],(0,Q.jsx)(E,{className:`size-4`,"aria-hidden":`true`})]})]}),(0,Q.jsx)(`div`,{id:f,className:p?`mt-3 border-t border-subtle`:`sr-only`,children:(0,Q.jsxs)(`table`,{"aria-label":e,"aria-describedby":d,className:`w-full text-label-13`,children:[(0,Q.jsx)(`thead`,{className:`text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`py-2 text-left`,children:n}),(0,Q.jsx)(`th`,{scope:`col`,className:`py-2 pl-4 text-right`,children:r})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:i.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,className:`break-words py-2 text-left`,children:e.label}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right tabular-nums`,children:(0,Q.jsx)(Qm,{value:e.value})})]},`${e.label}:${t}`))})]})})]})}function Eh(e){return[{label:`1`,value:e.top1},{label:`2–3`,value:e.top2To3},{label:`4–10`,value:e.top4To10},{label:`11–20`,value:e.top11To20}]}function Dh(e){return`${e.value} · ${e.includeSubdomains?`includes subdomains`:`exact host`}`}function Oh({summary:e}){return(0,Q.jsxs)(`dl`,{"aria-label":`Organic search metrics`,className:`grid gap-x-6 gap-y-3 border-b border-subtle px-1 pb-4 sm:grid-cols-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-13 text-secondary`,children:`Searches you rank for`}),(0,Q.jsx)(`dd`,{className:`mt-1 text-heading-24 tabular-nums text-heading`,children:(0,Q.jsx)(Qm,{value:e.organicKeywords})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-13 text-secondary`,children:`In the top 10`}),(0,Q.jsx)(`dd`,{className:`mt-1 text-heading-24 tabular-nums text-heading`,children:(0,Q.jsx)(Qm,{value:e.inTop10})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`dt`,{className:`flex items-center gap-1.5 text-label-13 text-secondary`,children:[`Estimated organic traffic`,(0,Q.jsx)(X,{text:`Modeled search traffic for this target and provider geography. Site traffic is measured separately.`})]}),(0,Q.jsx)(`dd`,{className:`mt-1 text-heading-24 tabular-nums text-heading`,children:(0,Q.jsx)(Qm,{value:e.estimatedOrganicTraffic})})]})]})}function kh({projectName:e,profileId:t,data:n,active:r,canRun:i,nextRefresh:a,onOpen:o}){let[s,c]=(0,Z.useState)(1),[l,u]=(0,Z.useState)(),d={client:Y,path:{name:e},query:{profileId:t,runId:n.evidenceRunId??void 0}},f=n.evidenceRunId!==null,p=f&&n.marketRankingCount>0,m=f&&n.summary!==null,h=W({...bo(d),enabled:p}),g=W({...Ta({...d,query:{...d.query,limit:20}}),enabled:m}),_=n.summary?.target,v=_&&g.data?.items.find(e=>e.target.kind===_.kind&&e.target.value===_.value&&e.target.includeSubdomains===_.includeSubdomains),y=v?Eh(v):[],b=y.some(e=>e.value!==null),x=f&&!p&&!b&&(!m||g.isSuccess)&&n.rankedKeywordCount>0,S=W({...Ka({...d,query:{...d.query,limit:_h}}),enabled:x}),C=S.data?.items??[],w=C.some(e=>e.rankOrganic!==null),T=f&&!p&&!b&&!w&&(!m||g.isSuccess)&&(!x||S.isSuccess)&&n.keywordMetricsCount>0,D=W({..._i({...d,query:{...d.query,limit:zm,offset:(s-1)*zm}}),enabled:T}),O=p?h:m&&!g.isSuccess?g:x&&!S.isSuccess?S:T?D:null,k;if(O?.error)k=(0,Q.jsx)(fh,{error:O.error,retry:()=>{O.refetch()}});else if(O?.isPending)k=(0,Q.jsx)(`p`,{role:`status`,className:`py-10 text-copy-14 text-secondary`,children:`Loading SEO overview…`});else if(p&&h.data){let{totals:e,depth:t}=h.data;k=(0,Q.jsx)(Th,{title:`Google rank across markets`,caption:`Non-brand queries · ${ng(e)}`,category:`Outcome`,unit:`Queries`,points:Dn(t,e).map(t=>({label:t.label,value:e[t.count]})),view:Cr[`market-rankings`],onOpen:o})}else if(v&&b)k=(0,Q.jsx)(Th,{title:`Organic positions in the top 20`,caption:`${Dh(v.target)} · Google · Location ${v.provenance.locationCode} · ${v.provenance.languageCode}`,category:`Position`,unit:`Ranking searches`,points:y,view:Cr[`domain-intelligence`],onOpen:o});else if(x&&w)k=(0,Q.jsx)(Th,{title:`Organic positions for saved searches`,caption:`First ${C.length} of ${Bm.format(n.rankedKeywordCount)} saved results · Google`,category:`Search and target`,unit:`Organic position`,rankAxis:!0,view:Cr[`ranked-keywords`],onOpen:o,points:C.map(e=>({label:`${e.keyword} · ${Dh(e.target)}`,tick:Ah(e.keyword),value:e.rankOrganic}))});else if(T&&D.data?.items.length){let e=D.data.items,t=(l===void 0?void 0:e[l])??e.find(e=>e.monthlySearches.some(e=>e.searchVolume!==null))??e[0],n=[...t.monthlySearches].sort((e,t)=>e.year-t.year||e.month-t.month).map(e=>{let t=new Date(Date.UTC(e.year,e.month-1,1));return{label:vh.format(t),tick:yh.format(t),value:e.searchVolume}}),r=n.some(e=>e.value!==null),i=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`flex w-fit max-w-full flex-wrap items-center gap-x-3 gap-y-1 text-label-13 text-secondary`,children:[`Search to chart`,(0,Q.jsx)(`select`,{className:`${Wm} min-w-0 sm:max-w-96`,value:e.indexOf(t),onChange:e=>{u(Number(e.target.value)),ze(`other`)},children:e.map((e,t)=>(0,Q.jsx)(`option`,{value:t,children:e.keyword},`${e.keyword}:${t}`))})]}),D.data.total>zm&&(0,Q.jsx)(tu,{page:s,pageSize:zm,visibleRows:e.length,totalRows:D.data.total,disabled:D.isFetching,itemLabel:`searches`,onPageChange:e=>{u(void 0),c(e)}})]}),a=`${t.keyword} · Google · Location ${t.provenance.locationCode} · ${t.provenance.languageCode}`;k=r?(0,Q.jsx)(Th,{title:`Monthly search demand`,caption:a,category:`Month`,unit:`Estimated searches`,points:n,monthAxis:!0,view:Cr[`keyword-metrics`],onOpen:o,controls:i}):t.searchVolume===null?(0,Q.jsxs)(`div`,{className:`material-base p-4 sm:p-5`,children:[(0,Q.jsx)(`h3`,{className:`mb-3 text-heading-20 text-heading`,children:`Search demand`}),i,(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:`The source did not report an estimate for this search.`})]}):(0,Q.jsx)(Th,{title:`Search demand estimate`,caption:a,category:`Search`,unit:`Estimated monthly searches`,points:[{label:t.keyword,tick:Ah(t.keyword),value:t.searchVolume}],view:Cr[`keyword-metrics`],onOpen:o,controls:i})}else{let e=Ym.find(e=>n.evidenceRun?.capabilities.includes(e));k=(0,Q.jsxs)(`div`,{className:`material-base`,children:[(0,Q.jsx)(ph,{title:r?`Refresh in progress`:f?`No rankings or search demand to chart`:`No SEO results yet`,children:r?`Results will appear after the refresh saves data.`:f?`Open the saved evidence for this profile.`:a?`First refresh ${a}.`:i?`Refresh this profile to collect its first results.`:`Results will appear after this profile is refreshed.`}),f&&e&&(0,Q.jsx)(`div`,{className:`pb-4 text-center`,children:(0,Q.jsxs)(q,{variant:`secondary`,"aria-label":`Open ${Jm[e]}`,onClick:()=>o(e),children:[Jm[e],(0,Q.jsx)(E,{className:`size-4`,"aria-hidden":`true`})]})})]})}return(0,Q.jsxs)(`div`,{className:`space-y-4 pt-4`,children:[k,n.summary&&(0,Q.jsx)(Oh,{summary:n.summary})]})}function Ah(e){return e.length>16?`${e.slice(0,15)}…`:e}function jh({projectName:e,profileId:t,runId:n,view:r,active:i,nextRefresh:a}){return r===Cr[`market-rankings`]?n?(0,Q.jsx)(tg,{projectName:e,profileId:t,runId:n,active:i}):(0,Q.jsx)(ph,{title:`No market rankings yet`,children:a?`First refresh ${a}`:`Refresh this profile to rank its tracked queries in each market.`}):(0,Q.jsx)(Mh,{projectName:e,profileId:t,runId:n,view:r,active:i})}function Mh({projectName:e,profileId:t,runId:n,view:r,active:i}){let[a,o]=(0,Z.useState)(1),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(),[d,f]=(0,Z.useState)(),p={client:Y,path:{name:e},query:{profileId:t,runId:n??void 0,limit:zm,offset:(a-1)*zm}},m=W({...Ka(p),enabled:!!n&&r===Cr[`ranked-keywords`]}),h=W({..._i(p),enabled:!!n&&r===Cr[`keyword-metrics`]}),g=W({...Ta(p),enabled:!!n&&r===Cr[`domain-intelligence`]}),_=W({...Ca({...p,query:{...p.query,sort:l}}),placeholderData:te,enabled:!!n&&r===Cr[`competitor-discovery`]}),v=W({...oa({...p,query:{...p.query,kind:s||void 0,sort:d}}),placeholderData:te,enabled:!!n&&r===Cr[`keyword-gaps`]}),y=r===Cr[`ranked-keywords`]?m:r===Cr[`keyword-metrics`]?h:r===Cr[`competitor-discovery`]?_:r===Cr[`keyword-gaps`]?v:g;return n?(0,Q.jsxs)(`div`,{className:`space-y-3 pt-4`,children:[r===Cr[`keyword-gaps`]&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsxs)(`label`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Comparison`}),(0,Q.jsxs)(`select`,{className:`${Wm} w-auto max-w-full`,value:s,onChange:e=>{c(e.target.value),o(1)},children:[(0,Q.jsx)(`option`,{value:``,children:`All comparisons`}),(0,Q.jsx)(`option`,{value:Ot.missing,children:`Missing`}),(0,Q.jsx)(`option`,{value:Ot.shared,children:`Shared`}),(0,Q.jsx)(`option`,{value:Ot.outranked,children:`Competitor ahead`})]})]}),(0,Q.jsx)(X,{placement:`bottom`,text:`Missing: the source lists the search for the competitor but not your domain. Shared includes searches where the competitor ranks higher. These are bounded observations from the source’s organic search database, not a live check of every Google result.`})]}),r===Cr[`competitor-discovery`]&&(0,Q.jsxs)(`p`,{className:`flex items-center gap-1.5 text-label-13 text-secondary`,children:[`Domains sharing organic searches`,(0,Q.jsx)(X,{text:`Discovery uses this profile’s whole domains, location and language. Suggested domains are not automatically added to tracked competitors. Counts describe the source’s database; the table is limited to this refresh’s saved results.`})]}),y.error?(0,Q.jsx)(fh,{error:y.error,retry:()=>{y.refetch()}}):y.data?y.data.items.length===0?(0,Q.jsx)(ph,{title:i?`Refresh in progress`:s?`No matching comparisons`:`No results returned`,children:i?`This profile is collecting data.`:s?`Choose another comparison filter to see the remaining saved results.`:`The source did not return records for this scope. Review the refresh in Refresh history.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`relative overflow-x-auto material-base`,role:`region`,"aria-label":`${Fm[r]} table`,"aria-busy":y.isFetching,tabIndex:0,children:[r===Cr[`ranked-keywords`]&&m.data&&(0,Q.jsx)(Lh,{rows:m.data.items}),r===Cr[`keyword-metrics`]&&h.data&&(0,Q.jsx)(Rh,{rows:h.data.items}),r===Cr[`domain-intelligence`]&&g.data&&(0,Q.jsx)(zh,{rows:g.data.items}),r===Cr[`competitor-discovery`]&&_.data&&(0,Q.jsx)(Fh,{rows:_.data.items,sort:l,onSort:e=>{u(e),o(1)}}),r===Cr[`keyword-gaps`]&&v.data&&(0,Q.jsx)(Ih,{rows:v.data.items,sort:d,onSort:e=>{f(e),o(1)}})]}),(0,Q.jsx)(tu,{page:a,pageSize:zm,visibleRows:y.data.items.length,totalRows:y.data.total,onPageChange:o,disabled:y.isFetching,className:`text-label-13 [&_button]:min-h-11`})]}):(0,Q.jsxs)(`p`,{role:`status`,className:`py-8 text-label-14 text-secondary`,children:[`Loading `,Fm[r].toLowerCase(),`…`]})]}):(0,Q.jsxs)(ph,{title:`No saved data yet`,children:[`Refresh this profile to collect `,Fm[r].toLowerCase(),` for its saved scope.`]})}function Nh({value:e}){return e===null?(0,Q.jsx)(Qm,{value:null}):(0,Q.jsxs)(Q.Fragment,{children:[e>0?`+`:``,Bm.format(e)]})}function Ph({label:e,sort:t,ascending:n,descending:r,align:i=`right`,onSort:a,help:o}){return(0,Q.jsx)(eg,{label:e,align:i,sorted:t===n?`ascending`:t===r?`descending`:null,onSort:()=>a(t===n?r:n),help:o,showUnsorted:!0})}function Fh({rows:e,sort:t,onSort:n}){return(0,Q.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Organic competitors, from the selected refresh`}),(0,Q.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(Ph,{label:`Competitor`,align:`left`,sort:t,ascending:De.domain,descending:De[`-domain`],onSort:n}),(0,Q.jsx)(Ph,{label:`Shared searches`,sort:t,ascending:De.shared,descending:De[`-shared`],onSort:n}),(0,Q.jsx)(Ph,{label:`Avg. position`,sort:t,ascending:De.position,descending:De[`-position`],onSort:n}),(0,Q.jsx)(Ph,{label:`Est. organic traffic`,sort:t,ascending:De.traffic,descending:De[`-traffic`],onSort:n}),(0,Q.jsx)(`th`,{className:`px-4`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:e.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`th`,{scope:`row`,className:Km,children:[(0,Q.jsx)(`p`,{className:`text-primary`,children:e.domain}),(0,Q.jsxs)(`p`,{className:`mt-1 text-label-13 text-secondary`,children:[`Compared with `,e.target.value]})]}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.sharedKeywords})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.averagePosition})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.estimatedOrganicTraffic})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(dh,{label:e.domain,source:e.provenance,children:[(0,Q.jsx)(`p`,{children:`Average position covers shared searches. Traffic covers the competitor’s whole domain.`}),(0,Q.jsxs)(`p`,{children:[`Competitor’s ranked searches: `,(0,Q.jsx)(Qm,{value:e.organicKeywords})]}),(0,Q.jsxs)(`p`,{children:[`Target: `,e.target.value,` · includes subdomains`]})]})})]},`${e.target.value}:${e.domain}:${t}`))})]})}function Ih({rows:e,sort:t,onSort:n}){return(0,Q.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Search gaps, from the selected refresh`}),(0,Q.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(Ph,{label:`Search`,align:`left`,sort:t,ascending:Be.keyword,descending:Be[`-keyword`],onSort:n}),(0,Q.jsx)(Ph,{label:`Comparison`,align:`left`,sort:t,ascending:Be.kind,descending:Be[`-kind`],onSort:n}),(0,Q.jsx)(Ph,{label:`Your rank`,sort:t,ascending:Be[`target-rank`],descending:Be[`-target-rank`],onSort:n}),(0,Q.jsx)(Ph,{label:`Competitor rank`,sort:t,ascending:Be[`competitor-rank`],descending:Be[`-competitor-rank`],onSort:n}),(0,Q.jsx)(Ph,{label:`Rank gap`,sort:t,ascending:Be[`rank-gap`],descending:Be[`-rank-gap`],onSort:n,help:Lm}),(0,Q.jsx)(Ph,{label:`Monthly searches`,sort:t,ascending:Be.volume,descending:Be[`-volume`],onSort:n}),(0,Q.jsx)(`th`,{className:`px-4`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:e.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`th`,{scope:`row`,className:Km,children:[(0,Q.jsx)(`p`,{className:`text-primary`,children:e.keyword}),(0,Q.jsxs)(`p`,{className:`mt-1 text-label-13 text-secondary`,children:[e.target.value,` · `,e.competitor.value]})]}),(0,Q.jsx)(`td`,{className:`px-4 py-3 align-top`,children:(0,Q.jsx)(J,{tone:e.kind===Ot.shared?`neutral`:`caution`,children:Im[e.kind]})}),(0,Q.jsx)(`td`,{className:Gm,children:e.kind===Ot.missing?(0,Q.jsx)(`span`,{className:`text-secondary`,children:`Not found`}):(0,Q.jsx)(Qm,{value:e.targetRankOrganic})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.competitorRankOrganic})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Nh,{value:e.rankGap})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(dh,{label:`${e.keyword} against ${e.competitor.value}`,source:e.provenance,children:[(0,Q.jsxs)(`p`,{children:[`Your ranking page: `,e.targetUrl?(0,Q.jsx)(Cc,{url:e.targetUrl}):`Not supplied`]}),(0,Q.jsxs)(`p`,{children:[`Competitor’s ranking page: `,e.competitorUrl?(0,Q.jsx)(Cc,{url:e.competitorUrl}):`Not supplied`]}),(0,Q.jsxs)(`p`,{children:[`Difficulty /100: `,(0,Q.jsx)(Qm,{value:e.keywordDifficulty})]}),(0,Q.jsxs)(`p`,{children:[`CPC: `,(0,Q.jsx)(Qm,{value:e.cpcUsd,currency:!0})]})]})})]},`${e.target.value}:${e.competitor.value}:${e.keyword}:${t}`))})]})}function Lh({rows:e}){return(0,Q.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Searches you rank for, from the selected refresh`}),(0,Q.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`px-4 py-3 text-left text-label-13-strong`,children:`Search`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:`Position`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:`Monthly searches`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:`Est. traffic`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:`Difficulty /100`}),(0,Q.jsx)(`th`,{className:`px-4`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:e.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`th`,{scope:`row`,className:Km,children:[(0,Q.jsx)(`p`,{className:`text-primary`,children:e.keyword}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:(0,Q.jsx)(Ql,{value:e.url??e.target.value})})]}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.rankOrganic})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.estimatedTraffic})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.keywordDifficulty})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(dh,{label:e.keyword,source:e.provenance,children:[(0,Q.jsx)(`p`,{className:`break-all`,children:e.url??`Ranking URL not supplied`}),(0,Q.jsxs)(`p`,{children:[`Target: `,e.target.value,` · `,e.target.includeSubdomains?`includes subdomains`:`exact host`]}),(0,Q.jsxs)(`p`,{children:[qm,`: `,(0,Q.jsx)(Qm,{value:e.rankAbsolute})]}),(0,Q.jsxs)(`p`,{children:[`CPC: `,(0,Q.jsx)(Qm,{value:e.cpcUsd,currency:!0})]}),(0,Q.jsxs)(`p`,{children:[`Results page features: `,e.serpFeatures.length?e.serpFeatures.map(e=>e.replaceAll(`_`,` `)).join(`, `):`Not supplied`]})]})})]},`${e.target.value}:${e.keyword}:${t}`))})]})}function Rh({rows:e}){return(0,Q.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Search demand from the selected refresh`}),(0,Q.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`px-4 py-3 text-left text-label-13-strong`,children:`Search`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:`Monthly searches`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:`CPC`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:`Difficulty /100`}),(0,Q.jsx)(`th`,{className:`px-4 py-3 text-left text-label-13-strong`,children:`Intent`}),(0,Q.jsx)(`th`,{className:`px-4`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:e.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,className:`${Km} text-primary`,children:e.keyword}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.cpcUsd,currency:!0})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.keywordDifficulty})}),(0,Q.jsx)(`td`,{className:`px-4 py-3 align-top`,children:e.searchIntent??`Not supplied`}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(dh,{label:e.keyword,source:e.provenance,children:[(0,Q.jsxs)(`p`,{children:[`Ad competition: `,e.adCompetition===null?`Not supplied`:Ut(e.adCompetition,Je.fraction)]}),(0,Q.jsxs)(`p`,{children:[`Core search: `,e.coreKeyword??`Not supplied`]}),e.monthlySearches.length>0&&(0,Q.jsx)(`dl`,{children:e.monthlySearches.map(e=>(0,Q.jsxs)(`div`,{className:`flex justify-between gap-5`,children:[(0,Q.jsxs)(`dt`,{children:[e.year,`-`,String(e.month).padStart(2,`0`)]}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Qm,{value:e.searchVolume})})]},`${e.year}-${e.month}`))})]})})]},`${e.keyword}:${t}`))})]})}function zh({rows:e}){return(0,Q.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Domain comparison from the selected refresh`}),(0,Q.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`px-4 py-3 text-left text-label-13-strong`,children:`Domain`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:`Searches ranked for`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:`Est. organic traffic`}),(0,Q.jsx)(`th`,{className:`px-4`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:e.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`th`,{scope:`row`,className:Km,children:[(0,Q.jsx)(`p`,{className:`text-primary`,children:e.target.value}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:e.target.includeSubdomains?`Includes subdomains`:`Exact host`})]}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.organicKeywords})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.estimatedOrganicTraffic})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsx)(dh,{label:e.target.value,source:e.provenance,children:(0,Q.jsxs)(`dl`,{className:`grid grid-cols-2 gap-2`,children:[(0,Q.jsx)(`dt`,{children:`Position 1`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Qm,{value:e.top1})}),(0,Q.jsx)(`dt`,{children:`Positions 2–3`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Qm,{value:e.top2To3})}),(0,Q.jsx)(`dt`,{children:`Positions 4–10`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Qm,{value:e.top4To10})}),(0,Q.jsx)(`dt`,{children:`Positions 11–20`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Qm,{value:e.top11To20})}),(0,Q.jsx)(`dt`,{children:`Est. traffic value`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Qm,{value:e.estimatedOrganicTrafficValueUsd,currency:!0})})]})})})]},`${e.target.value}:${t}`))})]})}var Bh=5,Vh=10,Hh=`all`;function Uh(e){return e===Hh?Hh:pn.safeParse(e).data??null}var Wh={column:`ranks11To20`,descending:!0},Gh={3:`sm:grid-cols-3`,4:`sm:grid-cols-4`,5:`sm:grid-cols-5`},Kh=`inline-flex min-h-11 cursor-pointer select-none items-center rounded-sm hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,qh=`inline-flex min-h-11 items-center rounded-sm text-secondary hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`;function Jh(e,t){switch(e.count){case`page1`:return`Google rank 1 to 10.`;case`ranks11To20`:return`Google rank 11 to 20: the closest to page 1.`;case`ranks21Plus`:return t!==null&&t>21?`Google rank 21 to ${t}.`:`Google rank 21 or deeper.`;case`notRanked`:return t===null?`Searched, and the site is not in the results checked.`:`Searched, and the site is not in the top ${t} results. A search that returned only part of them counts as partly checked instead.`;default:return e.count}}function Yh(e){return`Overlaps the figures beside it: queries where a tracked competitor ranks above the site, or ranks while the site is not in ${e===null?`the results`:`the top ${e}`}.`}function Xh(e){let t=e.filter(e=>e.kind===At.region).length;return t===e.length?{label:`Region`,plural:`regions`}:t===0?{label:`Market`,plural:`markets`}:{label:`Region or market`,plural:`regions and markets`}}function Zh(e,t){return e.counts[t]}function Qh(e){let t=e.descending?-1:1,n=e.column;return n===`label`?(e,n)=>t*(st(e.label,n.label)||st(e.key,n.key)):(e,r)=>t*(Zh(e,n)-Zh(r,n))||st(e.label,r.label)||st(e.key,r.key)}function $h(e,t=250){let[n,r]=(0,Z.useState)(e),i=e.trim()===``;return(0,Z.useEffect)(()=>{if(i){r(``);return}let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[i,e,t]),i?``:n}function eg({label:e,align:t,sorted:n,onSort:r,help:i,showUnsorted:a=!1}){return(0,Q.jsx)(`th`,{scope:`col`,"aria-sort":n??void 0,className:`px-4 text-label-14-strong whitespace-nowrap ${t===`right`?`text-right`:`text-left`}`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:r,className:`${Kh} ${n?`text-primary`:``}`,children:[e,(n||a)&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`ml-0.5`,children:n===`ascending`?`↑`:n===`descending`?`↓`:`↕`})]}),i&&(0,Q.jsx)(X,{text:i})]})})}function tg({projectName:e,profileId:t,runId:n,active:r}){let i=V({strict:!1}),a=B(),o=i.seoRegion,s=i.seoMarket,c=Uh(i.seoShow),l=tr.safeParse(i.seoSort).data??Gn.rank,u=t=>{a({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,...t}),replace:!0})},d=(0,Z.useId)(),f=W(bo({client:Y,path:{name:e},query:{profileId:t,runId:n,regionKey:o,marketKey:s}}));if(f.error)return(0,Q.jsx)(`div`,{className:`py-4`,children:(0,Q.jsx)(fh,{error:f.error,retry:()=>{f.refetch()}})});if(!f.data)return(0,Q.jsx)(`p`,{role:`status`,className:`py-8 text-copy-14 text-secondary`,children:`Loading market rankings…`});let{totals:p,depth:m,groups:h}=f.data,g=`${o??``}\u0000${s??``}`,_=o!==void 0||s!==void 0,v=_&&(0,Q.jsx)(ig,{projectName:e,regionKey:o,marketKey:s,regionLabel:f.data.regionLabel,marketLabel:f.data.marketLabel});if(p.queries===0)return(0,Q.jsxs)(`div`,{className:`pt-4`,children:[v,_?(0,Q.jsxs)(ph,{title:`No rankings here`,children:[`This refresh has no rankings for this `,s===void 0?`region`:`market`,`.`]}):(0,Q.jsx)(ph,{title:r?`Refresh in progress`:`No results returned`,children:r?`This profile is collecting data.`:`The source did not return records for this scope. Review the refresh in Refresh history.`})]});let y=Dn(m,p),b=c??(p.needsWork>0?St[`needs-work`]:Hh),x=h.length>1||h.some(e=>e.kind===At.region);return(0,Q.jsxs)(`div`,{className:`space-y-6 pt-4`,children:[v,(0,Q.jsxs)(`section`,{"aria-labelledby":d,className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-baseline justify-between gap-3`,children:[(0,Q.jsx)(`h3`,{id:d,className:`text-heading-16 text-heading`,children:`Google rank`}),(0,Q.jsx)(`p`,{className:`text-copy-13 tabular-nums text-secondary`,children:ng(p)})]}),(0,Q.jsxs)(`dl`,{className:`grid grid-cols-2 gap-5 border-b border-subtle pb-5 ${Gh[y.length+1]??`sm:grid-cols-5`}`,children:[y.map(e=>(0,Q.jsx)(rg,{label:e.label,help:Jh(e,m),value:p[e.count]},e.count)),(0,Q.jsx)(rg,{label:`Rival ahead`,help:Yh(m),value:p.rivalAhead,className:`sm:border-l sm:border-subtle sm:pl-5`})]})]}),x&&(0,Q.jsx)(ag,{projectName:e,groups:h,bands:y},`groups\u0000${g}`),(0,Q.jsx)(og,{projectName:e,profileId:t,runId:n,regionKey:o,marketKey:s,totals:p,bands:y,depth:m,show:b,onShow:e=>u({seoShow:e}),sort:l,onSort:e=>u({seoSort:e===Gn.rank?void 0:e}),urlQ:i.seoQ??``,onQ:e=>u({seoQ:e||void 0}),onClear:()=>u({seoShow:Hh,seoQ:void 0})},`queries\u0000${g}`)]})}function ng(e){return[`${Bm.format(e.queries)} ${e.queries===1?`query`:`queries`}`,...e.partlyChecked>0?[`${Bm.format(e.partlyChecked)} partly checked`]:[],...e.failed>0?[`${Bm.format(e.failed)} failed`]:[],...e.cancelled>0?[`${Bm.format(e.cancelled)} not searched`]:[]].join(` · `)}function rg({label:e,help:t,value:n,className:r}){return(0,Q.jsxs)(`div`,{className:r,children:[(0,Q.jsxs)(`dt`,{className:`flex items-center gap-1.5 text-label-13 text-secondary`,children:[e,(0,Q.jsx)(X,{text:t,placement:`bottom`})]}),(0,Q.jsx)(`dd`,{className:`mt-2 text-heading-32 tabular-nums text-heading`,children:Bm.format(n)})]})}function ig({projectName:e,regionKey:t,marketKey:n,regionLabel:r,marketLabel:i}){let a=r??`Region not in this refresh`;return(0,Q.jsxs)(`nav`,{"aria-label":`Market rankings scope`,className:`flex flex-wrap items-center gap-x-2 text-label-14`,children:[(0,Q.jsx)(U,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoView:Cr[`market-rankings`],seoRegion:void 0,seoMarket:void 0}),className:qh,children:`All markets`}),t!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted`,children:`/`}),n===void 0?(0,Q.jsx)(`span`,{"aria-current":`page`,className:`text-label-14-strong text-primary`,children:a}):(0,Q.jsx)(U,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoMarket:void 0}),className:qh,children:a})]}),n!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted`,children:`/`}),(0,Q.jsx)(`span`,{"aria-current":`page`,className:`text-label-14-strong text-primary`,children:i??`Market not in this refresh`})]})]})}function ag({projectName:e,groups:t,bands:n}){let r=B(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(1),c=Xh(t),l=(i===null?t:[...t].sort(Qh(i))).slice((o-1)*Bh,o*Bh),u=i??(n.some(e=>e.count===Wh.column)?Wh:null),d=[{column:`queries`,label:`Queries`},...n.map(e=>({column:e.count,label:e.label})),{column:`rivalAhead`,label:`Rival ahead`}],f=e=>{let t=i??Wh;a(t.column===e?{column:e,descending:!t.descending}:{column:e,descending:e!==`label`}),s(1)},p=e=>u?.column===e?u.descending?`descending`:`ascending`:null,h=e=>e.kind===At.region?t=>({...t,seoRegion:e.key,seoMarket:void 0}):t=>({...t,seoMarket:e.key}),g=`Google rank by ${c.label.toLowerCase()}`;return(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`h3`,{className:`text-heading-16 text-heading`,children:[`By `,c.label.toLowerCase()]}),(0,Q.jsx)(`div`,{className:`relative overflow-x-auto rounded-md border border-default`,role:`region`,"aria-label":g,tabIndex:0,children:(0,Q.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:g}),(0,Q.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(eg,{label:c.label,align:`left`,sorted:p(`label`),onSort:()=>f(`label`)}),d.map(e=>(0,Q.jsx)(eg,{label:e.label,align:`right`,sorted:p(e.column),onSort:()=>f(e.column)},e.column)),(0,Q.jsx)(`th`,{className:`px-4`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Open`})})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:l.map(t=>(0,Q.jsxs)(`tr`,{className:`cursor-pointer hover:bg-surface-hover`,onClick:n=>{n.target.closest(`a, button`)||r({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:h(t)})},children:[(0,Q.jsx)(`th`,{scope:`row`,className:`min-w-36 px-4 py-3 text-left align-top text-label-14`,children:(0,Q.jsx)(U,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:h(t),className:`rounded-sm text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:t.label})}),d.map(e=>(0,Q.jsx)(`td`,{className:Gm,children:Bm.format(t.counts[e.column])},e.column)),(0,Q.jsx)(`td`,{className:`px-4 py-3 text-right align-top`,children:(0,Q.jsx)(m,{"aria-hidden":`true`,className:`ml-auto size-4 text-muted`})})]},`${t.kind}:${t.key}`))})]})}),(0,Q.jsx)(tu,{page:o,pageSize:Bh,visibleRows:l.length,totalRows:t.length,onPageChange:s,itemLabel:c.plural,className:`text-label-13 [&_button]:min-h-11`})]})}function og({projectName:e,profileId:t,runId:n,regionKey:r,marketKey:i,totals:a,bands:o,depth:s,show:c,onShow:l,sort:u,onSort:d,urlQ:f,onQ:p,onClear:m}){let h=(0,Z.useId)(),[g,_]=(0,Z.useState)(f),v=$h(g).trim().slice(0,200),y=(0,Z.useRef)(f);(0,Z.useEffect)(()=>{v!==y.current&&(y.current=v,p(v))},[v]);let b=`${c}\u0000${u}\u0000${v}`,[x,S]=(0,Z.useState)({filterKey:b,page:1});x.filterKey!==b&&S({filterKey:b,page:1});let C=x.filterKey===b?x.page:1,w=W({...La({client:Y,path:{name:e},query:{profileId:t,runId:n,regionKey:r,marketKey:i,outcome:c===Hh?void 0:c,q:v||void 0,sort:u,limit:Vh,offset:(C-1)*Vh}}),placeholderData:te}),T=[{value:St[`needs-work`],label:`Needs work`,count:a.needsWork},...o.map(e=>({value:e.filter,label:e.label,count:a[e.count]})),{value:St[`rival-ahead`],label:`Rival ahead`,count:a.rivalAhead},{value:St[`partly-checked`],label:`Partly checked`,count:a.partlyChecked},{value:St.failed,label:`Failed`,count:a.failed},{value:St.cancelled,label:`Not searched`,count:a.cancelled},{value:Hh,label:`All`,count:a.queries}],E=[St[`partly-checked`],St.failed,St.cancelled],D=T.filter(e=>e.value===c||e.count>0||!E.includes(e.value)),O=D.find(e=>e.value===c)?.label??`All`,k=u===Gn.rank?`ascending`:u===Gn[`-rank`]?`descending`:null,A=u===Gn.query?`ascending`:u===Gn[`-query`]?`descending`:null,j=w.data?.items??[],M=s===null?`not ranked`:`not in the top ${s}`,N=!w.data||w.isPlaceholderData?null:w.data.total===0?`No queries match`:`${Bm.format(w.data.total)} ${w.data.total===1?`query`:`queries`}: ${O}`;return(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,id:h,children:`Queries`}),(0,Q.jsx)(X,{placement:`bottom`,text:`Needs work: queries ranking 11 or deeper, ${M}, or partly checked. Rival ahead: a tracked competitor ranks above the site.`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsxs)(`label`,{className:`flex min-w-0 items-center gap-3`,children:[(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:`Ranking filter`}),(0,Q.jsx)(`select`,{value:c,onChange:e=>l(e.target.value),className:`${Wm} min-w-0 sm:w-56`,children:D.map(e=>(0,Q.jsxs)(`option`,{value:e.value,children:[e.label,` (`,Bm.format(e.count),`)`]},e.value))})]}),(0,Q.jsx)(eu,{value:g,onChange:_,label:`Find a query`,placeholder:`Find a query`,className:`min-w-48 flex-1 sm:max-w-xs [&_input]:h-11`})]}),(0,Q.jsx)(`p`,{role:`status`,className:`sr-only`,children:N}),w.error?(0,Q.jsx)(fh,{error:w.error,retry:()=>{w.refetch()}}):w.data?w.data.total===0?(0,Q.jsxs)(`div`,{className:`py-12 text-center`,children:[(0,Q.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:`No queries match`}),(0,Q.jsx)(q,{variant:`secondary`,className:`mt-4 pointer-coarse:min-h-11`,onClick:()=>{y.current=``,_(``),m()},children:`Clear filters`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`relative overflow-x-auto rounded-md border border-default ${w.isPlaceholderData?`opacity-60`:``}`,role:`region`,"aria-label":`Queries`,"aria-busy":w.isPlaceholderData,tabIndex:0,children:(0,Q.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,Q.jsxs)(`caption`,{className:`sr-only`,children:[`Queries: `,O]}),(0,Q.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(eg,{label:`Query`,align:`left`,sorted:A,onSort:()=>d(u===Gn.query?Gn[`-query`]:Gn.query)}),(0,Q.jsx)(eg,{label:`Google rank`,align:`right`,sorted:k,onSort:()=>d(u===Gn.rank?Gn[`-rank`]:Gn.rank)}),(0,Q.jsx)(`th`,{className:`px-4 py-3 text-left text-label-13-strong whitespace-nowrap`,children:`Top rival`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:`Rival rank`}),(0,Q.jsx)(`th`,{className:`${Gm} text-label-13-strong`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[`Rank gap`,(0,Q.jsx)(X,{text:Lm,placement:`bottom`})]})}),(0,Q.jsx)(`th`,{className:`px-4`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:j.map((e,t)=>(0,Q.jsx)(sg,{row:e,requested:s},`${e.marketKey}\u0000${e.queryId??e.queryText}\u0000${t}`))})]})}),(0,Q.jsx)(tu,{page:C,pageSize:Vh,visibleRows:j.length,totalRows:w.data.total,onPageChange:e=>S({filterKey:b,page:e}),disabled:w.isFetching,itemLabel:`queries`,className:`text-label-13 [&_button]:min-h-11`})]}):(0,Q.jsx)(`p`,{className:`py-8 text-copy-14 text-secondary`,children:`Loading queries…`})]})}function sg({row:e,requested:t}){let[n,r]=(0,Z.useState)(!1),i=(0,Z.useId)();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:n?`border-b-0`:void 0,children:[(0,Q.jsxs)(`th`,{scope:`row`,className:Km,children:[(0,Q.jsx)(`p`,{className:`text-primary`,children:e.queryText}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:e.marketLabel})]}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(lg,{row:e,requested:t})}),(0,Q.jsx)(`td`,{className:`px-4 py-3 align-top text-label-13`,children:(0,Q.jsx)(ug,{row:e})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Qm,{value:e.topCompetitor?.rankOrganic??null})}),(0,Q.jsx)(`td`,{className:Gm,children:(0,Q.jsx)(Nh,{value:e.rankGap})}),(0,Q.jsx)(`td`,{className:`px-4 text-right align-top`,children:(0,Q.jsxs)(`button`,{type:`button`,"aria-expanded":n,"aria-controls":i,onClick:()=>r(e=>!e),className:`inline-flex min-h-11 items-center whitespace-nowrap rounded-sm text-button-14 text-secondary hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:[n?`Hide details`:`Details`,(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` for `,e.queryText,` in `,e.marketLabel]})]})})]}),(0,Q.jsx)(`tr`,{id:i,hidden:!n,children:(0,Q.jsx)(`td`,{colSpan:6,className:`bg-surface-subtle px-4 pb-4 pt-3`,children:(0,Q.jsx)(dg,{row:e,requested:t})})})]})}function cg(e){return e.outcome===Pe.failed||e.outcome===Pe.cancelled}function lg({row:e,requested:t}){return e.outcome===Pe.failed?(0,Q.jsx)(X,{tone:`caution`,label:`Failed`,placement:`bottom`,text:`Failed: the source returned no results for this search in this refresh.`}):e.outcome===Pe.cancelled?(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-secondary`,children:[`Not searched`,(0,Q.jsx)(X,{placement:`bottom`,text:`The refresh was cancelled, or reached a spending limit, before this search ran.`})]}):e.rankOrganic===null?e.outcome===Pe[`partly-checked`]?(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-secondary`,children:[`Not in top `,e.depth,(0,Q.jsx)(X,{placement:`bottom`,text:`Only the top ${e.depth}${t===null?``:` of ${t}`} results came back for this search, so ranks past ${e.depth} are unknown.`})]}):(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`Not in top `,e.depth]}):(0,Q.jsx)(Q.Fragment,{children:e.rankOrganic})}function ug({row:e}){if(cg(e))return(0,Q.jsxs)(`span`,{className:`text-muted`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`—`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:`No result`})]});let t=e.topCompetitor;return t?(0,Q.jsxs)(`span`,{className:`inline-flex flex-wrap items-center gap-x-1.5 gap-y-1`,children:[(0,Q.jsx)(`span`,{className:`text-primary`,children:t.domain}),e.rivalAhead&&(0,Q.jsx)(J,{tone:`caution`,children:`Ahead`})]}):(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`None in top `,e.depth]})}function dg({row:e,requested:t}){let n=`text-muted`,r=`mt-0.5 text-primary`,i=e.outcome===Pe.failed?`No result: the search failed`:e.outcome===Pe.cancelled?`No result: not searched`:`Not in the top ${e.depth}`;return(0,Q.jsxs)(`div`,{className:`grid gap-x-8 gap-y-3 text-label-13 text-secondary sm:grid-cols-2 lg:grid-cols-4`,children:[(0,Q.jsxs)(`div`,{className:`sm:col-span-2 lg:col-span-4`,children:[(0,Q.jsx)(`p`,{className:n,children:`Ranking page`}),e.url?(0,Q.jsx)(Cc,{url:e.url}):(0,Q.jsx)(`p`,{className:r,children:i})]}),(0,Q.jsxs)(`div`,{className:`lg:col-span-2`,children:[(0,Q.jsx)(`p`,{className:n,children:`Searched as`}),(0,Q.jsxs)(`p`,{className:r,children:[`“`,e.searchText,`” from `,e.locationLabel]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:n,children:`Target`}),(0,Q.jsxs)(`p`,{className:`${r} break-words`,children:[e.target.value,` · `,e.target.includeSubdomains?`includes subdomains`:`exact host`]})]}),e.rankOrganic!==null&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:n,children:qm}),(0,Q.jsx)(`p`,{className:`${r} tabular-nums`,children:(0,Q.jsx)(Qm,{value:e.rankAbsolute})})]}),e.searchStatus===Ye.partial&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:n,children:`Results checked`}),(0,Q.jsxs)(`p`,{className:`${r} tabular-nums`,children:[`Top `,e.depth,t===null?``:` of ${t}`]})]}),!cg(e)&&(0,Q.jsxs)(`div`,{className:`sm:col-span-2 lg:col-span-2`,children:[(0,Q.jsx)(`p`,{className:n,children:`Tracked competitors in these results`}),e.competitors.length?(0,Q.jsx)(`dl`,{className:`mt-0.5 grid grid-cols-[minmax(0,1fr)_auto] gap-x-6 gap-y-1`,children:e.competitors.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsx)(`dt`,{className:`break-all text-primary`,children:e.domain}),(0,Q.jsxs)(`dd`,{className:`text-right tabular-nums text-primary`,children:[`#`,e.rankOrganic]})]},e.domain))}):(0,Q.jsxs)(`p`,{className:r,children:[`None in the top `,e.depth]})]}),e.provenance&&(0,Q.jsx)(`div`,{className:`sm:col-span-2 lg:col-span-4`,children:(0,Q.jsx)(uh,{source:e.provenance})})]})}function fg({projectName:e,profileId:t,canRun:n,selectedRunId:r,exactRefresh:i,onViewSaved:a,onLatest:o}){let s=z(),[c,l]=(0,Z.useState)(r??null),[u,d]=(0,Z.useState)(null),f={name:e},p=W({...ao({client:Y,path:f,query:{profileId:t}}),enabled:!i,refetchInterval:e=>e.state.data?.runs.some(Xm)?2e3:!1}),m=W({...Oa({client:Y,path:{...f,id:c??``}}),enabled:!!c,refetchInterval:e=>Xm(e.state.data)?2e3:!1}),h=ie({...ga({client:Y}),meta:{skipGlobalErrorToast:!0}}),g=async t=>{if(n&&!h.isPending){d(null);try{await h.mutateAsync({path:{...f,id:t}}),await ui(s,`seo`,{projectName:e})}catch(e){d(ws(e))}}},_=i?m:p;if(_.error)return(0,Q.jsx)(fh,{error:_.error,retry:()=>{_.refetch()}});if(!_.data)return(0,Q.jsx)(`p`,{role:`status`,className:`py-4 text-copy-14 text-secondary`,children:i?`Loading refresh details…`:`Loading refresh history…`});let v=i&&m.data?[m.data]:p.data?.runs??[];if(!v.length)return(0,Q.jsx)(ph,{title:`No refreshes yet`,children:`Refresh this profile to collect its first saved results.`});let y=m.data?.tasks.filter(ah)??[];return(0,Q.jsxs)(Q.Fragment,{children:[u&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:u}),(0,Q.jsx)(`ul`,{className:`divide-y divide-subtle`,"aria-label":`SEO refreshes`,children:v.map(e=>{let t=i||c===e.id;return(0,Q.jsxs)(`li`,{className:`py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(`time`,{dateTime:e.createdAt,className:`text-label-14`,children:un(e.createdAt,Hm)}),(0,Q.jsx)($m,{status:e.status})]}),(0,Q.jsxs)(`p`,{className:`text-copy-13 text-secondary`,children:[e.completedTasks,` of `,e.taskCount,` `,ih(e),` completed`,e.failedTasks>0?` · ${e.failedTasks} failed`:``]})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[!i&&(0,Q.jsxs)(q,{variant:`ghost`,size:`sm`,"aria-expanded":t,"aria-controls":`seo-run-${e.id}`,onClick:()=>l(t?null:e.id),children:[`Details`,(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` for refresh `,e.id]})]}),n&&Xm(e)&&(0,Q.jsx)(q,{variant:`secondary`,size:`sm`,disabled:h.isPending||e.cancelRequested,onClick:ci(()=>g(e.id)),children:e.cancelRequested?`Cancellation requested`:`Cancel refresh`})]})]}),t&&(0,Q.jsxs)(`div`,{id:`seo-run-${e.id}`,className:`mt-3 space-y-2 border-t border-subtle pt-3 text-label-13 text-secondary`,children:[(0,Q.jsxs)(`p`,{className:`break-all`,children:[`Refresh `,e.id]}),(0,Q.jsxs)(`p`,{children:[`Profile revision `,e.profileRevision,` · `,nh(e),` · `,e.languageCode]}),(0,Q.jsxs)(`p`,{children:[`Scope `,e.scope.kind,e.scope.key?` · ${e.scope.key}`:``,e.scope.expectedPlanRevision===void 0?``:` · plan revision ${e.scope.expectedPlanRevision}`]}),e.error&&(0,Q.jsx)(`p`,{children:e.error}),m.error?(0,Q.jsx)(fh,{error:m.error,retry:()=>{m.refetch()}}):m.data?y.length>0&&(0,Q.jsx)(`ul`,{className:`space-y-3`,"aria-label":`Refresh tasks`,children:y.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,Q.jsxs)(`span`,{children:[Fm[e.capability],e.searchText===null?e.target?` · ${e.target.value}`:``:` · “${e.searchText}” from ${e.locationLabel??`its market`}`,e.comparison?` · ${e.comparison.competitor.value} · ${Im[e.comparison.mode]} searches`:``,e.retried?` · retried once`:``]}),(0,Q.jsx)($m,{status:e.status})]}),e.error&&(0,Q.jsx)(`p`,{className:`mt-1`,children:e.error})]},e.id))}):(0,Q.jsx)(`p`,{role:`status`,children:`Loading refresh details…`}),Zm(e)&&(0,Q.jsx)(q,{variant:`secondary`,size:`sm`,onClick:()=>a(e.id),children:`View saved data`})]})]},e.id)})}),i&&(0,Q.jsx)(`div`,{children:(0,Q.jsx)(q,{variant:`ghost`,onClick:o,children:`View latest data`})})]})}function pg({projectName:e,context:t,profile:n,id:r,onClose:i,onSaved:a}){let o=z(),s=Cr[`market-rankings`],c=(e,t)=>mh(e,t).filter(e=>e!==s||n?.rankings),l=t.connections.filter(e=>t.scopes.some(t=>c(e,t).length>0)),u=t.scopes.find(e=>e.kind===Rt.project),[d,f]=(0,Z.useState)(()=>n?.connectionId??(l.find(e=>c(e,u).length>0)??l[0])?.id??``),[p,m]=(0,Z.useState)(n?`${n.scope.kind}:${n.scope.key??``}`:`${Rt.project}:`),h=t.connections.find(e=>e.id===d),g=t.scopes.find(e=>`${e.kind}:${e.key??``}`===p),_=c(h,g),v=e=>{let t=Cr[`ranked-keywords`],n=e.includes(t)?t:e[0];return n?[n]:[]},[y,b]=(0,Z.useState)(n?.name??``),[x,S]=(0,Z.useState)(()=>n?.capabilities??v(_)),[C,w]=(0,Z.useState)(n?.targets??[{kind:Nt.domain,value:``,includeSubdomains:!0}]),[E,D]=(0,Z.useState)(n?.competitors?.map(e=>e.value).join(`
3
- `)??``),[O,k]=(0,Z.useState)(n?.keywords.join(`
4
- `)??``),[A,j]=(0,Z.useState)(n?.locationCode.toString()??``),[M,N]=(0,Z.useState)(n?.languageCode??`en`),[P,F]=(0,Z.useState)(n?.limit.toString()??`100`),[I,ee]=(0,Z.useState)(null),L=ie({...Ui({client:Y}),meta:{skipGlobalErrorToast:!0}}),R=t.connections.filter(e=>e===h||l.includes(e)),te=t.scopes.filter(e=>e===g||e.supported),ne=x.filter(e=>_.includes(e)),B=ne.includes(Cr[`keyword-gaps`]),V=B||ne.includes(Cr[`competitor-discovery`]),H=ne.some(e=>e!==Cr[`keyword-metrics`]),re=ne.includes(Cr[`ranked-keywords`])||V,U=ne.includes(Cr[`keyword-metrics`]),W=ne.includes(s),ae=_.filter(e=>W?e===s:e!==s||ne.length===0),oe=h?.capabilities.includes(s)&&(g?.capabilities?.includes(s)??!0),se=g?.reason??(g&&!g.supported?`SEO reports are unavailable for this scope.`:null),ce=n&&!g?`The saved scope is unavailable. Choose a current scope.`:se,le=(0,Z.useId)(),ue=(0,Z.useId)(),de=(0,Z.useId)(),fe=e=>S(t=>{let r=t.filter(t=>e.includes(t));return n||r.length?r:v(e)}),pe=async()=>{if(!t.access.canWrite||K()||rt()||L.isPending)return;if(!g){ee(`Choose a measurement scope.`);return}let i=O.split(`
5
- `).map(e=>e.trim()).filter(Boolean);if(U&&i.length===0){ee(`Enter at least one search to measure demand.`);return}if(H&&C.length===0){ee(`Add at least one domain or host to measure.`);return}if(V&&C.some(e=>e.kind!==Nt.domain||!e.includeSubdomains)){ee(`Organic competitors and search gaps require whole-domain targets including subdomains.`);return}let s={name:y,connectionId:d,capabilities:ne,targets:H?C:[],keywords:i,locationCode:Number(A),languageCode:M,limit:re?Number(P):n?.limit??100,scope:{kind:g.kind,...g.key?{key:g.key}:{},...g.planRevision===void 0?{}:{expectedPlanRevision:g.planRevision}},...W&&n?.rankings?{rankings:n.rankings}:{},...B?{competitors:E.split(`
6
- `).map(e=>e.trim()).filter(Boolean).map(e=>({kind:Nt.domain,value:e,includeSubdomains:!0}))}:{}},c=In.safeParse(s);if(!c.success)ee(c.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(` `));else{ee(null);try{await L.mutateAsync({path:{name:e,id:r},body:c.data}),await o.fetchQuery(ho({client:Y,path:{name:e}})),a(r)}catch(e){ee(ws(e))}}},me=(e,t)=>w(n=>n.map((n,r)=>r===e?{...n,...t}:n));return(0,Q.jsxs)(`form`,{"aria-label":n?`Edit SEO profile`:`New SEO profile`,className:`material-base space-y-5 p-4 sm:p-5`,onSubmit:e=>{e.preventDefault(),pe()},children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:n?`Edit profile`:`New profile`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,className:`size-9 pointer-coarse:min-h-11 pointer-coarse:min-w-11 p-0`,"aria-label":`Close profile editor`,onClick:i,children:(0,Q.jsx)(T,{className:`size-4`,"aria-hidden":`true`})})]}),(0,Q.jsxs)(`label`,{className:`block max-w-lg space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Profile name`}),(0,Q.jsx)(`input`,{className:Wm,required:!0,maxLength:120,value:y,onChange:e=>b(e.target.value),autoFocus:!0})]}),(0,Q.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0 space-y-1.5`,children:[g&&te.length===1?(0,Q.jsxs)(`dl`,{className:`space-y-1`,children:[(0,Q.jsx)(`dt`,{className:`text-label-13 text-secondary`,children:`Measurement scope`}),(0,Q.jsx)(`dd`,{className:`break-words text-label-14 text-primary`,children:g.label})]}):(0,Q.jsxs)(`label`,{className:`block space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Measurement scope`}),(0,Q.jsxs)(`select`,{className:Wm,required:!0,value:g?p:``,"aria-describedby":ce?le:void 0,onChange:e=>{let n=t.scopes.find(t=>`${t.kind}:${t.key??``}`===e.target.value);m(e.target.value),fe(c(h,n))},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Choose a scope`}),te.map(e=>(0,Q.jsx)(`option`,{value:`${e.kind}:${e.key??``}`,children:e.label},`${e.kind}:${e.key}`))]})]}),ce&&(0,Q.jsx)(`p`,{id:le,className:`text-copy-13 text-secondary`,children:ce})]}),(0,Q.jsxs)(`div`,{className:`min-w-0 space-y-1.5`,children:[h&&R.length===1?(0,Q.jsxs)(`dl`,{className:`space-y-1`,children:[(0,Q.jsx)(`dt`,{className:`text-label-13 text-secondary`,children:`Data source`}),(0,Q.jsx)(`dd`,{className:`break-words text-label-14 text-primary`,children:h.label})]}):(0,Q.jsxs)(`label`,{className:`block space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Data source`}),(0,Q.jsxs)(`select`,{className:Wm,required:!0,value:h?d:``,"aria-describedby":n&&!h?ue:void 0,onChange:e=>{let n=t.connections.find(t=>t.id===e.target.value);f(e.target.value),fe(c(n,g))},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Choose a source`}),R.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),n&&!h&&(0,Q.jsx)(`p`,{id:ue,className:`text-copy-13 text-secondary`,children:`The saved data source is unavailable. Choose a configured source.`})]})]}),(0,Q.jsx)(`div`,{className:`border-t border-subtle pt-4`,children:(0,Q.jsxs)(`fieldset`,{className:`space-y-2`,children:[(0,Q.jsx)(`legend`,{className:`text-heading-14 text-heading`,children:`Reports to collect`}),ae.length?(0,Q.jsx)(`div`,{className:`grid gap-x-6 sm:grid-cols-2`,children:ae.map(e=>(0,Q.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-label-14`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`size-4 shrink-0 accent-accent`,checked:ne.includes(e),onChange:t=>{let n=t.currentTarget.checked;S(t=>n?[...t,e]:t.filter(t=>t!==e))}}),Fm[e]]},e))}):(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:g&&h?`No reports can be set up here with this scope and data source.`:`Choose a scope and data source to see available reports.`}),oe&&!n?.rankings&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Set up market rankings with the CLI or API.`}),W&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Market rankings use their own profile.`})]})}),H&&(0,Q.jsxs)(`fieldset`,{className:`space-y-3`,children:[(0,Q.jsx)(`legend`,{className:`mb-1 text-heading-14 text-heading`,children:`Sites to measure`}),(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:W?`Choose one of this project’s own domains.`:V||ne.includes(Cr[`domain-intelligence`])?`Use a domain with its subdomains for domain reports.`:`Enter a domain or an exact host. Leave out paths and ports.`}),C.map((e,t)=>(0,Q.jsxs)(`div`,{className:`grid items-end gap-3 sm:grid-cols-[1fr_13rem_auto]`,children:[(0,Q.jsxs)(`label`,{className:`space-y-1 text-label-14`,children:[(0,Q.jsxs)(`span`,{className:`sr-only`,children:[`Target `,t+1]}),(0,Q.jsx)(`input`,{className:Wm,value:e.value,placeholder:`example.com`,"aria-label":`Target ${t+1}`,onChange:e=>me(t,{value:e.target.value}),required:!0,maxLength:253})]}),(0,Q.jsxs)(`label`,{className:`space-y-1 text-label-14`,children:[(0,Q.jsxs)(`span`,{className:`sr-only`,children:[`Target `,t+1,` kind`]}),(0,Q.jsxs)(`select`,{className:Wm,"aria-label":`Target ${t+1} kind`,value:e.kind,onChange:e=>me(t,{kind:e.target.value,includeSubdomains:e.target.value===Nt.domain}),children:[(0,Q.jsx)(`option`,{value:Nt.domain,children:`Domain + subdomains`}),(0,Q.jsx)(`option`,{value:Nt.host,children:`Exact host`})]})]}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>w(e=>e.filter((e,n)=>n!==t)),"aria-label":`Remove target ${t+1}`,children:`Remove`})]},t)),(0,Q.jsx)(q,{type:`button`,variant:`secondary`,className:`pointer-coarse:min-h-11`,disabled:C.length>=(W?1:20),onClick:()=>w(e=>[...e,{kind:Nt.domain,value:``,includeSubdomains:!0}]),children:`Add target`})]}),B&&(0,Q.jsxs)(`label`,{className:`block space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Comparison domains`}),(0,Q.jsx)(`textarea`,{className:`${Wm} min-h-24`,value:E,onChange:e=>D(e.target.value),placeholder:`competitor.com`,required:!0}),(0,Q.jsx)(`span`,{className:`block text-copy-13 text-secondary`,children:`One domain per line, up to 5. Includes subdomains. Each is compared with every target in this profile.`})]}),U&&(0,Q.jsxs)(`label`,{className:`block space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Searches`}),(0,Q.jsx)(`textarea`,{className:`${Wm} min-h-28`,value:O,onChange:e=>k(e.target.value),placeholder:`One search per line`,required:!0}),(0,Q.jsx)(`span`,{className:`block text-copy-13 text-secondary`,children:`Enter up to 700 searches, with at most 10 words and 80 characters each.`})]}),(0,Q.jsx)(`div`,{className:`border-t border-subtle pt-4`,children:(0,Q.jsxs)(`fieldset`,{className:`space-y-3`,"aria-describedby":de,children:[(0,Q.jsx)(`legend`,{className:`text-heading-14 text-heading`,children:`Search settings`}),(0,Q.jsx)(`p`,{id:de,className:`text-copy-13 text-secondary`,children:W?`The profile’s location code applies only when the project has no markets or locations.`:`Use the location code from your data source and a language code such as en for English.`}),(0,Q.jsxs)(`div`,{className:`grid gap-4 ${re?`sm:grid-cols-3`:`sm:grid-cols-2`}`,children:[(0,Q.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Provider location code`}),(0,Q.jsx)(`input`,{className:Wm,type:`number`,min:1,step:1,required:!0,value:A,onChange:e=>j(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Language code`}),(0,Q.jsx)(`input`,{className:Wm,required:!0,minLength:2,maxLength:10,value:M,onChange:e=>N(e.target.value)})]}),re&&(0,Q.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:V?`Result limit`:`Ranked searches per target`}),(0,Q.jsx)(`input`,{className:Wm,type:`number`,min:1,max:1e3,step:1,required:!0,value:P,onChange:e=>F(e.target.value)}),V&&(0,Q.jsx)(`span`,{className:`block text-copy-13 text-secondary`,children:B?`Each gap comparison uses this limit separately for shared and missing searches.`:`Maximum rows per target.`})]})]})]})}),I&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-secondary`,children:I}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsx)(q,{type:`submit`,className:`pointer-coarse:min-h-11`,disabled:L.isPending||!g?.supported||!h||!ne.length,children:L.isPending?`Saving…`:`Save profile`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:i,children:`Cancel`})]})]})}var mg=[{value:`7`,label:`7d`},{value:`30`,label:`30d`},{value:`90`,label:`90d`},{value:`180`,label:`180d`}],hg=[{value:`1`,label:`1h`},{value:`24`,label:`24h`},{value:`168`,label:`7d`},{value:`720`,label:`30d`}],gg=20,_g=12,vg=20,yg=50,bg=3,xg=`h-8 rounded-md border border-base bg-bg px-2 text-label-14 text-heading outline-none transition hover:border-strong focus-visible:ring-2 focus-visible:ring-mono-500 disabled:opacity-50`,Sg=`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500`,Cg=`inline-flex w-fit cursor-pointer list-none items-center gap-1 rounded text-label-14 text-secondary hover:text-heading ${Sg} [&::-webkit-details-marker]:hidden`,wg=`inline-flex items-center gap-1.5 rounded text-left ${Sg}`,Tg={ai:`AI referral`,search:`Search`,social:`Social`,paid:`Paid`,referral:`Referral`,direct:`Direct`},Eg={cloudflare:`Cloudflare`,vercel:`Vercel`,"cloud-run":`Cloud Run`,wordpress:`WordPress`},Dg={[_t.matched]:`Matched`,[_t.unmatched]:`No URL match`,[_t.ambiguous]:`Ambiguous URL match`,[_t[`unknown-host`]]:`Host not recorded`,[_t.redacted]:`URL redacted`,[_t[`not-configured`]]:`No Property plan`},Og={[bt.verified]:`text-positive`,[bt.likely_real]:`text-heading`,[bt.unknown]:`text-secondary`},kg=`This project's traffic source logs no IP address, so one person can't be told from another. AI-referred visits are still counted.`,Ag=`Each row is everyone on one browser version, so its visits are not one person's.`,jg=(e,t)=>`${e.toLocaleString()} ${t}${e===1?``:`s`}`,Mg=e=>e.entryName??Tg[e.entryClass],Ng=e=>{if(!e.entryName)return e.paid&&e.entryClass!==`paid`?`Paid`:null;let t=e.paid&&e.entryClass!==`paid`?`${Tg[e.entryClass]}, paid`:Tg[e.entryClass];return t===Mg(e)?null:t},Pg=e=>Nr(e,e),Fg=e=>e&&e.toUpperCase()!==`GET`?e.toUpperCase():null;function Ig(){let e=V({strict:!1}),t=B(),n=re({select:e=>e.location.pathname});return{search:e,update:e=>{t({to:n,search:t=>({...t,...e}),replace:!0})}}}function Lg({projectName:e}){let{account:t}=si(),{search:n,update:r}=Ig();if(K()||t?.role===_r.viewer)return(0,Q.jsx)(`p`,{className:`py-6 text-copy-14 text-secondary`,children:`Journeys are unavailable for view-only accounts and embedded reports.`});let i=n.journeyView===`agents`?`agents`:`visitors`;return(0,Q.jsxs)(`section`,{"aria-labelledby":`journeys-heading`,className:`space-y-6`,children:[(0,Q.jsx)(`h2`,{id:`journeys-heading`,className:`sr-only`,children:`Journeys`}),(0,Q.jsx)(`nav`,{"aria-label":`Journey view`,className:`flex gap-6 border-b border-default`,children:[{value:`visitors`,label:`Visitors`},{value:`agents`,label:`Agent requests`}].map(e=>(0,Q.jsx)(`button`,{type:`button`,"aria-current":i===e.value?`page`:void 0,onClick:()=>{i!==e.value&&(ze(`other`),r({journeyView:e.value===`visitors`?void 0:e.value}))},className:`-mb-px border-b-2 pb-2 text-label-14 transition-colors ${Sg} ${i===e.value?`border-mono-100 text-heading`:`border-transparent text-secondary hover:text-heading`}`,children:e.label},e.value))}),i===`visitors`?(0,Q.jsx)(Ug,{projectName:e},`visitors:${e}`):(0,Q.jsx)(Qg,{projectName:e},`agents:${e}`)]})}function Rg({options:e,value:t,onChange:n,label:r}){let i=(0,Z.useRef)([]),a=r=>{let a=e[(r+e.length)%e.length];i.current[(r+e.length)%e.length]?.focus(),a.value!==t&&n(a.value)},o=Math.max(0,e.findIndex(e=>e.value===t));return(0,Q.jsx)(`div`,{role:`radiogroup`,"aria-label":r,className:`inline-flex overflow-hidden rounded-md border border-base`,onKeyDown:e=>{e.key===`ArrowRight`||e.key===`ArrowDown`?(e.preventDefault(),a(o+1)):(e.key===`ArrowLeft`||e.key===`ArrowUp`)&&(e.preventDefault(),a(o-1))},children:e.map((e,r)=>(0,Q.jsx)(`button`,{ref:e=>{i.current[r]=e},type:`button`,role:`radio`,"aria-checked":e.value===t,tabIndex:e.value===t?0:-1,onClick:()=>{e.value!==t&&n(e.value)},className:`px-3 py-1.5 text-label-14 transition-colors ${Sg} ${e.value===t?`bg-surface-active text-heading`:`text-secondary hover:text-heading`}`,children:e.label},e.value))})}function zg({summary:e,children:t}){let[n,r]=(0,Z.useState)(!1);return(0,Q.jsxs)(`details`,{open:n,onToggle:e=>r(e.currentTarget.open),className:`text-copy-14 text-secondary`,children:[(0,Q.jsxs)(`summary`,{className:Cg,children:[n?(0,Q.jsx)(d,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(m,{className:`size-3.5`,"aria-hidden":`true`}),e]}),(0,Q.jsx)(`div`,{className:`mt-3`,children:t})]})}function Bg({what:e,error:t,retry:n}){return(0,Q.jsxs)(`div`,{role:`alert`,className:`space-y-2 text-copy-14 text-secondary`,children:[(0,Q.jsxs)(`p`,{children:[`Could not load `,e,`. `,ws(t)]}),(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:n,children:`Retry`})]})}function Vg({label:e,help:t,children:n}){return(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`dt`,{className:`flex items-center gap-1 text-label-13 text-secondary`,children:[e,t&&(0,Q.jsx)(X,{placement:`bottom`,text:t})]}),(0,Q.jsx)(`dd`,{className:`mt-1 text-heading-20 tabular-nums text-heading`,children:n})]})}function Hg({projectName:e,partialSources:t}){return t.length===0?null:(0,Q.jsx)(`ul`,{className:`space-y-1`,children:t.map(t=>(0,Q.jsxs)(`li`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-label-14`,children:[(0,Q.jsx)(O,{className:`size-3.5 shrink-0 text-caution`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`text-heading`,children:[`Later visits are not recorded for `,Eg[t.sourceType]??t.sourceType,`.`]}),(0,Q.jsx)(X,{placement:`bottom`,text:t.reason}),(0,Q.jsx)(U,{to:`/traffic/$projectName/$sourceId`,params:{projectName:e,sourceId:t.sourceId},className:`rounded text-link underline-offset-4 hover:underline ${Sg}`,children:`Review source`})]},t.sourceId))})}function Ug({projectName:e}){let{search:t,update:n}=Ig(),r=mg.some(e=>e.value===t.journeyDays)?t.journeyDays:`30`,i=t.journeyEngine??``,a=t.journeyReturned===`true`||t.journeyReturned===`false`?t.journeyReturned:``,o=t.journeyMatching===pr.ua?pr.ua:``,s=Math.max(0,Number.parseInt(t.journeyOffset??`0`,10)||0),[c,l]=(0,Z.useState)(()=>new Date().toISOString()),u={since:new Date(Date.parse(c)-Number(r)*864e5).toISOString(),until:c},d=W({...Ti({client:Y,path:{name:e},query:u}),staleTime:3e4}),f={...u,engine:i||void 0,returned:a||void 0,keyBasis:o||pr[`ip-ua`],limit:gg,offset:s},p=W({...da({client:Y,path:{name:e},query:f}),staleTime:3e4}),m=p.data,h=t.journeyVisitor??null;return(0,Q.jsxs)(`div`,{className:`space-y-6`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-x-10 gap-y-4`,children:[d.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading visitor summary…`}):d.isError?(0,Q.jsx)(Bg,{what:`the visitor summary`,error:d.error,retry:()=>{d.refetch()}}):(0,Q.jsx)(Wg,{summary:d.data}),(0,Q.jsx)(Rg,{label:`First AI visit within`,options:mg,value:r,onChange:e=>{ze(`window`),l(new Date().toISOString()),n({journeyDays:e===`30`?void 0:e,journeyOffset:void 0,journeyVisitor:void 0})}})]}),m&&(0,Q.jsx)(Hg,{projectName:e,partialSources:m.partialSources}),p.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`py-6 text-copy-14 text-secondary`,children:`Loading visitors…`}):p.isError?(0,Q.jsx)(Bg,{what:`visitors`,error:p.error,retry:()=>{p.refetch()}}):m&&m.visitors.length===0&&!i&&!a&&!o&&d.data?.aiVisitors===null?(0,Q.jsxs)(`div`,{className:`border-y border-default py-8 text-copy-14 text-secondary`,children:[(0,Q.jsx)(`p`,{className:`text-label-14-strong text-heading`,children:`Visitors can't be measured here.`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-prose`,children:kg}),(0,Q.jsx)(q,{className:`mt-3`,size:`sm`,variant:`outline`,onClick:()=>{ze(`other`),n({journeyMatching:pr.ua,journeyOffset:void 0,journeyVisitor:void 0})},children:`Show browser groups`})]}):m&&m.visitors.length===0&&!i&&!a&&!o?(0,Q.jsxs)(`div`,{className:`border-y border-default py-8 text-copy-14 text-secondary`,children:[(0,Q.jsx)(`p`,{className:`text-label-14-strong text-heading`,children:`No AI-referred visitors in this period.`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-prose`,children:`Visitors appear after a connected traffic source records an AI referral. Try a longer period.`}),(0,Q.jsx)(U,{to:`/projects/$projectName/traffic`,params:{projectName:e},className:`mt-2 inline-block text-link hover:underline`,children:`Review traffic sources`})]}):m?(0,Q.jsx)(Kg,{projectName:e,data:m,engines:d.data?.byEngine.map(e=>e.engine)??[],engine:i,returned:a,matching:o,openKey:h,onToggle:e=>{e&&Dt(`journeys.visitor_open`),n({journeyVisitor:e??void 0})},onFilter:e=>{ze(`other`),n({...e,journeyOffset:void 0,journeyVisitor:void 0})},onPage:e=>n({journeyOffset:e===0?void 0:String(e),journeyVisitor:void 0})}):null,(0,Q.jsx)(zg,{summary:`About this data`,children:(0,Q.jsxs)(`div`,{className:`max-w-prose space-y-3`,children:[d.data&&(0,Q.jsx)(Xg,{summary:d.data}),m&&(0,Q.jsx)(Zg,{data:m})]})})]})}function Wg({summary:e}){let t=(0,Q.jsx)(Vg,{label:`AI-referred visits`,children:e.aiVisits.toLocaleString()});if(e.aiVisitors===null||e.returningVisitors===null||e.returnedVia===null)return(0,Q.jsxs)(`dl`,{className:`flex flex-wrap items-start gap-x-12 gap-y-4`,children:[t,(0,Q.jsx)(Vg,{label:`Visitors and returns`,help:kg,children:(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Not measurable`})})]});let n=Object.entries(e.returnedVia).filter(([,e])=>e>0).sort((e,t)=>t[1]-e[1]),r=e.returnRate===null?null:Ut(e.returnRate,Je.fraction),i=e.keyBasis.ua>0?`${jg(e.keyBasis.ua,`more visitor`)} matched by browser only ${e.keyBasis.ua===1?`is`:`are`} not counted: one browser version can be many people.`:void 0;return(0,Q.jsxs)(`dl`,{className:`flex flex-wrap items-start gap-x-12 gap-y-4`,children:[t,(0,Q.jsx)(Vg,{label:`AI-referred visitors`,help:i,children:e.aiVisitors.toLocaleString()}),(0,Q.jsxs)(Vg,{label:`Came back`,help:r?`${r} came back in a later visit.`:void 0,children:[e.returningVisitors.toLocaleString(),` `,(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[`of `,e.aiVisitors.toLocaleString()]}),r&&(0,Q.jsxs)(`span`,{className:`sr-only`,children:[`, a `,r,` return rate`]})]}),(0,Q.jsx)(Vg,{label:`Median time to return`,children:e.medianDaysToReturn===null?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Not available`}):Kn(e.medianDaysToReturn)}),(0,Q.jsx)(Vg,{label:`Return visits by channel`,children:n.length===0?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`None yet`}):(0,Q.jsx)(`span`,{className:`flex flex-wrap gap-x-3 gap-y-1 text-label-14 text-heading`,children:n.map(([e,t])=>(0,Q.jsxs)(`span`,{children:[Tg[e],` `,(0,Q.jsx)(`span`,{className:`tabular-nums text-secondary`,children:t.toLocaleString()})]},e))})})]})}function Gg({visitor:e}){let t=e.visits.findIndex(e=>e.entryClass===`ai`),n=t===-1?[]:e.visits.slice(t+1);if(n.length===0)return(0,Q.jsx)(`span`,{className:`text-secondary`,children:e.returned?`Came back`:`No return yet`});let r=[];for(let e of n){let t=`${Mg(e)}${e.paid?` (paid)`:``}`,n=r.at(-1);n?.label===t?n.visits++:r.push({label:t,visits:1})}let i=r.slice(0,bg),a=e.returnChannels.length-i.reduce((e,t)=>e+t.visits,0);return(0,Q.jsxs)(`span`,{className:`text-heading`,children:[i.map(e=>e.visits>1?`${e.label} ×${e.visits}`:e.label).join(`, `),a>0&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[` +`,a.toLocaleString(),` more`]})]})}function Kg({projectName:e,data:t,engines:n,engine:r,returned:i,matching:a,openKey:o,onToggle:s,onFilter:c,onPage:l}){let u=!!(r||i||a),f=a===pr.ua,p=t.totalVisitors===0?0:t.offset+1,h=t.offset+t.visitors.length,g=o!==null&&!t.visitors.some(e=>e.visitorKey===o);return(0,Q.jsxs)(`section`,{"aria-label":`AI-referred visitors`,className:`min-w-0 space-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,Q.jsxs)(`p`,{role:`status`,className:`text-label-13 text-secondary`,children:[p.toLocaleString(),` to `,h.toLocaleString(),` of `,jg(t.totalVisitors,f?`browser group`:`visitor`)]}),(0,Q.jsxs)(`details`,{className:`text-label-14`,open:u||void 0,children:[(0,Q.jsxs)(`summary`,{className:`inline-flex cursor-pointer list-none items-center gap-1.5 rounded-md border border-base px-2.5 py-1 text-secondary hover:text-heading ${Sg} [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(M,{className:`size-3`,"aria-hidden":`true`}),`Filter`,u&&(0,Q.jsx)(`span`,{className:`text-heading`,children:[r,i===`true`?`Came back`:i===`false`?`No return yet`:``,f?`Browser groups`:``].filter(Boolean).join(` · `)})]}),(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-end gap-3`,children:[(0,Q.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`First AI engine`,(0,Q.jsxs)(`select`,{className:xg,value:r,onChange:e=>c({journeyEngine:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:`All engines`}),r&&!n.includes(r)&&(0,Q.jsx)(`option`,{value:r,children:r}),n.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`Came back`,(0,Q.jsxs)(`select`,{className:xg,value:i,onChange:e=>c({journeyReturned:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:`All visitors`}),(0,Q.jsx)(`option`,{value:`true`,children:`Came back`}),(0,Q.jsx)(`option`,{value:`false`,children:`No return yet`})]})]}),(0,Q.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`Matched by`,(0,Q.jsxs)(`select`,{className:xg,value:a,onChange:e=>c({journeyMatching:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:`Network and browser`}),(0,Q.jsx)(`option`,{value:pr.ua,children:`Browser only (groups)`})]})]}),u&&(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>c({journeyEngine:void 0,journeyReturned:void 0,journeyMatching:void 0}),children:`Clear filters`})]})]})]}),f&&(0,Q.jsxs)(`p`,{className:`flex items-center gap-2 text-label-14 text-heading`,children:[(0,Q.jsx)(O,{className:`size-3.5 shrink-0 text-caution`,"aria-hidden":`true`}),Ag]}),o&&g&&(0,Q.jsxs)(`div`,{className:`rounded-md border border-default bg-surface-subtle px-4 py-4 sm:px-8`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-2`,children:[(0,Q.jsx)(`p`,{className:`text-label-13 text-secondary`,children:`This visitor is not on this page of the list.`}),(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>s(null),children:`Close`})]}),(0,Q.jsx)(qg,{projectName:e,visitorKey:o,partialSources:t.partialSources})]}),t.visitors.length===0?(0,Q.jsx)(`p`,{className:`rounded-md border border-default p-5 text-copy-14 text-secondary`,children:`No visitors match these filters.`}):(0,Q.jsx)(`div`,{className:`overflow-x-auto rounded-md border border-default`,children:(0,Q.jsxs)(`table`,{className:`w-full min-w-[42rem]`,"aria-label":`AI-referred visitors`,children:[(0,Q.jsx)(`thead`,{className:`bg-surface-subtle text-left text-label-13 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`py-2 pl-3 pr-2 font-normal`,children:`First AI visit`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-2 font-normal`,children:`Landing page`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-2 font-normal`,children:`Came back through`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-2 text-right font-normal`,children:`Visits`}),(0,Q.jsx)(`th`,{scope:`col`,className:`py-2 pl-2 pr-3 text-right font-normal`,children:`Last seen`})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-default`,children:t.visitors.map(n=>{let r=n.visitorKey===o,i=n.visits.find(e=>e.entryClass===`ai`),a=`journey-visitor-${n.visitorKey}`;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:r?`bg-surface-active`:`hover:bg-surface-hover`,children:[(0,Q.jsx)(`td`,{className:`py-2.5 pl-3 pr-2 align-top`,children:(0,Q.jsxs)(`button`,{type:`button`,"aria-expanded":r,"aria-controls":r?a:void 0,"aria-label":`${n.firstAiEngine} visitor, first AI visit ${Nr(n.firstAiAt)}`,onClick:()=>s(r?null:n.visitorKey),className:`${wg} whitespace-nowrap`,children:[r?(0,Q.jsx)(d,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(m,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:n.firstAiEngine}),(0,Q.jsx)(`time`,{dateTime:n.firstAiAt,className:`text-label-14 text-secondary`,children:Dr(n.firstAiAt)})]})}),(0,Q.jsx)(`td`,{className:`px-2 py-2.5 align-top`,children:i?(0,Q.jsx)(`span`,{className:`block max-w-[18rem] truncate text-label-13-mono text-heading`,title:i.landingPath,children:sl(i.landingPath)}):(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Not kept`})}),(0,Q.jsx)(`td`,{className:`px-2 py-2.5 align-top text-label-14`,children:(0,Q.jsx)(Gg,{visitor:n})}),(0,Q.jsx)(`td`,{className:`px-2 py-2.5 text-right align-top text-label-14 tabular-nums text-heading`,children:n.visitCount.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-2.5 pl-2 pr-3 text-right align-top text-label-14 text-secondary`,children:(0,Q.jsx)(`time`,{dateTime:n.lastSeenAt,children:Dr(n.lastSeenAt)})})]}),r&&(0,Q.jsx)(`tr`,{id:a,children:(0,Q.jsx)(`td`,{colSpan:5,className:`bg-surface-subtle px-4 py-4 sm:px-8`,children:(0,Q.jsx)(qg,{projectName:e,visitorKey:n.visitorKey,partialSources:t.partialSources})})})]},n.visitorKey)})})]})}),(t.totalVisitors>t.limit||t.offset>0)&&(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:t.offset===0,onClick:()=>l(Math.max(0,t.offset-t.limit)),children:`Previous`}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:t.offset+t.limit>=t.totalVisitors,onClick:()=>l(t.offset+t.limit),children:`Next visitors`})]})]})}function qg({projectName:e,visitorKey:t,partialSources:n}){let[r,i]=(0,Z.useState)(0),[a,o]=(0,Z.useState)(Oe.pages),[s,c]=(0,Z.useState)(null),l=W({...Ao({client:Y,path:{name:e,visitorKey:t},query:{limit:_g,offset:r,events:a}}),staleTime:3e4,placeholderData:e=>e});if(l.isPending)return(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading visits…`});if(l.isError)return(0,Q.jsx)(Bg,{what:`this visitor's visits`,error:l.error,retry:()=>{l.refetch()}});let u=l.data,{visitor:d}=u,f=u.offset+u.visits.length>=u.totalVisits,p=u.visits.at(-1),m=f&&p?n.find(e=>e.sourceId===p.sourceId):void 0;return(0,Q.jsxs)(`div`,{className:`space-y-4`,role:`region`,"aria-label":`Visits by this visitor`,children:[(0,Q.jsxs)(`p`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-label-13 text-secondary`,children:[(0,Q.jsx)(`span`,{className:`text-heading`,children:d.device}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsx)(`span`,{children:jg(u.totalVisits,`visit`)}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[d.keyBasis===pr.ua?`Matched by browser only`:`Matched by network and browser`,(0,Q.jsx)(X,{placement:`bottom`,text:d.keyBasis===pr.ua?`May combine people who use the same browser version.`:`May combine people on one network, or split one person whose address changed.`})]})]}),d.cappedDays>0&&(0,Q.jsxs)(`p`,{className:`flex items-center gap-2 text-label-14`,children:[(0,Q.jsx)(O,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`text-heading`,children:[`Some requests are missing on `,jg(d.cappedDays,`day`),`.`]}),(0,Q.jsx)(X,{placement:`bottom`,text:`At most ${300 .toLocaleString()} requests per visitor are kept each day.`})]}),(0,Q.jsx)(Jg,{visits:u.visits,openId:s,events:u.events,loading:l.isFetching,onToggle:e=>{e&&Dt(`journeys.visit_open`),c(e)},onToggleEvents:()=>o(a===Oe.pages?Oe.all:Oe.pages)}),m&&(0,Q.jsxs)(`p`,{className:`text-label-13 text-secondary`,children:[`Later visits are not recorded by `,Eg[m.sourceType]??m.sourceType,`.`]}),(u.totalVisits>u.limit||u.offset>0)&&(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:u.offset===0||l.isFetching,onClick:()=>{i(Math.max(0,u.offset-u.limit)),c(null)},children:`Earlier visits`}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:f||l.isFetching,onClick:()=>{i(u.offset+u.limit),c(null)},children:`Later visits`})]}),(0,Q.jsx)(zg,{summary:`Technical details`,children:(0,Q.jsxs)(`dl`,{className:`max-w-prose space-y-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-13-strong text-heading`,children:`Visitor key`}),(0,Q.jsx)(`dd`,{className:`break-all text-label-13-mono`,children:d.visitorKey})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-13-strong text-heading`,children:`Last recorded request`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`time`,{dateTime:d.lastSeenAt,children:Jr(d.lastSeenAt)})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-13-strong text-heading`,children:`User agent`}),(0,Q.jsx)(`dd`,{className:`break-all text-label-13-mono`,children:d.userAgent??`Not recorded`})]})]})})]})}function Jg({visits:e,openId:t,events:n,loading:r,onToggle:i,onToggleEvents:a}){return(0,Q.jsxs)(`table`,{className:`w-full`,"aria-label":`Visits in time order`,children:[(0,Q.jsx)(`thead`,{className:`text-left text-label-12 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`pb-1.5 pr-4 font-normal`,children:`When`}),(0,Q.jsx)(`th`,{scope:`col`,className:`pb-1.5 pr-4 font-normal`,children:`Came from`}),(0,Q.jsx)(`th`,{scope:`col`,className:`pb-1.5 pr-4 font-normal`,children:`Landing page`}),(0,Q.jsx)(`th`,{scope:`col`,className:`pb-1.5 text-right font-normal`,children:`Pages`})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-default`,children:e.map(e=>{let o=e.id===t,s=Ng(e);return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`whitespace-nowrap py-2 pr-4 align-top`,children:(0,Q.jsxs)(`button`,{type:`button`,"aria-expanded":o,onClick:()=>i(o?null:e.id),className:`${wg} text-label-14 text-heading`,children:[o?(0,Q.jsx)(d,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(m,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}),(0,Q.jsx)(`time`,{dateTime:e.startedAt,children:Nr(e.startedAt)})]})}),(0,Q.jsxs)(`td`,{className:`py-2 pr-4 align-top text-label-14`,children:[(0,Q.jsx)(`span`,{className:e.entryClass===`ai`?`text-label-14-strong text-heading`:`text-heading`,children:Mg(e)}),s&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[` · `,s]})]}),(0,Q.jsx)(`td`,{className:`py-2 pr-4 align-top`,children:(0,Q.jsx)(`span`,{className:`block max-w-[22rem] truncate text-label-13-mono text-heading`,title:e.landingPath,children:sl(e.landingPath)})}),(0,Q.jsx)(`td`,{className:`py-2 text-right align-top text-label-14 tabular-nums text-heading`,children:e.pageCount.toLocaleString()})]}),o&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`pb-3 pl-6`,children:(0,Q.jsx)(Yg,{visit:e,events:n,loading:r,onToggleEvents:a})})})]},e.id)})})]})}function Yg({visit:e,events:t,loading:n,onToggleEvents:r}){return(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[e.events.length===0?(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:t===Oe.pages?`No pages recorded for this visit.`:`No requests recorded for this visit.`}):(0,Q.jsx)(`ol`,{"aria-label":`${Mg(e)} visit requests`,className:`space-y-1`,children:e.events.map((e,t)=>(0,Q.jsxs)(`li`,{className:`flex items-baseline gap-3`,children:[(0,Q.jsx)(`time`,{dateTime:e.ts,className:`w-20 shrink-0 text-label-13 tabular-nums text-secondary`,children:Pg(e.ts)}),(0,Q.jsxs)(`span`,{className:`min-w-0 break-all text-label-13-mono text-heading`,children:[Fg(e.method)&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[Fg(e.method),` `]}),e.path]}),e.status!==null&&e.status>=400&&(0,Q.jsx)(`span`,{className:`text-label-13 tabular-nums text-caution`,children:e.status})]},`${e.ts}:${t}`))}),(0,Q.jsx)(`button`,{type:`button`,disabled:n,onClick:r,className:`rounded text-label-13 text-link hover:underline disabled:opacity-50 ${Sg}`,children:t===Oe.pages?`Show all ${jg(e.requestCount,`request`)}`:`Show fewer requests`})]})}function Xg({summary:e}){return(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`p`,{children:[jg(e.aiVisits,`AI-referred visit`),` started in this period, including visits from earlier visitors.`]}),e.byEngine.length>0&&(0,Q.jsxs)(`table`,{className:`w-full max-w-md text-label-14`,"aria-label":`Visitors by first AI engine`,children:[(0,Q.jsx)(`thead`,{className:`text-left text-label-13`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`py-1.5 font-normal`,children:`First AI engine`}),(0,Q.jsx)(`th`,{scope:`col`,className:`py-1.5 text-right font-normal`,children:`Visitors`}),(0,Q.jsx)(`th`,{scope:`col`,className:`py-1.5 text-right font-normal`,children:`Came back`})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-default`,children:e.byEngine.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`py-1.5 text-heading`,children:e.engine}),(0,Q.jsx)(`td`,{className:`py-1.5 text-right tabular-nums text-heading`,children:e.visitors.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 text-right tabular-nums text-heading`,children:e.returningVisitors.toLocaleString()})]},e.engine))})]}),(0,Q.jsxs)(`p`,{children:[`Matching: `,jg(e.keyBasis.ipUa,`visitor`),` by network and browser, `,jg(e.keyBasis.ua,`visitor`),` by browser only. Visitor figures count only the first: one browser version can be many people.`]})]})}function Zg({data:e}){return(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`p`,{children:[`Visitors are picked by their first AI visit, from `,Nr(e.windowStart),` to `,Nr(e.windowEnd),`. Their later visits show even after that.`]}),(0,Q.jsxs)(`p`,{children:[`A new visit starts after `,30,` minutes without requests. Requests count for `,e.lookbackDays,` days after an AI visit and are kept `,e.retentionDays,` days, up to `,300 .toLocaleString(),` per visitor per UTC day.`]}),(0,Q.jsx)(`p`,{children:`Visitors are inferred from server requests, not identified people, and a request does not prove a booking, sale or sign-up.`}),e.partialSources.map(e=>(0,Q.jsxs)(`p`,{children:[(0,Q.jsxs)(`span`,{className:`text-label-14-strong text-heading`,children:[Eg[e.sourceType]??e.sourceType,`:`]}),` `,e.reason]},e.sourceId))]})}function Qg({projectName:e}){let{search:t,update:n}=Ig(),r=hg.some(e=>e.value===t.agentHours)?t.agentHours:`24`,[i,a]=(0,Z.useState)(()=>new Date().toISOString()),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(null),[u,f]=(0,Z.useState)(``),[p,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(``),[v,y]=(0,Z.useState)(0),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)({properties:[],sources:[]}),w=(0,Z.useRef)(null),T={since:new Date(Date.parse(i)-Number(r)*36e5).toISOString(),until:i,sourceId:o||void 0,agentId:c?.id,trust:u||void 0,targetKey:p||void 0},E=W({...co({client:Y,path:{name:e},query:{...T,limit:vg,offset:v}}),staleTime:3e4}),D=E.data;(0,Z.useEffect)(()=>{D&&C({properties:D.properties,sources:D.coverage.sources})},[D]);let O=D?.properties??S.properties,k=D?.coverage.sources??S.sources,A=O.find(e=>e.key===p),j=k.find(e=>e.sourceId===o),N=()=>{y(0),x(null)},P=!!(o||u||p||c);return(0,Q.jsxs)(`div`,{className:`space-y-6`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-x-10 gap-y-4`,children:[D?(0,Q.jsx)($g,{context:D}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Requests AI assistants made for a person`}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start gap-3`,children:[(0,Q.jsxs)(`details`,{className:`text-label-14`,open:P||void 0,children:[(0,Q.jsxs)(`summary`,{className:`inline-flex cursor-pointer list-none items-center gap-1.5 rounded-md border border-base px-2.5 py-1.5 text-secondary hover:text-heading ${Sg} [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(M,{className:`size-3`,"aria-hidden":`true`}),`Filter`]}),(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-end gap-3`,children:[(0,Q.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`Source`,(0,Q.jsxs)(`select`,{className:xg,value:o,onChange:e=>{ze(`other`),s(e.target.value),N()},children:[(0,Q.jsx)(`option`,{value:``,children:`All sources`}),k.map(e=>(0,Q.jsx)(`option`,{value:e.sourceId,children:e.label},e.sourceId))]})]}),(0,Q.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`Trust`,(0,Q.jsxs)(`select`,{className:xg,value:u,onChange:e=>{ze(`other`),f(e.target.value),N()},children:[(0,Q.jsx)(`option`,{value:``,children:`All trust levels`}),Object.values(bt).filter(e=>e!==bt.likely_fake).map(e=>(0,Q.jsx)(`option`,{value:e,children:il[e]},e))]})]}),O.length>0&&(0,Q.jsxs)(`details`,{ref:w,className:`relative`,children:[(0,Q.jsxs)(`summary`,{className:`${xg} inline-flex cursor-pointer list-none items-center py-1.5 [&::-webkit-details-marker]:hidden`,children:[`Property: `,A?.label??`All properties`]}),(0,Q.jsxs)(`div`,{className:`mt-2 w-72 max-w-full`,children:[(0,Q.jsx)(`input`,{"aria-label":`Find a property`,type:`search`,value:g,onChange:e=>_(e.target.value),placeholder:`Find a property`,className:`${xg} mb-2 w-full`}),(0,Q.jsx)(`div`,{className:`max-h-64 overflow-y-auto`,role:`group`,"aria-label":`Properties`,children:[{key:``,label:`All properties`},...O.filter(e=>e.label.toLowerCase().includes(g.toLowerCase()))].map(e=>(0,Q.jsx)(`button`,{type:`button`,"aria-pressed":p===e.key,className:`block w-full rounded px-2 py-2 text-left text-secondary hover:bg-surface-hover hover:text-heading aria-pressed:bg-surface-active aria-pressed:text-heading ${Sg}`,onClick:()=>{ze(`other`),h(e.key),N(),w.current&&(w.current.open=!1,w.current.querySelector(`summary`)?.focus())},children:e.label},e.key))})]})]}),P&&(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>{ze(`other`),s(``),f(``),h(``),l(null),N()},children:`Clear filters`})]})]}),(0,Q.jsx)(Rg,{label:`Period`,options:hg,value:r,onChange:e=>{ze(`window`),a(new Date().toISOString()),N(),n({agentHours:e===`24`?void 0:e})}})]})]}),P&&(0,Q.jsxs)(`p`,{className:`flex flex-wrap items-center gap-x-4 gap-y-1 text-label-14 text-secondary`,children:[o&&(0,Q.jsxs)(`span`,{children:[`Source: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:j?.label??o})]}),u&&(0,Q.jsxs)(`span`,{children:[`Trust: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:il[u]})]}),p&&(0,Q.jsxs)(`span`,{children:[`Property: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:A?.label??p})]}),c&&(0,Q.jsxs)(`span`,{children:[`Agent: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:c.label})]})]}),E.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`py-6 text-copy-14 text-secondary`,children:`Loading agent requests…`}):E.isError?(0,Q.jsx)(Bg,{what:`agent requests`,error:E.error,retry:()=>{E.refetch()}}):D?(0,Q.jsxs)(Q.Fragment,{children:[D.journeys.length===0?(0,Q.jsxs)(`div`,{className:`border-y border-default py-8 text-copy-14 text-secondary`,children:[(0,Q.jsx)(`p`,{className:`text-label-14-strong text-heading`,children:`No agent requests in this period.`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-prose`,children:`Try a longer period or clear filters.`})]}):(0,Q.jsx)(`div`,{className:`overflow-x-auto rounded-md border border-default`,children:(0,Q.jsxs)(`table`,{className:`w-full min-w-[40rem]`,"aria-label":`Agent visits`,children:[(0,Q.jsx)(`thead`,{className:`bg-surface-subtle text-left text-label-13 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-normal`,children:`Agent`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-normal`,children:`Trust`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-normal`,children:`First page`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-normal`,children:`Started`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-3 py-2 text-right font-normal`,children:`Requests`})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-default`,children:D.journeys.map(t=>{let n=b===t.id;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:n?`bg-surface-active`:`hover:bg-surface-hover`,children:[(0,Q.jsx)(`td`,{className:`px-3 py-2.5 align-top`,children:(0,Q.jsxs)(`button`,{type:`button`,"aria-expanded":n,"aria-controls":n?`agent-sequence-${t.id}`:void 0,"aria-label":`${t.product} visit starting ${Nr(t.startedAt)}`,onClick:()=>{n||Dt(`journeys.agent_open`),x(n?null:t.id)},className:`${wg} text-label-14-strong text-heading`,children:[n?(0,Q.jsx)(d,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(m,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}),t.product]})}),(0,Q.jsx)(`td`,{className:`px-3 py-2.5 align-top text-label-14`,children:t.trustLevels.map(e=>(0,Q.jsx)(`span`,{className:`block ${Og[e]}`,children:il[e]},e))}),(0,Q.jsx)(`td`,{className:`px-3 py-2.5 align-top`,children:(0,Q.jsx)(`span`,{className:`block max-w-[22rem] truncate text-label-13-mono text-heading`,title:`${t.firstHost??``}${t.firstPath}`,children:t.firstPath})}),(0,Q.jsx)(`td`,{className:`whitespace-nowrap px-3 py-2.5 align-top text-label-14 text-secondary`,children:(0,Q.jsx)(`time`,{dateTime:t.startedAt,children:Nr(t.startedAt)})}),(0,Q.jsxs)(`td`,{className:`px-3 py-2.5 text-right align-top text-label-14 tabular-nums text-heading`,children:[t.requestCount.toLocaleString(),t.errorCount>0&&(0,Q.jsx)(`span`,{className:`block text-label-13 text-caution`,children:jg(t.errorCount,`error`)})]})]}),n&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:5,className:`bg-surface-subtle px-4 py-4 sm:px-10`,children:(0,Q.jsx)(e_,{projectName:e,journey:t,selection:{...T,since:D.windowStart,until:D.windowEnd},onSelectAgent:()=>{ze(`other`),l({id:t.agentId,label:t.product}),N()}})})})]},t.id)})})]})}),(D.totalJourneys>D.limit||D.offset>0)&&(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:D.offset===0||E.isFetching,onClick:()=>{y(Math.max(0,D.offset-D.limit)),x(null)},children:`Previous`}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:D.offset+D.limit>=D.totalJourneys||E.isFetching,onClick:()=>{y(D.offset+D.limit),x(null)},children:`Next agent visits`})]}),(0,Q.jsx)(zg,{summary:`About this data`,children:(0,Q.jsx)(n_,{context:D})})]}):null]})}function $g({context:e}){let t=e.coverage.likelyFakeRequests;return(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsxs)(`dl`,{className:`flex flex-wrap items-start gap-x-12 gap-y-4`,children:[(0,Q.jsx)(Vg,{label:`Agent visits`,help:`Requests an AI assistant made for a person, grouped when they come close together.`,children:e.totalJourneys.toLocaleString()}),(0,Q.jsx)(Vg,{label:`Requests`,children:e.observedRequests.toLocaleString()}),t!==null&&t>0&&(0,Q.jsx)(Vg,{label:`Fake, not shown`,help:`Bots posing as an AI assistant, such as scanners looking for secret files.`,children:t.toLocaleString()})]}),!e.coverage.recordingEnabled&&(0,Q.jsxs)(`p`,{className:`flex items-center gap-2 text-label-14 text-heading`,children:[(0,Q.jsx)(O,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),`Recording is off on this instance.`]}),e.coverage.cappedSourceDays.length>0&&(0,Q.jsxs)(`p`,{className:`flex items-center gap-2 text-label-14 text-heading`,children:[(0,Q.jsx)(O,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),`Some requests are missing: a source reached its daily limit.`]})]})}function e_({projectName:e,journey:t,selection:n,onSelectAgent:r}){let[i,a]=(0,Z.useState)(0),o=W({...Ba({client:Y,path:{name:e,journeyId:t.id},query:{...n,limit:yg,offset:i}}),staleTime:3e4});return(0,Q.jsxs)(`div`,{id:`agent-sequence-${t.id}`,role:`region`,"aria-label":`${t.product} requests`,className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[o.data&&o.data.events.length>0?(0,Q.jsx)(t_,{operator:t.operator,events:o.data.events}):(0,Q.jsx)(`span`,{}),(0,Q.jsxs)(q,{size:`sm`,variant:`outline`,onClick:r,children:[`Only `,t.product]})]}),o.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading requests…`}):o.isError?(0,Q.jsx)(Bg,{what:`these requests`,error:o.error,retry:()=>{o.refetch()}}):(0,Q.jsxs)(Q.Fragment,{children:[o.data.events.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No recorded requests on this page.`}):(0,Q.jsxs)(`table`,{className:`w-full max-w-4xl`,"aria-label":`${t.product} recorded requests`,children:[(0,Q.jsx)(`thead`,{className:`text-left text-label-12 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`py-1.5 pr-3 font-normal`,children:`Time`}),(0,Q.jsx)(`th`,{scope:`col`,className:`py-1.5 pr-3 font-normal`,children:`Request`}),o.data.scope.mode===`advanced`&&(0,Q.jsx)(`th`,{scope:`col`,className:`py-1.5 pr-3 font-normal`,children:`Property`}),(0,Q.jsx)(`th`,{scope:`col`,className:`py-1.5 pr-3 text-right font-normal`,children:`Latency`}),(0,Q.jsx)(`th`,{scope:`col`,className:`py-1.5 text-right font-normal`,children:`Status`})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-default`,children:o.data.events.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`whitespace-nowrap py-1.5 pr-3 align-top text-label-13 tabular-nums text-secondary`,children:(0,Q.jsx)(`time`,{dateTime:e.ts,children:new Date(e.ts).toLocaleTimeString(`en-US`,{hour:`numeric`,minute:`2-digit`,second:`2-digit`})})}),(0,Q.jsxs)(`td`,{className:`break-all py-1.5 pr-3 align-top text-label-13-mono text-heading`,children:[Fg(e.method)&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[Fg(e.method),` `]}),(0,Q.jsx)(`span`,{className:`text-secondary`,children:e.host??``}),e.path]}),o.data.scope.mode===`advanced`&&(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 align-top text-label-13 text-heading`,children:e.targetKey?o.data.properties.find(t=>t.key===e.targetKey)?.label??e.targetKey:Dg[e.attribution]}),(0,Q.jsx)(`td`,{className:`whitespace-nowrap py-1.5 pr-3 text-right align-top text-label-13 tabular-nums text-secondary`,children:e.latencyMs===null?`-`:`${e.latencyMs} ms`}),(0,Q.jsx)(`td`,{className:`py-1.5 text-right align-top text-label-13 tabular-nums ${e.status!==null&&e.status>=400?`text-caution`:`text-secondary`}`,children:e.status??`-`})]},e.id))})]}),(o.data.totalEvents>o.data.limit||o.data.offset>0)&&(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:o.data.offset===0||o.isFetching,onClick:()=>a(Math.max(0,o.data.offset-o.data.limit)),children:`Earlier requests`}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:o.data.offset+o.data.limit>=o.data.totalEvents||o.isFetching,onClick:()=>a(o.data.offset+o.data.limit),children:`Later requests`})]})]})]})}function t_({operator:e,events:t}){let n=new Map;for(let e of t){let t=n.get(e.trust)??new Set;for(let n of e.trustReasons)t.add(n);n.set(e.trust,t)}return(0,Q.jsx)(`ul`,{className:`space-y-1 text-label-14`,children:[...n].map(([t,n])=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:Og[t],children:il[t]}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`: `,[...n].map(t=>rl(t,e)).join(` · `)]})]},t))})}function n_({context:e}){return(0,Q.jsxs)(`div`,{className:`max-w-prose space-y-3`,children:[(0,Q.jsxs)(`p`,{children:[Nr(e.windowStart),` to `,Nr(e.windowEnd),`. Agent visits are limited to this period.`]}),(0,Q.jsxs)(`p`,{children:[`Requests are kept `,e.coverage.retentionDays,` days, up to `,e.coverage.dailyEventLimit.toLocaleString(),` per source per day. An agent visit ends after `,e.coverage.idleMinutes,` minutes without requests, and one network address can combine different tasks.`]}),e.scope.planRevision!==null&&(0,Q.jsxs)(`p`,{children:[`Property attribution uses URL matches in plan revision `,e.scope.planRevision,`.`]}),(0,Q.jsx)(`p`,{children:`These requests do not show the person's task, market, tracked query, query class or model.`}),(0,Q.jsx)(`ul`,{className:`list-disc space-y-1 pl-5`,children:e.coverage.limitations.map(e=>(0,Q.jsx)(`li`,{children:e},e))}),e.coverage.cappedSourceDays.map(t=>(0,Q.jsxs)(`p`,{children:[`Daily limit reached: `,e.coverage.sources.find(e=>e.sourceId===t.sourceId)?.label??t.sourceId,`, `,t.day,` (UTC).`]},`${t.sourceId}:${t.day}`)),e.coverage.sources.map(e=>(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-label-14-strong text-heading`,children:e.label}),(0,Q.jsx)(`ul`,{className:`list-disc space-y-1 pl-5`,children:e.limitations.map(e=>(0,Q.jsx)(`li`,{children:e},e))})]},e.sourceId))]})}var r_={"non-brand":`Non-brand`,branded:`Branded`,unknown:`Unclassified`},i_={"no-population":`No answers in this class`,incomplete:`Awaiting answers`,"evidence-incomplete":`Incomplete evidence`,"identity-ambiguous":`Brand identity unavailable`,"not-applicable":`Not measured`,"citation-not-measured":Ar.label};function a_({value:e,queryClass:t}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`engine-comparison-metric`,children:[(0,Q.jsxs)(`span`,{className:`text-label-14-strong text-primary`,children:[e.rate===null?`—`:Ut(e.rate,Je.fraction),(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` · `,r_[t].toLowerCase(),` queries`]})]}),e.rate!==null&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{"aria-hidden":`true`,className:`text-label-13 text-secondary`,children:[e.numerator,`/`,e.denominator]}),(0,Q.jsxs)(`span`,{className:`sr-only`,children:[e.numerator,` of `,e.denominator,` answers`]})]})]}),e.rate===null&&(0,Q.jsx)(`span`,{className:`block text-label-13 text-secondary`,children:i_[e.reason??`not-applicable`]}),e.unattributed!==void 0&&e.unattributed>0?(0,Q.jsxs)(`span`,{className:`block text-label-13 text-secondary`,children:[e.unattributed,` unattributed`]}):null,e.unchecked!==void 0&&e.unchecked>0?(0,Q.jsxs)(`span`,{className:`block text-label-13 text-secondary`,children:[e.unchecked,` unchecked`]}):null]})}function o_({projectName:e,revision:t}){let n=(0,Z.useId)(),[r,i]=(0,Z.useState)(`non-brand`),a=Mo({client:Y,path:{name:e},query:{queryClass:`all`,limit:1}}),o=W({...a,queryKey:[{...a.queryKey[0],tags:[t??`no-sweep`]}],staleTime:fi}),s=o.data,c=[`non-brand`,`branded`,`unknown`].flatMap(e=>{let t=s?.populations.find(t=>t.queryClass===e);return t&&(e===`non-brand`||t.summary.queryCount>0)?[t]:[]}),l=c.find(e=>e.queryClass===r)??c[0],u=l?.breakdown.providers,d=s?.selection.measurement.completedAt,f;return o.isError?f=(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Could not load engine results: `,ws(o.error)]}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{o.refetch()},children:`Retry`})]}):s?s.selection.availability.state!==`available`||u===void 0?f=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Engine breakdown unavailable for this report.`}):s.selection.run.id?u.length===0?f=(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`No `,r_[l.queryClass].toLowerCase(),` queries in this check.`]}):l&&(f=(0,Q.jsxs)(`table`,{className:`engine-comparison`,"aria-label":`By engine, ${r_[l.queryClass].toLowerCase()} queries`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Engine`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Mentioned`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Cited`})]})}),(0,Q.jsx)(`tbody`,{children:u.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,children:(0,Q.jsx)(Qc,{provider:e.provider})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(a_,{value:e.mentionCoverage,queryClass:l.queryClass})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(a_,{value:e.citationCoverage,queryClass:l.queryClass})})]},e.provider))})]})):f=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:we()?Ls:`Engine results appear after your first check.`}):f=(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading engine results…`}),(0,Q.jsxs)(`section`,{className:`overview-brief max-w-2xl`,"aria-labelledby":n,children:[(0,Q.jsxs)(`div`,{className:`av-card-head`,children:[(0,Q.jsxs)(`div`,{className:`inline-flex flex-wrap items-center`,children:[(0,Q.jsx)(`h2`,{id:n,className:`av-card-title`,children:`By engine`}),(0,Q.jsx)(X,{text:`Mentioned: the answer names you. Cited: its sources link to your site. Each rate uses this check’s answers in the selected query class. Missing answers are never counted as negative results. Not measured: the engine returns no sources, so its citations cannot be checked.`}),l&&(0,Q.jsxs)(`span`,{className:`ml-3 text-label-13 text-secondary`,children:[r_[l.queryClass],` queries`]})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[d?(0,Q.jsxs)(`p`,{className:`av-card-meta`,children:[`Latest check `,Nr(d),s?.selection.measurement.state===`partial`?` · incomplete`:``]}):null,c.length>1?(0,Q.jsx)(Bc,{label:`Query type`,className:`flex-wrap`,options:c.map(e=>({value:e.queryClass,label:r_[e.queryClass]})),value:l.queryClass,onChange:i}):null]})]}),(0,Q.jsx)(`div`,{className:`av-card-body`,children:f})]})}var s_={[hr.queued]:{word:`queued`,tone:`text-secondary`},[hr.running]:{word:`running`,tone:`text-info-300`},[hr.completed]:{word:`completed`,tone:`text-secondary`},[hr.partial]:{word:`partial`,tone:`text-caution-400`},[hr.failed]:{word:`failed`,tone:`text-negative-400`},[hr.cancelled]:{word:`cancelled`,tone:`text-secondary`}};function c_({runs:e,projectName:t,collapsed:n=!1}){let r=(0,Z.useId)(),i=(0,Z.useId)(),a=new Set(e.map(e=>e.location??``)).size>1,o=e.some(e=>e.kind!==Qt[`answer-visibility`]),s=e.map(e=>`${e.startedAt}: ${e.summary}.${e.statusDetail?` ${e.statusDetail}`:``}`);return(0,Q.jsx)(`section`,{className:`overview-brief`,"aria-labelledby":r,children:(0,Q.jsxs)(`details`,{className:`av-history`,open:!n||void 0,children:[(0,Q.jsxs)(`summary`,{className:`av-card-head`,"aria-labelledby":r,"aria-describedby":e.length>0?i:void 0,children:[(0,Q.jsx)(`h2`,{id:r,className:`av-card-title`,children:`Past checks`}),(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[e.length>0?(0,Q.jsxs)(`span`,{id:i,className:`av-card-meta`,children:[e.length,` recent`]}):null,(0,Q.jsx)(d,{className:`overview-disclosure-icon`,size:16,"aria-hidden":`true`})]})]}),(0,Q.jsx)(`div`,{className:`av-card-body`,children:e.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No checks yet.`}):(0,Q.jsxs)(`table`,{className:`av-grid av-grid-dense av-grid-sweeps`,"aria-labelledby":r,children:[(0,Q.jsx)(`thead`,{className:`sr-only`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Started`}),o?(0,Q.jsx)(`th`,{scope:`col`,children:`Type`}):null,(0,Q.jsx)(`th`,{scope:`col`,children:`Trigger`}),a?(0,Q.jsx)(`th`,{scope:`col`,children:`Location`}):null,(0,Q.jsx)(`th`,{scope:`col`,children:`Duration`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Status`})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let n=s_[e.status],r=e.status===hr.partial||e.status===hr.failed;return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,className:`av-row-label tabular-nums`,children:(0,Q.jsx)(Ds,{run:e,projectName:t,className:`av-link`,label:e.opensSeoWorkspace?`View SEO refresh from ${e.startedAt}`:`View the ${e.startedAt} check`,children:e.startedAt})}),o?(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.kindLabel}):null,(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.triggerLabel}),a?(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.location??`No location`}):null,(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.duration}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`span`,{className:`av-status ${n.tone}`,children:n.word}),r&&e.statusDetail?(0,Q.jsx)(`span`,{className:`ml-2 text-label-13 text-secondary`,children:e.statusDetail}):null]})]},e.id)})})]})}),(0,Q.jsx)(El,{items:s})]})})}var l_=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],u_=`Measured answers`,d_=`Close answers`,f_={"non-brand":`Non-brand queries`,branded:`Branded queries`,unknown:`Unclassified queries`},p_={"non-brand":`non-brand queries`,branded:`branded queries`,unknown:`unclassified queries`},m_={up:e=>`Up ${e} pts`,down:e=>`Down ${e} pts`,none:`No change`,previousUnavailable:`No earlier value`,comparedWith:e=>`vs ${e} check`,noPreviousRun:`No earlier check to compare`,definitionChanged:e=>e===null?`Not compared: setup changed`:`Not compared: setup changed since ${e}`,modelChanged:e=>e===null?`Not compared: engines or models changed`:`Not compared: engines or models changed since ${e}`,legacyUnknown:`Not compared: older check lacks comparison details`,partialRun:`Not compared: a check was incomplete`,scopedRun:`Not compared: this check covered part of the project`,explanation:`Change compares this check with the check before it when both completed and used the same setup, engines and models.`},h_={simpleMention:`Mentioned counts answers naming your brand in the answer text, not in the source links.`,simpleCitation:`Cited counts answers linking to your site in the sources behind the answer, not in the answer text.`,advancedMention:`An answer counts when it mentions any assigned property. This does not mean every property was mentioned. An answer that could not be tied to one property is left out of the rate, never counted as not mentioned.`,advancedCitation:`An answer counts when it cites a matching URL for any assigned property. This does not mean every property was cited. An answer whose sources could not be checked is left out of the rate, as neither cited nor not cited, and counted on its own line. So is an answer from an engine that returns no sources.`,propertyReach:`Selected properties named in at least one measured answer, out of the selected properties that have a name to match on. It counts properties, not answers, and shows no rate while any of those properties is unmeasured.`},g_=`Counts properties, not answers. The buckets do not overlap and add up to the total. Cited only means the engine used the property's page as a source without naming it in the answer. Not measured covers a property with no eligible completed measurement, and one where only one of the two signals was measured, including one whose answers all came from engines that return no sources: calling that mentioned but not cited would assert an absence nothing measured. Neither signal means both were measured and neither was found. One verified mention or citation stands, and a later uncertain answer cannot erase it.`,__=`min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`;function v_(e){return e.kind===`project`?`Whole site`:e.kind===`group`?`${e.label} · Group`:e.kind===`market`?`${e.label} · Market`:e.label}function y_(e){return e.reason===`identity-ambiguous`?Tr.ambiguous:e.reason===`not-applicable`?`Not applicable`:`Not measured`}function b_({value:e,signal:t}){if(e.rate===null&&e.reason===`citation-not-measured`)return(0,Q.jsxs)(`span`,{className:`inline-flex items-center text-label-14 text-secondary`,children:[y_(e),(0,Q.jsx)(X,{text:Fr})]});if(e.rate===null)return(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:y_(e)});let n=Ir(e,t);return(0,Q.jsxs)(`span`,{className:`inline-flex flex-col gap-1`,children:[(0,Q.jsx)(`strong`,{className:`tabular-nums text-heading`,children:Ut(e.rate)}),(0,Q.jsxs)(`span`,{className:`text-label-14 tabular-nums text-secondary`,children:[e.numerator,` of `,e.denominator]}),n?(0,Q.jsx)(`span`,{className:`-ml-2 flex`,children:(0,Q.jsx)(X,{tone:`caution`,placement:`bottom`,label:n.label,text:n.text})}):null]})}function x_({value:e}){return e.rate===null?null:(0,Q.jsx)(`span`,{className:`report-rate-bar`,"aria-hidden":`true`,children:(0,Q.jsx)(`span`,{className:`report-rate-bar-fill progress-fill-neutral`,style:{width:`${e.rate*100}%`}})})}function S_(e,t){if(!e||e.state===`unavailable`)return null;let n=e[t];if(n.state===`unavailable`)switch(n.reason){case Ae[`previous-unavailable`]:return{text:m_.previousUnavailable,tone:`text-secondary`};case Ae[`current-unavailable`]:case Ae[`not-applicable`]:return null}let{direction:r,magnitude:i}=lt(n.delta);switch(r){case`up`:return{text:m_.up(i),tone:`text-positive`};case`down`:return{text:m_.down(i),tone:`text-negative`};case`none`:return{text:m_.none,tone:`text-secondary`}}}function C_(e,t){let n=Gr(e);return t!==null&&Wr(n)===Wr(Gr(t))?$r(n):Ur(n)}function w_(e,t){return(e.run.id===null?void 0:t.trend.find(t=>t.runId===e.run.id))?.createdAt??e.measurement.completedAt??t.trend.at(-1)?.createdAt??null}function T_(e,t){if(!e)return null;if(e.state===`unavailable`){let n=e.previousRun?C_(e.previousRun.createdAt,t):null;switch(e.reason){case yt[`no-selected-run`]:return null;case yt[`no-previous-run`]:return m_.noPreviousRun;case yt[`definition-changed`]:return m_.definitionChanged(n);case yt[`model-changed`]:return m_.modelChanged(n);case yt[`legacy-unknown`]:return m_.legacyUnknown;case yt[`partial-run`]:return m_.partialRun;case yt[`scoped-run`]:return m_.scopedRun}}return m_.comparedWith(C_(e.previousRun.createdAt,t))}function E_(e,t){let n=`${e.queryCount} measured ${e.queryCount===1?`query`:`queries`} · ${e.answerCount} ${e.answerCount===1?`answer`:`answers`}`;return t===null?n:`${n} · ${t}`}function D_({label:e,help:t,value:n,signal:r,unit:i,classNoun:a,change:o}){let s=(0,Q.jsx)(`span`,{className:`sr-only`,children:` · ${a}`}),c=Ir(n,r);return(0,Q.jsxs)(`div`,{className:`report-headline-tile`,children:[(0,Q.jsxs)(`dt`,{className:`flex items-center gap-1 text-label-14 text-secondary`,children:[(0,Q.jsx)(`span`,{children:e}),(0,Q.jsx)(X,{text:t})]}),n.rate===null?(0,Q.jsxs)(`dd`,{className:`text-label-18 text-secondary`,children:[y_(n),s]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`dd`,{className:`report-headline-value`,children:[(0,Q.jsx)(`span`,{className:`text-heading-32 tabular-nums text-heading`,children:Ut(n.rate)}),s,o?(0,Q.jsx)(`span`,{className:`text-label-14 ${o.tone}`,children:o.text}):null]}),(0,Q.jsx)(`dd`,{className:`text-label-14 tabular-nums text-secondary`,children:`${n.numerator} of ${n.denominator} ${i}`}),c?(0,Q.jsx)(`dd`,{className:`-ml-2 flex`,children:(0,Q.jsx)(X,{tone:`caution`,placement:`bottom`,label:c.label,text:c.text})}):null]})]})}var O_={otherQueries:`Other queries`},k_={retiredScope:`This saved scope is unavailable for this measurement. Show the whole site to choose another.`,retiredMarket:`This saved market is unavailable for this measurement. Show all markets to choose another.`,showWholeSite:`Show whole site`,showAllMarkets:`Show all markets`};function A_(e,t){let n=new Map;for(let t of e){let e=n.get(t.queryKey);e?e.rows.push(t):n.set(t.queryKey,{queryKey:t.queryKey,query:t.query,rows:[t]})}let r=[...n.values()];if(!t||!e.some(e=>e.marketKeys?.length))return r;for(let e of r)e.marketLabel=[...new Set(e.rows.flatMap(e=>e.marketKeys??[]))].sort().map(e=>t.get(e)??e).join(` · `)||O_.otherQueries;return r.sort((e,t)=>e.marketLabel.localeCompare(t.marketLabel)||e.query.localeCompare(t.query))}var j_={help:`Only part of the source list for this answer was saved, so its sources could not all be checked. It is left out of Cited, counted neither as cited nor as not cited. The links that were saved still show what it cited. A property that no fully checked answer cites shows as Not measured.`,partlySaved:e=>e===1?`Sources partly saved`:`${e} answers with sources partly saved`,savedCite:(e,t,n)=>t===1?`Saved links cite ${n}`:`Saved links in ${e} of ${t} answers cite ${n}`,savedCiteNone:e=>e===null?`No saved link cites an assigned property`:`No saved link cites ${e}`,outcomes:e=>`${e} not measured only because an answer's sources were partly saved. Query results shows which answer.`,outcomesNoSources:e=>`${e} not measured for citation because ${e===1?`its`:`their`} answers came only from engines that return no sources.`};function M_({row:e,targetLabels:t,showCount:n}){let r=e.uncheckedSources;if(!r)return null;let i=e=>t.get(e)??e,a=r.citedAnswers>0?j_.savedCite(r.citedAnswers,r.answers,r.citedTargetKeys.map(i).join(`, `)):j_.savedCiteNone(e.targetKeys.length===1?i(e.targetKeys[0]):null);return(0,Q.jsxs)(Q.Fragment,{children:[n?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:j_.partlySaved(r.answers)}):null,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:a})]})}function N_({value:e,signal:t,singleAnswer:n,row:a,targetLabels:o}){if(n&&e.denominator===1&&e.unattributed===void 0&&e.unchecked===void 0&&(e.rate===0||e.rate===1)){let t=e.rate===1;return(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-2 text-label-14 ${t?`text-positive`:`text-secondary`}`,children:[t?(0,Q.jsx)(r,{size:16,"aria-hidden":`true`}):(0,Q.jsx)(i,{size:16,"aria-hidden":`true`}),t?`Yes`:`No`]})}let s=t===`cited`&&a?.uncheckedSources?a:void 0;return(0,Q.jsxs)(`span`,{className:`inline-flex items-start gap-1`,children:[(0,Q.jsxs)(`span`,{className:`inline-flex flex-col gap-1`,children:[(0,Q.jsx)(b_,{value:e,signal:t}),s?(0,Q.jsx)(M_,{row:s,targetLabels:o??new Map,showCount:e.rate===null}):null]}),s?(0,Q.jsx)(X,{text:j_.help}):e.reason===`evidence-incomplete`?(0,Q.jsx)(X,{text:`The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation.`}):null]})}function P_({targetKeys:e,labels:t}){return e.length===0?(0,Q.jsx)(`span`,{children:`No assigned properties`}):e.length===1?(0,Q.jsx)(`span`,{children:t.get(e[0])??e[0]}):(0,Q.jsxs)(`details`,{children:[(0,Q.jsxs)(`summary`,{className:`min-h-11 cursor-pointer py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:[e.length,` properties`]}),(0,Q.jsx)(`ul`,{className:`max-h-48 space-y-2 overflow-y-auto pb-3`,children:e.map(e=>(0,Q.jsx)(`li`,{children:t.get(e)??e},e))})]})}function F_({group:e,queryClass:t,advanced:n,targetLabels:r,marketHeading:i,onViewAnswers:a}){let o=e.rows[0],s=e=>JSON.stringify([...e.targetKeys].sort()),c=e.rows.every(e=>s(e)===s(o)),l=e.rows.every(e=>e.location===o.location),u=e=>e===null?`No location requested`:`Requested search location: ${e}`;return(0,Q.jsxs)(`tbody`,{"data-query-key":e.queryKey,children:[i?(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`th`,{colSpan:4,className:`border-t border-default py-4 text-left`,children:(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:i})})}):null,(0,Q.jsx)(`tr`,{className:`measurement-result-heading`,children:(0,Q.jsxs)(`th`,{scope:`rowgroup`,colSpan:4,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Q.jsx)(`h3`,{className:`break-words text-heading-16 text-heading`,children:e.query}),(0,Q.jsx)(`div`,{className:`text-label-14`,children:(0,Q.jsx)(zs,{showLabel:!0,queryId:o.queryId,sourceSnapshotIds:e.rows.flatMap(e=>e.sourceSnapshotIds??[]),queryClass:t===`unknown`?null:t,location:l?o.location:void 0})})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-5 text-label-14 text-secondary`,children:[n&&c?(0,Q.jsx)(P_,{targetKeys:o.targetKeys,labels:r}):null,l?(0,Q.jsx)(`span`,{children:u(o.location)}):null]})]})}),e.rows.map(e=>(0,Q.jsxs)(`tr`,{className:`measurement-engine-result`,children:[(0,Q.jsxs)(`td`,{className:`measurement-result-engine`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:Vo(e.provider)}),(!e.model||e.model!==an(e.provider))&&(0,Q.jsx)(`span`,{className:`block break-words text-label-14 text-secondary`,title:e.model??void 0,children:e.model?an(e.provider)?Me(e.model):e.model:`Model not recorded`}),n&&!c?(0,Q.jsx)(`div`,{className:`mt-1 text-label-14 text-secondary`,children:(0,Q.jsx)(P_,{targetKeys:e.targetKeys,labels:r})}):null,l?null:(0,Q.jsx)(`span`,{className:`mt-1 block text-label-14 text-secondary`,children:u(e.location)}),(0,Q.jsx)(Us,{showLabel:!0,showSubjects:n,queryId:e.queryId,sourceSnapshotIds:e.sourceSnapshotIds??[],queryClass:t===`unknown`?null:t,provider:e.provider,model:e.model,location:e.location})]}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`span`,{className:`measurement-result-mobile-label`,"aria-hidden":`true`,children:`Mentioned`}),(0,Q.jsx)(N_,{value:e.mentionCoverage,signal:`mentioned`,singleAnswer:e.answerCount===1})]}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`span`,{className:`measurement-result-mobile-label`,"aria-hidden":`true`,children:`Cited`}),(0,Q.jsx)(N_,{value:e.citationCoverage,signal:`cited`,singleAnswer:e.answerCount===1,row:e,targetLabels:r})]}),(0,Q.jsx)(`td`,{className:`measurement-result-action`,children:(0,Q.jsxs)(q,{variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-label":`View answers for ${e.query} · ${Vo(e.provider)}`,onClick:t=>a(e,t.currentTarget),children:[e.answerCount===1?`View answer`:`View answers`,(0,Q.jsx)(m,{size:16,"aria-hidden":`true`})]})})]},JSON.stringify([e.provider,e.model,e.location])))]})}var I_=`Cited counts only answers whose sources could be checked.`,L_=[{key:`mentioned`,label:`Mentioned`,color:zr[1],dashed:!1},{key:`cited`,label:`Cited`,color:Qr.positive,dashed:!0}],R_=`var(--chart-tooltip-bg)`;function z_({population:e}){let t=(0,Z.useId)(),[n,r]=(0,Z.useState)({mentioned:!0,cited:!0}),i=L_.filter(e=>n[e.key]).map(e=>e.key),a=e=>r(t=>{let n={...t,[e]:!t[e]};return n.mentioned||n.cited?n:t}),o=0,s=e.trend.map((e,t)=>(t>0&&e.continuity.state!==`comparable`&&(o+=1),{createdAt:Date.parse(e.createdAt),[`mentioned-${o}`]:e.mentionCoverage.rate,[`cited-${o}`]:e.citationCoverage.rate})),c=Array.from({length:o+1},(e,t)=>t),l=new Set(e.trend.slice(1).map(e=>e.continuity.state)),u=[...s.length===1?[`This view has one measurement point. A trend needs at least two comparable points.`]:[],...l.has(`definition-changed`)?[`Gaps mark changes to what was measured.`]:[],...l.has(`model-changed`)?[`Gaps mark changes to answer engines or models.`]:[],...l.has(`legacy-unknown`)?[`Older runs lack the details needed for comparison.`]:[],...e.trend.some(e=>e.citationCoverage.reason===`evidence-incomplete`)?[`Missing citation results mean the saved evidence is incomplete.`]:[],...e.trend.some(e=>e.citationCoverage.unchecked!==void 0)?[I_]:[],...e.trend.some(e=>e.citationCoverage.citationNotMeasured!==void 0||e.citationCoverage.reason===`citation-not-measured`)?[`Cited leaves out answers from engines that return no sources.`]:[]];if(s.length===0)return e.summary.mentionCoverage.rate!==null||e.summary.citationCoverage.rate!==null?null:(0,Q.jsx)(`p`,{className:`py-6 text-copy-14 text-secondary`,children:`No measured trend for this selection.`});let d=e.trend.some(e=>e.mentionCoverage.rate!==null||e.citationCoverage.rate!==null),f=d&&s.length>1,p=f?`div`:`details`;return(0,Q.jsxs)(Q.Fragment,{children:[f?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`fieldset`,{className:`flex flex-wrap items-center gap-x-5 py-1 text-label-14 text-secondary`,children:[(0,Q.jsx)(`legend`,{className:`sr-only`,children:`Trend legend`}),L_.map(e=>(0,Q.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,checked:n[e.key],disabled:n[e.key]&&i.length===1,onChange:()=>a(e.key)}),(0,Q.jsxs)(`svg`,{"aria-hidden":`true`,className:`shrink-0`,width:`24`,height:`10`,viewBox:`0 0 24 10`,children:[(0,Q.jsx)(`line`,{x1:`0`,y1:`5`,x2:`24`,y2:`5`,stroke:e.color,strokeWidth:`2`,strokeDasharray:e.dashed?`6 4`:void 0}),(0,Q.jsx)(`circle`,{cx:`12`,cy:`5`,r:`3`,fill:e.dashed?R_:e.color,stroke:e.color,strokeWidth:`2`})]}),e.label]},e.key)),u.length>0&&(0,Q.jsx)(X,{text:u.join(` `)})]}),u.length>0&&(0,Q.jsx)(`span`,{id:t,className:`sr-only`,children:u.join(` `)}),(0,Q.jsx)(`div`,{className:`visibility-trend-chart`,role:`img`,"data-visible-series":i.join(` `),"aria-describedby":u.length>0?t:void 0,"aria-label":`${f_[e.queryClass]} mention and citation trend`,children:(0,Q.jsx)(le,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(ve,{data:s,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(oe,{stroke:ei,vertical:!1}),(0,Q.jsx)(ue,{dataKey:`createdAt`,type:`number`,scale:`time`,domain:[`dataMin`,`dataMax`],tick:Zr,tickLine:!1,axisLine:{stroke:ni},tickFormatter:e=>new Date(Number(e)).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),minTickGap:24}),(0,Q.jsx)(ge,{domain:[0,1],tick:Zr,tickLine:!1,axisLine:!1,width:48,tickFormatter:e=>Ut(Number(e))}),(0,Q.jsx)(he,{...ti,formatter:e=>typeof e==`number`?Ut(e):`Not measured`,labelFormatter:e=>new Date(Number(e)).toLocaleDateString()}),c.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[n.mentioned?(0,Q.jsx)(_e,{type:`linear`,dataKey:`mentioned-${e}`,name:`Mentioned`,stroke:zr[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:zr[1]}}):null,n.cited?(0,Q.jsx)(_e,{type:`linear`,dataKey:`cited-${e}`,name:`Cited`,stroke:Qr.positive,strokeWidth:2,strokeDasharray:`6 4`,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:R_,strokeDasharray:`none`}}):null]},e))]})})})]}):d?null:(0,Q.jsx)(`p`,{className:`py-6 text-copy-14 text-secondary`,children:`No measured trend for this selection.`}),(0,Q.jsxs)(p,{className:f?`sr-only`:`overflow-x-auto`,children:[!f&&(0,Q.jsx)(`summary`,{className:`cursor-pointer text-label-14 text-secondary`,children:`Measurement details`}),(0,Q.jsxs)(`table`,{className:`evidence-table`,"aria-label":`${f_[e.queryClass]} trend data`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Date`}),(0,Q.jsx)(`th`,{children:`Mentioned`}),(0,Q.jsx)(`th`,{children:`Cited`}),(0,Q.jsx)(`th`,{children:`Comparison`})]})}),(0,Q.jsx)(`tbody`,{children:e.trend.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:new Date(e.createdAt).toLocaleDateString()}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(b_,{value:e.mentionCoverage,signal:`mentioned`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(b_,{value:e.citationCoverage,signal:`cited`})}),(0,Q.jsx)(`td`,{children:e.continuity.state.replaceAll(`-`,` `)})]},e.runId))})]})]})]})}function B_(e,t){return t?e?.populations.find(e=>[...e.queries.items,...e.evidence.items].some(e=>e.queryKey===t)):void 0}function V_(e,t,n,r){let i=e.selection.queryClass===`all`?n?.queryClass:e.selection.queryClass,a=e.populations.find(e=>e.queryClass===i);if(a)return a;let o=B_(r,t)??B_(e,t),s=e.populations.find(e=>e.queryClass===o?.queryClass);if(s)return s;let c=[`non-brand`,`branded`,`unknown`].map(t=>e.populations.find(e=>e.queryClass===t));return c.find(e=>e&&(e.summary.queryCount>0||e.trend.some(e=>e.queryCount>0)))??c.find(e=>e!==void 0)??e.populations[0]}var H_={queryType:`Query type`,filters:e=>e===0?`Filters`:`Filters · ${e}`,panel:`Visibility filters`,clearFilters:`Clear filters`,manageQueries:`Manage queries`,removeFilter:e=>`Remove filter ${e}`,engine:e=>`Engine: ${Vo(e)}`,model:e=>`Model: ${e.includes(`/`)?Me(e):e}`,location:e=>`Requested search location: ${e}`,noLocation:`No location requested`,dateRange:(e,t)=>`${e} to ${t} (UTC)`,dateFrom:e=>`From ${e} (UTC)`,dateThrough:e=>`Through ${e} (UTC)`,resultsFrom:e=>`Results from: ${e}`,resultsFromSelectedSweep:`Results from: selected check`,trackingChanged:(e,t,n)=>[e?`Tracking changed ${e}.`:`Tracking changed.`,`Showing the ${t??`last`} results, from before the change.`,`New numbers after the ${n??`next`} check.`].join(` `)},U_={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},W_=`min-h-11 rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`;function G_(e,t){return e&&t?H_.dateRange(e.slice(0,4)===t.slice(0,4)?ri(e):Yr(e),Yr(t)):e?H_.dateFrom(Yr(e)):t?H_.dateThrough(Yr(t)):null}function K_(e,t){let n=[];e.provider&&n.push({key:`engine`,label:H_.engine(e.provider),patch:{measurementProvider:void 0}}),e.model&&n.push({key:`model`,label:H_.model(e.model),patch:{measurementModel:void 0}}),e.location&&n.push({key:`location`,label:e.location===`none`?H_.noLocation:H_.location(e.location),patch:{measurementLocation:void 0}});let r=G_(e.from,e.to);if(r&&n.push({key:`dates`,label:r,patch:{measurementFrom:void 0,measurementTo:void 0}}),e.measurementRunId){let r=t.populations.flatMap(e=>e.trend).find(t=>t.runId===e.measurementRunId);n.push({key:`run`,label:r?H_.resultsFrom(Ur(Gr(r.createdAt))):H_.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function q_(e,t,n){return t===``||e.some(e=>e.value===t)?e:[...e,{value:t,label:n}]}function J_({report:e,selection:t,onSelectionChange:n,onManageQueries:r,renderPropertyLink:i,trackingChangedAt:a,nextSweepDate:o,reportIsPlaceholder:s=!1}){let[c,l]=(0,Z.useState)(!1),u=(0,Z.useRef)(null),d=(0,Z.useId)(),f=`${d}-filters`,{filterOptions:p,selection:m}=e,h=m.measurement,g=V_(e,t.queryKey,t.answer),_=t.queryClass===`all`?g.queryClass:t.queryClass,v=K_(t,e),y=t.measurementScope===`property`?t.measurementScopeKey:void 0,b=y?i?.({id:y,label:ml(e.scopeOptions,t)?.label??y}):null,x=t.provider??``,S=t.model??``,C=t.location??``,w=t.measurementRunId??``,E=!s&&h.awaitingSweep&&h.measuredRevision!==null&&!m.run.explicit&&t.measurementRunId===void 0&&t.revision===void 0&&t.to===void 0,D=()=>u.current?.focus(),O=(e,t,r,i,a)=>(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsxs)(`div`,{className:`mb-1 flex items-center gap-1`,children:[(0,Q.jsx)(`label`,{htmlFor:`${d}-${t}`,className:`text-label-14-strong text-heading`,children:e}),a?(0,Q.jsx)(X,{text:a}):null]}),(0,Q.jsx)(`select`,{id:`${d}-${t}`,className:__,value:r,onChange:e=>n({[t]:e.target.value||void 0,measurementQueryKey:void 0}),children:i.map(e=>(0,Q.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),k=(e,t,r,i)=>(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`label`,{htmlFor:`${d}-${t}`,className:`mb-1 block text-label-14-strong text-heading`,children:e}),(0,Q.jsx)(`input`,{id:`${d}-${t}`,type:`date`,className:__,value:r?.slice(0,10)??``,onChange:e=>n({[t]:e.target.value?`${e.target.value}${i}`:void 0})})]});return(0,Q.jsxs)(`div`,{className:`visibility-filter-container`,children:[(0,Q.jsxs)(`div`,{className:`visibility-results-toolbar`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2`,children:[(0,Q.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:H_.queryType}),(0,Q.jsxs)(`select`,{"aria-label":H_.queryType,className:W_,value:_,onChange:e=>n({queryClass:e.target.value,measurementQueryKey:void 0}),children:[(0,Q.jsx)(`option`,{value:`non-brand`,children:`Non-brand`}),(0,Q.jsx)(`option`,{value:`branded`,children:`Branded`}),(0,Q.jsx)(`option`,{value:`unknown`,children:`Unclassified`})]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(J,{tone:h.state===`measured`?`positive`:`neutral`,children:h.state===`measured`?`Complete`:h.state===`partial`?`Partial`:`Not measured`}),h.completedAt?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:Ur(Gr(h.completedAt))}):null]})]}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-3`,children:[(0,Q.jsx)(q,{ref:u,type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,"aria-expanded":c,"aria-controls":f,onClick:()=>l(e=>!e),children:H_.filters(v.length)}),v.map(e=>(0,Q.jsxs)(q,{type:`button`,variant:`outline`,className:`visibility-filter-token pointer-coarse:min-h-11 rounded-md text-button-14`,"aria-label":H_.removeFilter(e.label),onClick:()=>{n(e.patch),D()},children:[(0,Q.jsx)(`span`,{className:`min-w-0 truncate`,children:e.label}),(0,Q.jsx)(T,{size:16,className:`shrink-0`,"aria-hidden":`true`})]},e.key)),b,r?(0,Q.jsx)(q,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:r,children:H_.manageQueries}):null]})]}),(0,Q.jsxs)(`div`,{id:f,role:`group`,"aria-label":H_.panel,hidden:!c,className:`border-b border-default`,onKeyDown:e=>{e.key===`Escape`&&(e.target instanceof HTMLElement&&e.target.getAttribute(`aria-expanded`)===`true`||(l(!1),D()))},children:[(0,Q.jsxs)(`div`,{className:`visibility-report-filters`,children:[O(`Answer engine`,`measurementProvider`,x,q_([{value:``,label:`All engines`},...p.providers.map(e=>({value:e,label:Vo(e)}))],x,Vo(x))),O(`Requested search location`,`measurementLocation`,C,q_([{value:``,label:`All requested locations`},...p.locations.flatMap(e=>e.kind===`exact`?[{value:e.value,label:e.value}]:e.kind===`none`?[{value:`none`,label:H_.noLocation}]:[])],C,C===`none`?H_.noLocation:C)),O(`AI model`,`measurementModel`,S,q_([{value:``,label:`All models`},...Array.from(new Set(p.models.filter(e=>!t.provider||e.provider===t.provider).map(e=>e.model))).map(e=>({value:e,label:e.includes(`/`)?Me(e):e}))],S,S.includes(`/`)?Me(S):S),`Filter by the AI model recorded with each answer. This does not change the model used by future checks.`),k(`Start date (UTC)`,`measurementFrom`,t.from,`T00:00:00.000Z`),k(`End date (UTC)`,`measurementTo`,t.to,`T23:59:59.999Z`),O(`Results from`,`measurementRunId`,w,q_([{value:``,label:`Latest saved check`},...[...g.trend].reverse().map(e=>({value:e.runId,label:new Date(e.createdAt).toLocaleString()}))],w,`Selected check`),`Choose a saved AI Visibility check to view its results. No new check starts.`)]}),(0,Q.jsx)(`div`,{className:`flex justify-end pb-3`,children:(0,Q.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:v.length===0,onClick:()=>{n({...U_}),D()},children:H_.clearFilters})})]}),E?(0,Q.jsx)(`p`,{role:`status`,className:`border-b border-default py-3 text-copy-14 text-secondary`,children:H_.trackingChanged(a?$r(Gr(a)):null,h.completedAt?$r(Gr(h.completedAt)):null,o??null)}):null]})}function Y_({report:e,isRefreshing:t=!1,onSelectionChange:n,onPage:r,onSearch:i,search:a=``,queryKey:o,answerSelection:s,evidenceReport:c,isEvidenceLoading:l=!1,evidenceError:u,onRetryEvidence:d,onEvidencePage:f}){let p=(0,Z.useRef)(null),m=(0,Z.useRef)(void 0),h=(0,Z.useRef)(null),g=V_(e,o,s,c),_=c??e,v=_.populations.filter(e=>[...e.queries.items,...e.evidence.items].some(e=>e.queryKey===o)),y=s?[s.queryClass]:(v.length?v:l?[]:[g]).map(e=>e.queryClass),b=o?JSON.stringify([s??o,y]):void 0;(0,Z.useEffect)(()=>{if(!b){t||(m.current=void 0);return}if(m.current===b)return;let e=p.current?.querySelectorAll(`[aria-label="${u_}"]`);if(e?.length){for(let t of e){let e=t.closest(`details[data-query-results]`);e&&(e.open=!0)}e[0].focus({preventScroll:!0}),e[0].scrollIntoView?.({block:`start`}),m.current=b}},[b,t]);let{selection:x}=e,S=v_(x.scope),C=new Map(e.scopeOptions.filter(e=>e.kind===`property`).map(e=>[e.id,e.label])),w=e=>{let t=_.populations.find(t=>t.queryClass===e.queryClass)?.evidence;return{items:t?.items.filter(e=>e.queryKey===o&&(!s||e.provider===s.provider&&e.model===s.model&&e.location===s.location&&(s.runId===null||e.runId===s.runId)))??[],nextCursor:t?.nextCursor}},T=()=>{m.current=void 0;let e=h.current;e!==null&&e.row.queryKey===o&&(!s||e.row.provider===s.provider&&e.row.model===s.model&&e.row.location===s.location)&&e?.element.isConnected?e.element.focus():p.current?.querySelector(`details[data-query-results="${g.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})};return(0,Q.jsxs)(`section`,{ref:p,className:`visibility-report`,"aria-label":`AI visibility results`,children:[x.provenance.kind===`legacy-simple`&&x.queryClass!==`unknown`&&x.queryClass!==`all`?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 border-b border-default py-3 text-label-14 text-secondary`,children:[(0,Q.jsx)(`p`,{children:`These saved results aren't separated by query type.`}),(0,Q.jsx)(q,{variant:`outline`,onClick:()=>n({queryClass:`all`,measurementQueryKey:void 0}),children:`View all saved results`})]}):null,[g].map(t=>{let s=A_(t.queries.items,x.scope.kind===`property`&&!x.market&&t.queryClass===`non-brand`?new Map(e.scopeOptions.filter(e=>e.kind===`market`).map(e=>[e.id,e.label])):void 0),c=w(t),p=c.items[0]?.query??t.queries.items.find(e=>e.queryKey===o)?.query,m=x.mode===`advanced`&&x.scope.kind!==`property`,g=p_[t.queryClass],_=T_(t.comparison,w_(x,t)),v=t.trend.length===0&&(t.summary.mentionCoverage.rate!==null||t.summary.citationCoverage.rate!==null)?`No trend history is available for this selection.`:t.trend.length===1?`This view has one measurement point. A trend needs at least two comparable points.`:m_.explanation;return(0,Q.jsxs)(`section`,{"aria-label":f_[t.queryClass],className:`py-4`,children:[(0,Q.jsxs)(`div`,{className:`section-head flex-wrap items-center`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Q.jsx)(`h2`,{children:f_[t.queryClass]}),(0,Q.jsx)(X,{text:t.queryClass===`non-brand`?`Queries that do not name the measured identity. Geography alone is not a brand.`:t.queryClass===`branded`?`Queries that name the measured identity.`:`These queries were not labeled as branded or non-brand when measured. Their saved results remain available here, separate from branded and non-brand rates.`})]}),(0,Q.jsxs)(`div`,{className:`report-headline-caption`,children:[(0,Q.jsx)(`span`,{className:`tabular-nums`,children:E_(t.summary,_)}),(0,Q.jsx)(X,{text:v})]})]}),(0,Q.jsxs)(`dl`,{className:`report-headline mt-3`,"data-columns":m?3:2,"aria-label":`${f_[t.queryClass]} headline results`,children:[(0,Q.jsx)(D_,{label:m?`Answers mentioning a property`:`Mentioned answers`,help:x.mode===`advanced`?h_.advancedMention:h_.simpleMention,value:t.summary.mentionCoverage,signal:`mentioned`,unit:`answers`,classNoun:g,change:S_(t.comparison,`mentionCoverage`)}),(0,Q.jsx)(D_,{label:m?`Answers citing a property`:`Cited answers`,help:x.mode===`advanced`?h_.advancedCitation:h_.simpleCitation,value:t.summary.citationCoverage,signal:`cited`,unit:`answers`,classNoun:g,change:S_(t.comparison,`citationCoverage`)}),m?(0,Q.jsx)(D_,{label:`Properties mentioned`,help:h_.propertyReach,value:t.summary.propertyReach,signal:`mentioned`,unit:`properties`,classNoun:g,change:S_(t.comparison,`propertyReach`)}):null]}),(0,Q.jsx)(Is,{queryClass:x.queryClass,manage:!0}),(0,Q.jsx)(z_,{population:t}),m&&(t.breakdown.groups.length>0||t.breakdown.properties.length>0)?(0,Q.jsx)(X_,{population:t,scope:x.scope,scopeOptions:e.scopeOptions,marketKey:x.market?.id,onSelectionChange:n},`${x.scope.kind}:${x.scope.id}`):null,x.mode===`advanced`?(0,Q.jsxs)(`details`,{className:`visibility-disclosure`,"aria-label":`${f_[t.queryClass]} property outcomes`,children:[(0,Q.jsxs)(`summary`,{className:`visibility-disclosure-summary`,children:[(0,Q.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Property outcomes`}),(0,Q.jsxs)(`span`,{className:`visibility-disclosure-meta`,children:[t.summary.outcomes.total,` `,t.summary.outcomes.total===1?`property`:`properties`]})]}),(0,Q.jsxs)(`div`,{className:`visibility-disclosure-panel flex flex-wrap items-start justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-x-8 gap-y-3`,children:[[`bothSignals`,`mentioned and cited`],[`mentionedOnly`,`mentioned only`],[`citedOnly`,`cited only`],[`neither`,`neither signal`],[`notMeasured`,`not measured`]].map(([e,n])=>(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{className:`block tabular-nums text-heading`,children:t.summary.outcomes[e]}),(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:n})]},e))}),t.summary.notMeasuredUnchecked?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:j_.outcomes(t.summary.notMeasuredUnchecked)}):null,t.summary.notMeasuredNoSources?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:j_.outcomesNoSources(t.summary.notMeasuredNoSources)}):null]}),(0,Q.jsx)(X,{text:g_})]})]}):null,(0,Q.jsxs)(`details`,{className:`visibility-disclosure`,"data-query-results":t.queryClass,"aria-label":`${f_[t.queryClass]} query results`,children:[(0,Q.jsxs)(`summary`,{className:`visibility-disclosure-summary`,children:[(0,Q.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Query results`}),(0,Q.jsxs)(`span`,{className:`visibility-disclosure-meta`,children:[t.queries.total,` `,t.queries.total===1?`result`:`results`,` · `,S]})]}),(0,Q.jsxs)(`div`,{className:`visibility-disclosure-panel`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-3`,children:[i?(0,Q.jsx)(`input`,{type:`search`,"aria-label":`Search ${f_[t.queryClass]}`,placeholder:`Search queries`,className:`${__} max-w-sm`,value:a,onChange:e=>i(e.target.value)}):null,(0,Q.jsx)(X,{text:x.mode===`advanced`?`Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, property scope, and answer counts. Mentioned and Cited count answers matching any assigned property, not the percentage of properties found.`:`Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, and answer counts. Mentioned counts answers naming your brand. Cited counts answers linking to your site.`})]}),(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`evidence-table measurement-responsive-table measurement-results-table`,"aria-label":`${f_[t.queryClass]} engine results`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Answer engine`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Mentioned`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Cited`}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),s.map((e,r)=>(0,Q.jsx)(F_,{group:e,queryClass:t.queryClass,marketHeading:e.marketLabel===s[r-1]?.marketLabel?void 0:e.marketLabel,advanced:x.mode===`advanced`,targetLabels:C,onViewAnswers:(e,r)=>{h.current={row:e,element:r},n({measurementQueryKey:e.queryKey,measurementAnswer:JSON.stringify({queryKey:e.queryKey,queryClass:t.queryClass,provider:e.provider,model:e.model,location:e.location,runId:x.run.id,revision:x.revision})})}},e.queryKey))]})}),t.queries.items.length===0?(0,Q.jsx)(`p`,{className:`py-4 text-copy-14 text-secondary`,children:`No measured queries match this selection.`}):(0,Q.jsxs)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:[s.length,` `,s.length===1?`query`:`queries`,` · `,t.queries.items.length,` `,t.queries.items.length===1?`engine result`:`engine results`,` shown of `,t.queries.total,` results`]}),t.queries.nextCursor&&r?(0,Q.jsx)(q,{variant:`outline`,onClick:()=>r(t.queries.nextCursor),children:`Next queries`}):null,o&&y.includes(t.queryClass)?(0,Q.jsxs)(`section`,{tabIndex:-1,className:`scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,"aria-label":u_,"aria-busy":l,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Q.jsx)(`h3`,{className:`min-w-0 flex-1 text-heading-16 text-heading [overflow-wrap:anywhere]`,children:p??`Answers`}),(0,Q.jsx)(q,{variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:T,children:d_})]}),l?(0,Q.jsx)(`p`,{role:`status`,className:`py-4 text-copy-14 text-secondary`,children:`Loading saved answers…`}):u?(0,Q.jsxs)(`div`,{role:`alert`,className:`py-4 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`p`,{children:[`Saved answers unavailable: `,u]}),d?(0,Q.jsx)(q,{variant:`outline`,onClick:d,children:`Retry answers`}):null]}):(0,Q.jsxs)(Q.Fragment,{children:[c.items.map(e=>(0,Q.jsxs)(`article`,{className:`border-b border-default py-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-2`,children:[(0,Q.jsx)(`strong`,{className:`text-label-14 text-heading`,children:Vo(e.provider)}),e.model&&e.model!==an(e.provider)?(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,title:e.model,children:an(e.provider)?Me(e.model):e.model}):null,(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:e.location===null?H_.noLocation:H_.location(e.location)}),(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Q.jsx)(J,{tone:`neutral`,children:e.mentioned===null?e.mentionUnavailableReason===`identity-ambiguous`?Tr.ambiguous:`Mention not checked`:e.mentioned?`Mentioned`:`Not mentioned`}),(0,Q.jsx)(J,{tone:`neutral`,children:e.cited===null?e.citationUnavailableReason===`citation-not-measured`?Ar.label:`Citation not checked`:e.cited?`Cited`:`Not cited`})]}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(dc,{headingLevel:4,copyable:!!e.answerText?.trim(),children:e.answerText??`Answer text unavailable.`})}),e.sources.length>0?(0,Q.jsxs)(`details`,{className:`mt-2`,"data-answer-sources":!0,children:[(0,Q.jsxs)(`summary`,{className:`min-h-11 cursor-pointer py-3 text-label-14 text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:[Fc,` (`,e.sources.length,`)`]}),(0,Q.jsx)(`ul`,{className:`space-y-2 pb-3`,children:e.sources.map(e=>(0,Q.jsx)(`li`,{className:`min-w-0`,children:(0,Q.jsx)(Cc,{url:e})},e))})]}):null]},e.answerId)),w(t).items.length===0?(0,Q.jsx)(`p`,{className:`py-4 text-copy-14 text-secondary`,children:w(t).nextCursor?`No matching answers on this page. Continue to the next answers.`:`No matching saved answers on this page.`}):null,w(t).nextCursor&&f?(0,Q.jsx)(q,{variant:`outline`,onClick:()=>f(w(t).nextCursor),children:`Next answers`}):null]})]}):null]})]}),(0,Q.jsxs)(`details`,{className:`visibility-disclosure`,"aria-label":`${f_[t.queryClass]} competitors`,children:[(0,Q.jsxs)(`summary`,{className:`visibility-disclosure-summary`,children:[(0,Q.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Competitors`}),(0,Q.jsx)(`span`,{className:`visibility-disclosure-meta`,children:t.competitorAvailability.state===`unavailable`?`Not available`:`${t.competitors.length} measured`})]}),(0,Q.jsxs)(`div`,{className:`visibility-disclosure-panel`,children:[t.competitorAvailability.state===`unavailable`?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Competitor rates unavailable for this historical definition.`}):t.competitors.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No measured competitors in this selection.`}):(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Competitor`}),(0,Q.jsx)(`th`,{children:`Mentioned`}),(0,Q.jsx)(`th`,{children:`Cited`})]})}),(0,Q.jsx)(`tbody`,{children:t.competitors.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:e.domain}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(b_,{value:e.mentionCoverage,signal:`mentioned`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(b_,{value:e.citationCoverage,signal:`cited`})})]},e.domain))})]})}),t.observedCompetitors.length>0?(0,Q.jsxs)(`details`,{className:`mt-4 text-label-14`,children:[(0,Q.jsx)(`summary`,{className:`min-h-11 cursor-pointer py-3 text-heading`,children:`Other names in answers`}),(0,Q.jsx)(`ul`,{className:`divide-y divide-default`,children:t.observedCompetitors.map(e=>(0,Q.jsxs)(`li`,{className:`flex items-center justify-between gap-4 py-3`,children:[(0,Q.jsx)(`span`,{children:e.name}),(0,Q.jsxs)(`span`,{className:`tabular-nums text-secondary`,children:[e.answerCount,` `,e.answerCount===1?`answer`:`answers`]})]},e.name))}),(0,Q.jsx)(`p`,{className:`py-2 text-secondary`,children:`Observed names, not additions to your tracked competitors.`})]}):null]})]})]},t.queryClass)})]})}function X_({population:e,scope:t,scopeOptions:n,marketKey:r,onSelectionChange:i}){let a=new Map(n.filter(e=>e.kind===`group`).map(e=>[e.id,e])),o=[...a.values()].some(e=>e.parentGroupIds?.length),s=e.breakdown.groups.filter(e=>{let n=a.get(e.id)?.parentGroupIds??[];return t.kind===`project`?n.length===0:t.kind===`group`&&o?n.includes(t.id):!0}),[c,l]=(0,Z.useState)(()=>t.kind===`project`&&s.length>0?`groups`:`properties`),u=$l({rows:c===`groups`?s:e.breakdown.properties,getSearchText:e=>e.label});return(0,Q.jsxs)(`section`,{className:`border-t border-default py-5`,"aria-label":`Scope breakdown`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3`,children:[(0,Q.jsx)(`div`,{className:`flex gap-2`,children:[`groups`,`properties`].map(e=>(0,Q.jsx)(q,{variant:c===e?`secondary`:`ghost`,onClick:()=>{l(e),u.setPage(1)},children:e===`groups`?`Groups`:`Properties`},e))}),(0,Q.jsx)(`input`,{type:`search`,"aria-label":`Search breakdown`,placeholder:`Search`,value:u.query,onChange:e=>u.setQuery(e.target.value),className:`${__} max-w-sm`})]}),(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:c===`groups`?`Group`:`Property`}),(0,Q.jsx)(`th`,{children:`Queries`}),(0,Q.jsx)(`th`,{children:`Mentioned`}),(0,Q.jsx)(`th`,{children:`Cited`})]})}),(0,Q.jsx)(`tbody`,{children:u.rows.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{className:`min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>i({measurementScope:c===`groups`?`group`:`property`,measurementScopeKey:e.id,measurementMarketKey:r}),children:e.label})}),(0,Q.jsx)(`td`,{children:e.queryCount}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(b_,{value:e.mentionCoverage,signal:`mentioned`}),(0,Q.jsx)(x_,{value:e.mentionCoverage})]}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(b_,{value:e.citationCoverage,signal:`cited`}),(0,Q.jsx)(x_,{value:e.citationCoverage})]})]},e.id))})]})}),u.rows.length===0?(0,Q.jsxs)(`p`,{className:`py-3 text-copy-14 text-secondary`,children:[`No `,c,` match this search.`]}):null,(0,Q.jsx)(tu,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:c,onPageChange:u.setPage})]})}function Z_(e,t,{enabled:n}){return W({...Mo({client:Y,path:{name:e},query:fc(t)}),enabled:n,staleTime:mi,retry:!1,placeholderData:te})}function Q_(e,t){return t&&e.selection.mode===`simple`&&e.selection.measurement.state===`not-measured`}function $_({projectName:e,selection:t,onSelectionChange:n,fallback:r,showUnmeasuredFallback:i=!1}){let[a,o]=(0,Z.useState)(),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(),d=z(),f=(0,Z.useMemo)(()=>({scope:t.measurementScope,scopeKey:t.measurementScopeKey,marketKey:t.marketKey,queryClass:t.queryClass,provider:t.provider,model:t.model,location:t.location,from:t.from,to:t.to,revision:t.revision,runId:t.measurementRunId}),[t.measurementScope,t.measurementScopeKey,t.marketKey,t.queryClass,t.provider,t.model,t.location,t.from,t.to,t.revision,t.measurementRunId]),p=W({...Mo({client:Y,path:{name:e},query:{...fc(t),cursor:a,search:s||void 0}}),staleTime:mi,retry:!1,placeholderData:te}),m={...f,queryKey:t.queryKey,queryClass:t.answer?.queryClass??t.queryClass,provider:t.answer?.provider??t.provider,model:t.answer?t.answer.model??void 0:t.model,location:t.answer?t.answer.location??`none`:t.location,runId:t.answer?.runId??p.data?.selection.run.id??t.measurementRunId,revision:t.answer?.revision??p.data?.selection.revision??t.revision,limit:50},h=JSON.stringify(m),g=W({...Mo({client:Y,path:{name:e},query:{...m,cursor:l?.selection===h?l.cursor:void 0}}),enabled:!!t.queryKey&&!!p.data&&!p.isPlaceholderData,retry:!1});if((0,Z.useEffect)(()=>{if(t.queryClass!==`all`||!p.data||p.isPlaceholderData||p.isFetching||p.isError||p.data.selection.availability.state===`unsupported`||p.data.populations.length===0||t.queryKey&&!t.answer&&!B_(p.data,t.queryKey)&&!g.data)return;let r=V_(p.data,t.queryKey,t.answer,g.data);if(!a&&!s){let{queryKey:n}=Mo({client:Y,path:{name:e},query:fc({...t,queryClass:r.queryClass})});d.setQueryData(n,{...p.data,selection:{...p.data.selection,queryClass:r.queryClass},populations:[r]},{updatedAt:p.dataUpdatedAt})}n({queryClass:r.queryClass,...t.queryKey?{measurementQueryKey:t.queryKey,measurementAnswer:t.answer?JSON.stringify(t.answer):void 0}:{}},{replace:!0})},[t.queryClass,t.queryKey,t.answer,p.data,p.dataUpdatedAt,p.isPlaceholderData,p.isFetching,p.isError,g.data,n,d,e,f,a,s]),p.data?.selection.availability.state===`unsupported`||p.data&&Q_(p.data,i))return(0,Q.jsx)(Q.Fragment,{children:r});if(p.error){let e=it(Tn(p.error)),t=e?.reason===ke[`retired-market`];return(0,Q.jsxs)(`section`,{className:`page-section-divider`,role:`alert`,children:[(0,Q.jsx)(`h2`,{children:`AI visibility unavailable`}),(0,Q.jsx)(`p`,{className:`my-3 text-copy-14 text-secondary`,children:t?k_.retiredMarket:e?k_.retiredScope:be(p.error)}),t?(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{o(void 0),n({measurementMarketKey:void 0})},children:k_.showAllMarkets}):e?(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{o(void 0),n({measurementScope:`project`,measurementScopeKey:void 0})},children:k_.showWholeSite}):(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{o(void 0),p.refetch()},children:`Retry`})]})}return p.data?(0,Q.jsx)(`div`,{"aria-busy":p.isFetching,children:(0,Q.jsx)(Y_,{report:p.data,isRefreshing:p.isFetching,queryKey:t.queryKey,answerSelection:t.answer,evidenceReport:g.data,isEvidenceLoading:g.isFetching||!!t.queryKey&&g.isPending,evidenceError:g.error?be(g.error):void 0,onRetryEvidence:()=>{g.refetch()},onEvidencePage:g.isFetching?void 0:e=>u({selection:h,cursor:e}),search:s,onSearch:e=>{c(e),o(void 0)},onPage:p.isFetching?void 0:o,onSelectionChange:e=>{(!(`measurementQueryKey`in e)||Object.keys(e).some(e=>e!==`measurementQueryKey`&&e!==`measurementAnswer`))&&o(void 0),u(void 0),n(e)}})}):(0,Q.jsx)(`section`,{className:`page-section-divider`,role:`status`,"aria-label":`Loading AI visibility`,children:(0,Q.jsx)(`div`,{className:`h-64 animate-pulse rounded-md bg-surface`})})}function ev({projectName:e,selection:t,onSelectionChange:n,onManageQueries:r,renderPropertyLink:i,trackingChangedAt:a,nextSweepDate:o,fallback:s,showUnmeasuredFallback:c=!1}){let l=Z_(e,t,{enabled:!0}),u=l.error?void 0:l.data,d=!l.isPlaceholderData&&u?.selection.availability.state===`available`?u.selection.run.id:null;Hc(d,null);let f=!(!u||u.selection.availability.state!==`available`||Q_(u,c));return(0,Q.jsxs)(Q.Fragment,{children:[f?(0,Q.jsx)(J_,{report:u,selection:t,onSelectionChange:n,onManageQueries:r,renderPropertyLink:i,trackingChangedAt:a,nextSweepDate:o,reportIsPlaceholder:l.isPlaceholderData}):null,!f&&(u||l.error)?(0,Q.jsx)(`div`,{className:`mb-3 flex justify-end`,children:(0,Q.jsx)(Ks,{})}):null,(0,Q.jsx)($_,{projectName:e,selection:t,onSelectionChange:n,fallback:s,showUnmeasuredFallback:c},`${e}:${JSON.stringify({...t,queryKey:void 0,answer:void 0})}`)]})}var tv=[{value:`byProvider`,label:`By engine`},{value:`overall`,label:`All engines`}],nv=[{value:`non-brand`,label:`Non-brand`,description:`Queries that do not name you.`},{value:`branded`,label:`Branded`,description:`Queries that name you, where a mention is nearly certain.`},{value:`all`,label:`All`,description:`Branded and non-brand queries pooled.`}],rv=[{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:`Your share of the answer-text brand mentions for you and tracked competitors, in non-brand answers, or in all answers when queries cannot be split by brand.`}],iv=zr[2],av=zr[4],ov=`var(--chart-tooltip-bg)`,sv={up:`text-positive-400`,down:`text-negative-400`,none:`text-muted`};function cv({direction:e,magnitude:t}){switch(e){case`up`:return`up ${t} points`;case`down`:return`down ${t} points`;case`none`:return`no change`}}function lv(e){return e.direction===`none`?`no change over the period`:`${cv(e)} over the period`}function uv(e){return e===`__cited__`||e===`__mentioned__`||e===`__mentionShare__`}function dv(e){return e===`__cited__`?`Cited`:e===`__mentioned__`?`Mentioned`:e===`__mentionShare__`?`Mention share`:Vo(e)}function fv(e,t){return e===`__cited__`?Qr.positive:e===`__mentioned__`?zr[1]:e===`__mentionShare__`?iv:Rr(bs(e),t)}function pv(e){return e===`non-brand`?`non-brand answers`:`all answers`}function mv(e){return e===`cited`?`Cited`:e===`mentionShare`?`Mention share`:`Mentioned`}function hv(e,t){return e===`mentionShare`?`Mention share in ${pv(t)}`:mv(e)}function gv(e){return`Mentioned = share of answers that name you. Cited = share that link to your site. Mention share = your share of tracked-brand mentions in ${e===`non-brand`?`non-brand answers`:`all answers`}.`}var _v={value:`Not measured`,point:`not measured, no answer has sources`,window:`Not measured: the engines in this window return no sources, so whether they cite you is not measured.`};function vv(e,t){return t===`cited`?{count:e.cited,total:e.citedTotal??e.total,rate:e.citationRate}:{count:e.mentionedCount,total:e.total,rate:e.mentionRate}}function yv(e,t,n){let r=e.byProvider[t];return r?vv(r,n):null}function bv(e){return e.rate===null?_v.point:`${e.count} of ${e.total}`}function xv(e,t){let n=mv(t).toLowerCase();return e.rate===null?`${n} ${_v.point}`:`${Ut(e.rate)} ${n}, ${e.count} of ${e.total} answers`}function Sv(e,t){if(t===`mentionShare`){let{projectMentionSnapshots:t,competitorMentionSnapshots:n}=e.mentionShare;return`${t} of ${t+n} tracked-brand mentions`}let n=vv(e,t);return n.rate===null?_v.point:`${n.count} of ${n.total} answers`}function Cv(e,t){if(t===void 0)return null;let n=String(t);return e.find(e=>e.startDate===n)??null}function wv(e){let t=cs(e);return t===null?[]:Object.entries(t).sort(([e],[t])=>bs(e).localeCompare(bs(t))).map(([e,t])=>`${Vo(e)}: ${ds(t)}`)}function Tv(e,t){return new Date(e).toDateString()===new Date(t).toDateString()}function Ev(e){return`${e} ${e===1?`query`:`queries`}`}function Dv(e){let{added:t,removed:n}=e;return[...t.length>0?[`${Ev(t.length)} added`]:[],...n.length>0?[`${t.length>0?n.length:Ev(n.length)} removed`]:[]].join(`, `)}function Ov(e,t){let n=Go(e),r=is(e),i=ys(e,t);if(!n||!r||!i)return null;let a=qo(i.moves),o=Tv(n.start,n.end),s=e=>Nr(e,o?n.start:null);return n.sweepCount===2?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`strong`,{children:r}),` point mixes the `,(0,Q.jsx)(`strong`,{children:s(n.start)}),` check and the `,(0,Q.jsx)(`strong`,{children:s(n.end)}),` check, with `,a,` between them`]}):i.moves.added.length+i.moves.removed.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`strong`,{children:r}),` point mixes checks with `,a,` between them`]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`strong`,{children:r}),` point pools `,(0,Q.jsx)(`strong`,{children:n.sweepCount}),` checks, with `,a,` between the first and last`]})}function kv(e,t,n){let r=Ov(t,n);return r?(0,Q.jsxs)(Q.Fragment,{children:[`Not the same queries: `,r]}):e.changes.length>0?(0,Q.jsxs)(Q.Fragment,{children:[`Not the same queries: `,e.changes.map((e,t)=>(0,Q.jsxs)(Z.Fragment,{children:[t>0?`, `:``,Dv(e),` `,(0,Q.jsx)(`strong`,{children:os(Gr(e.at))})]},e.at)),`; first and latest points cover different queries`]}):(0,Q.jsxs)(Q.Fragment,{children:[`Not the same queries: first and latest points have answers for `,(0,Q.jsx)(`strong`,{children:e.firstCount}),` and `,(0,Q.jsx)(`strong`,{children:e.latestCount}),` queries`]})}var Av=`Queries changed`;function jv(e){let t=qo(e.moves);return t?`${Av}: ${t} between the first and latest points, so the change compares different queries.`:`${Av}: the first and latest points have answers for ${e.firstCount} and ${e.latestCount} queries, so the change compares different queries.`}function Mv(e){return e.replace(/ /g,`\xA0`)}function Nv({state:e,from:t=!1}){return(0,Q.jsx)(`span`,{className:t?`av-model av-model-from`:`av-model`,children:ds(e)})}function Pv(e,t){return e.reroute?`Same preset, answered with a different model.`:as(e.provider,e.to)?e.served?`Preset picks its own model. Answered with ${ds(e.served.to)} (was ${ds(e.served.from)}).`:t&&t.length>0?`Preset picks its own model. Answered with ${t.map(e=>e.includes(`/`)?Me(e):e).join(`, `)}.`:`Preset picks its own model.`:null}function Fv({buckets:e,queryChanges:t,modelRows:n,served:r,pointerNotices:i,truncated:a,incompleteHistory:o,queryName:s,sweepTimes:c}){let l=e.at(-1),u=e=>os(e),d=new Map;for(let[e,t]of i){let r=n.find(n=>n.provider===e&&!n.reroute&&n.to.status===`known`&&t.modelIds.includes(n.to.model));r&&d.set(e,r)}let f=[];t.length>0&&f.push({key:`queries`,label:`Queries`,rows:t.map(e=>({key:`queries-${e.at}`,at:e.at,onOrBefore:!1,from:null,to:(0,Q.jsx)(`span`,{className:`text-strong`,children:Dv(e)}),toHelp:null}))});let p=[...new Set(n.map(e=>e.provider))].sort((e,t)=>Vo(e).localeCompare(Vo(t)));for(let e of p){let t=r[e]?.latestServedModelIds??null,a=n.filter(t=>t.provider===e);f.push({key:e,label:Vo(e),rows:a.map((n,r)=>{let a=d.get(e)===n?i.get(e).text:null,o=[Pv(n,r===0?t:null),a].filter(Boolean).join(` `);return{key:`${e}-${n.at}-${n.reroute?`served`:`set`}`,at:n.at,onOrBefore:n.onOrBefore,from:(0,Q.jsx)(Nv,{state:n.from,from:!0}),to:(0,Q.jsx)(Nv,{state:n.to}),toHelp:o||null}})})}let m=f.reduce((e,t)=>e+t.rows.length,0),h=[];for(let e of t)e.added.length>0&&h.push((0,Q.jsxs)(Q.Fragment,{children:[`Added `,(0,Q.jsx)(`strong`,{children:u(e.at)}),`: `,e.added.map(s).join(`, `)]})),e.removed.length>0&&h.push((0,Q.jsxs)(Q.Fragment,{children:[`Removed `,(0,Q.jsx)(`strong`,{children:u(e.at)}),`: `,e.removed.map(s).join(`, `)]}));let g=l?is(l):null;for(let[e,t]of Object.entries(l?cs(l)??{}:{}).sort(([e],[t])=>e.localeCompare(t)))t.status===`mixed`&&g&&h.push((0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`strong`,{children:g}),` point mixes `,Vo(e),` models: `,ms(t)]}));let _=new Map;for(let e of n.filter(e=>e.onOrBefore)){let t=e.anchorAt?u(e.anchorAt):``;_.set(t,[...new Set([..._.get(t)??[],Vo(e.provider)])])}for(let[e,t]of _)h.push(e?(0,Q.jsxs)(Q.Fragment,{children:[`Changed before this date range, after the `,(0,Q.jsx)(`strong`,{children:e}),` check: `,$o(t)]}):`Changed before this date range: ${$o(t)}`);for(let e of a)h.push(`${Vo(e.provider)}: most recent ${e.shown} of ${e.total} changes`);for(let e of o)h.push(`${Vo(e)}: may be missing older changes`);for(let[e,t]of i)d.has(e)||h.push((0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[Vo(e),`: no model updates on record`,(0,Q.jsx)(X,{text:t.text})]}));if(m===0&&h.length===0)return null;for(let[e,t]of Object.entries(r).sort(([e],[t])=>Vo(e).localeCompare(Vo(t)))){let n=t.latestServedModelIds??[],r=n.length>0?n.map(e=>e.includes(`/`)?Me(e):e).join(`, `):ds(t.latestObservation.state);h.push((0,Q.jsxs)(Q.Fragment,{children:[Vo(e),` last answered with `,(0,Q.jsx)(`strong`,{children:r}),` on `,(0,Q.jsx)(`strong`,{children:u(Gr(t.latestObservation.observedAt))})]}))}let v=f.flatMap(e=>e.rows.map(e=>e.at)),y=`First check on the new model or query set.`;if(v.length>0){let t=u(v.reduce((e,t)=>Date.parse(t)>Date.parse(e)?t:e)),r=[...new Set(v.filter(e=>u(e)===t))].sort(),i=r.map(e=>Nr(e,e));y+=` ${t} = the ${$o(i)} ${i.length===1?`check`:`checks`}.`;let a=n.flatMap(e=>e.anchorAt?[e.anchorAt]:[]),o=a.length>0?a.reduce((e,t)=>Date.parse(t)>Date.parse(e)?t:e):null,s=Ss(r[0],c,e,o);s&&(y+=` Check before: ${u(s)}.`)}let b=Qo({latest:l,queryChanges:t,modelRows:n})??`No changes in this date range`;return(0,Q.jsxs)(`details`,{className:`av-wc`,children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsx)(`span`,{className:`av-card-title`,children:`What changed`}),(0,Q.jsx)(`span`,{className:`av-wc-summary av-wc-when-closed`,children:b}),(0,Q.jsxs)(`span`,{className:`av-wc-toggle`,children:[(0,Q.jsxs)(`span`,{className:`av-wc-when-closed`,children:[m>0?`Show all ${m}`:`Details`,` `,(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`▸`})]}),(0,Q.jsxs)(`span`,{className:`av-wc-when-open`,children:[`Hide `,(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`▴`})]})]})]}),(0,Q.jsx)(`div`,{className:`av-wc-body`,children:m>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`av-change-table`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Query and model changes, newest first`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Changed`})}),(0,Q.jsx)(`th`,{scope:`col`,"aria-label":`Date`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[`Date`,(0,Q.jsx)(X,{text:y})]})}),(0,Q.jsx)(`th`,{scope:`col`,children:`From`}),(0,Q.jsx)(`th`,{scope:`col`,children:`To`})]})}),f.map(e=>(0,Q.jsx)(`tbody`,{children:e.rows.map((t,n)=>(0,Q.jsxs)(`tr`,{children:[n===0?(0,Q.jsx)(`th`,{scope:`row`,className:`av-engine`,children:e.label}):(0,Q.jsx)(`td`,{className:`av-engine`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:e.label})}),(0,Q.jsx)(`td`,{className:`av-date`,children:t.onOrBefore?`on or before ${Mv(u(t.at))}`:Mv(u(t.at))}),t.from===null?null:(0,Q.jsx)(`td`,{children:t.from}),(0,Q.jsx)(`td`,{colSpan:t.from===null?2:void 0,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t.to,t.toHelp?(0,Q.jsx)(X,{text:t.toHelp}):null]})})]},t.key))},e.key))]})}),(0,Q.jsx)(El,{items:h})]}):(0,Q.jsx)(`ul`,{className:`av-details-list`,children:h.map((e,t)=>(0,Q.jsx)(`li`,{children:e},t))})})]})}function Iv({substitutions:e}){return e.length===0?null:(0,Q.jsx)(`ul`,{className:`space-y-3`,"aria-label":`Model substitutions`,children:e.map(({provider:e,mismatch:t})=>(0,Q.jsxs)(`li`,{className:`av-amber-row border border-caution-800/60 bg-caution-950/20`,children:[(0,Q.jsx)(`span`,{className:`av-engine`,children:Vo(e)}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`selected `,(0,Q.jsx)(Nv,{state:t.configured}),` · answered `,(0,Q.jsx)(Nv,{state:t.served})]}),(0,Q.jsx)(`span`,{className:`av-status text-caution-400`,children:`substituted`})]},e))})}function Lv({active:e,label:t,payload:n,metric:r,mode:i,buckets:a,basketChanges:o}){if(!e)return null;let s=Cv(a,t);if(!s)return null;let c=Go(s),l=c!==null&&Tv(c.start,c.end)?c.start:null,u=ps(s,o),d=wv(s),f=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`trend-tooltip-label`,children:_s(s)}),u.map(e=>(0,Q.jsxs)(`p`,{className:`trend-tooltip-detail trend-tooltip-note`,children:[Dv(e),` `,Nr(e.at,l)]},e.at))]}),p=d.length>0&&(0,Q.jsx)(`p`,{className:`trend-tooltip-detail trend-tooltip-models`,children:d.map((e,t)=>(0,Q.jsxs)(Z.Fragment,{children:[t>0?`; `:``,(0,Q.jsx)(`span`,{className:`whitespace-nowrap`,children:e})]},t))});if(r===`mentionShare`){let e=s.mentionShare.projectMentionSnapshots,t=s.mentionShare.competitorMentionSnapshots,n=e+t;return(0,Q.jsxs)(`div`,{className:`trend-tooltip`,children:[f,(0,Q.jsxs)(`div`,{className:`trend-tooltip-row`,children:[(0,Q.jsx)(`span`,{className:`trend-tooltip-swatch trend-tooltip-swatch-ring`,style:{borderColor:iv},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`trend-tooltip-name`,children:hv(`mentionShare`,s.mentionShare.scope)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-value`,children:Ut(s.mentionShare.rate)})]}),(0,Q.jsx)(`p`,{className:`trend-tooltip-detail`,children:n>0?`You ${e} of ${n} tracked-brand mentions. Competitors ${t}.`:`No tracked-brand mentions in this point`}),p]})}let m=i===`byProvider`?(n??[]).filter(e=>e.dataKey!==void 0):[{dataKey:r===`cited`?hs:ss}];return(0,Q.jsxs)(`div`,{className:`trend-tooltip`,children:[f,m.map((e,t)=>{let n=String(e.dataKey??e.name??``),a=(i===`byProvider`?yv(s,n,r):null)??vv(s,r),o=e.color??fv(n,t);return(0,Q.jsx)(`div`,{className:`trend-tooltip-block`,children:(0,Q.jsxs)(`div`,{className:`trend-tooltip-row`,children:[(0,Q.jsx)(`span`,{className:`trend-tooltip-swatch`,style:{backgroundColor:o},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`trend-tooltip-name`,children:dv(n)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-value`,children:a.rate===null?_v.value:Ut(a.rate)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-count`,children:bv(a)})]})},`${n}-${t}`)}),p]})}function Rv({buckets:e,metric:t,mode:n,series:r,mentionShareScope:i}){return(0,Q.jsx)(`div`,{className:`sr-only`,children:(0,Q.jsxs)(`table`,{children:[(0,Q.jsxs)(`caption`,{children:[hv(t,i),` trend data`]}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Point`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Values`})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let i;if(t===`mentionShare`){let t=e.mentionShare.projectMentionSnapshots,n=t+e.mentionShare.competitorMentionSnapshots,r=pv(e.mentionShare.scope);i=n>0?`${Ut(e.mentionShare.rate)} mention share in ${r}, ${t} of ${n} tracked-brand mentions were you`:`mention share undefined in ${r}, no project or competitor brand mentions`}else i=n===`byProvider`?r.map(n=>{let r=yv(e,n,t);return r?`${Vo(n)} ${xv(r,t)}`:`${Vo(n)} no data`}).join(`; `):xv(vv(e,t),t);let a=wv(e);return a.length>0&&(i+=`; models: ${a.join(`; `)}`),(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,children:_s(e)}),(0,Q.jsx)(`td`,{children:i})]},e.startDate)})})]})})}function zv({projectName:e,competitorDomains:t=[],competitorAliases:n,analyticsRevision:r=`none`,queryTexts:i=[],classifyQuery:a,sweepTimes:o=[],queryClassSplit:s=!1}){let[c,l]=(0,Z.useState)(`all`),[u,d]=(0,Z.useState)(`mentioned`),[f,p]=(0,Z.useState)(`non-brand`),m=s&&u!==`mentionShare`,h=m?f:`all`,[g,_]=(0,Z.useState)(`byProvider`),v=(0,Z.useId)(),y=(0,Z.useMemo)(()=>us(t,n),[t,n]),b=W({queryKey:[`analytics-metrics`,e,c,y,r,h],queryFn:()=>Te(e,c,h),staleTime:fi}),x=b.data??null,S=b.error,C=u===`mentionShare`?`overall`:g,w=(0,Z.useMemo)(()=>x?gs(x,u,C):null,[x,u,C]),T=x?Ko(x):null,E=(0,Z.useMemo)(()=>Xo(T??{}),[T]),D=(0,Z.useMemo)(()=>Ro(T??{}),[T]),O=(0,Z.useMemo)(()=>Object.entries(T??{}).filter(([,e])=>e.anchorUnavailable).map(([e])=>e).sort(),[T]),k=(0,Z.useMemo)(()=>x?Uo(x):{},[x]),A=(0,Z.useMemo)(()=>x?Yo(Ho(x)):[],[x]),j=(0,Z.useMemo)(()=>x?Lo(x):[],[x]),M=(0,Z.useMemo)(()=>x?Bo(x):[],[x]),N=(0,Z.useMemo)(()=>ts(T??{},k),[T,k]),P=(0,Z.useMemo)(()=>x?Jo(x):{},[x]),F=(0,Z.useMemo)(()=>Ve(P,{engineName:Vo}),[P]),I=(0,Z.useMemo)(()=>{let e=new Map;for(let[t,n]of Object.entries(P).sort(([e],[t])=>e.localeCompare(t))){let r=Ve({[t]:n},{engineName:Vo});r?.kind===`no-known-change`&&e.set(t,{text:`${r.text} ${r.detail}`,modelIds:n.modelIds??[]})}return e},[P]),ee=(0,Z.useMemo)(()=>{let e=new Map(i.map(e=>[tt(e),e]));return t=>e.get(tt(t))??t},[i]),L=u!==`mentionShare`&&C===`byProvider`,R=x?.buckets??[],z=R[R.length-1]?.mentionShare.scope??x?.mentionShareScope??`pooled`,te=hv(u,z),ne=L?Kr.textDim:u===`cited`?Qr.positive:u===`mentionShare`?iv:zr[1],B=(0,Z.useMemo)(()=>{let e=new Map(R.map(e=>[e.startDate,rs(e)]));return t=>e.get(String(t))??``},[R]),V=u===`mentionShare`?R.filter(e=>typeof e.mentionShare.rate==`number`&&Number.isFinite(e.mentionShare.rate)):u===`cited`?R.filter(e=>e.citationRate!==null):R,H=V.at(-1),re=(x?zo(x,u):[]).at(-1)??null,U=x?xs(x,u):null,ie=ls(V,j),ae=Wo(ie,u,z,a),se=re!==null&&U!==null?lt(U.delta):null,ce=se!==null&&!ae,de=t.length,fe=[];if(re!==null&&H&&fe.push((0,Q.jsxs)(Q.Fragment,{children:[`Latest point: `,(0,Q.jsx)(`strong`,{children:Sv(H,u)})]})),H&&U!==null&&ie&&!ae&&fe.push(kv(ie,H,j)),H&&V.length===1){let e=Ov(H,j);e&&!Wo(ys(H,j),u,z,a)&&fe.push(e)}if(se!==null&&V[0]){let e=is(V[0]);e&&fe.push((0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:e}),` point`]}))}if(L&&re!==null){let e=u===`cited`&&H&&H.citationNotMeasured>0?`all answers with sources`:`all answers`;fe.push((0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`strong`,{children:Ut(re)}),` pools `,e,`; not an average of engines`]}))}let pe=[...new Set([...E.buckets.map(e=>e.bucketStartDate),...R.filter(e=>ps(e,j).length>0).map(e=>e.startDate)])].sort(),me=re!==null&&H&&(0,Q.jsxs)(`div`,{className:`visibility-trend-current`,children:[(0,Q.jsx)(`span`,{className:`visibility-trend-current-dot`,style:{backgroundColor:ne},"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`visibility-trend-current-label`,children:[te,!m&&u!==`mentionShare`?` · ${h} queries`:``]}),(0,Q.jsxs)(`span`,{className:`visibility-trend-current-value`,children:[Ut(re),m?(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` · `,h,` queries`]}):null]}),w?.rows.length===1&&(0,Q.jsx)(X,{text:`This view has one measurement point. A trend needs at least two comparable points.`,placement:`bottom`}),se!==null&&(0,Q.jsx)(`span`,{className:`visibility-trend-current-delta ${ce?`text-muted`:sv[se.direction]}`,children:cv(se)}),ce&&ie?(0,Q.jsx)(X,{tone:`caution`,label:`Queries changed`,text:jv(ie)}):null]}),xe=(0,Q.jsxs)(`div`,{className:`visibility-trend-controls`,children:[(0,Q.jsx)(Bc,{options:rv,value:u,onChange:d,label:`Metric`,className:`visibility-trend-metric-control`}),u!==`mentionShare`&&(0,Q.jsx)(Bc,{options:tv,value:g,onChange:_,label:`Series`}),(0,Q.jsx)(Bc,{options:l_,value:c,onChange:l,label:`Time window`,className:`sm:ml-auto`})]}),Se;if(S)Se=(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative-400`,children:be(S)});else if(b.isLoading&&!x)Se=(0,Q.jsx)(`div`,{className:`visibility-trend-chart animate-pulse rounded-md bg-bg-elevated/40`,"aria-hidden":`true`});else if(u===`mentionShare`&&de===0)Se=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Add tracked competitors to measure mention share over time.`});else if(!x||!w)Se=null;else{let{rows:e,series:t,hasData:n}=w;if(!n)Se=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:u===`mentionShare`?`No answer-text brand mentions for you or tracked competitors in ${pv(z)} in this window yet.`:h===`all`?we()?Ls:`Run a check to start tracking citations and mentions over time.`:`No ${h} answers in this window.`});else if(u===`cited`&&!ns(x))Se=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:_v.window});else if(L&&t.length===0)Se=(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`No per-engine breakdown for this data yet. Switch to `,(0,Q.jsx)(`span`,{className:`text-strong`,children:`All engines`}),` to see the trend.`]});else{let n=`${te} rate${h===`all`?``:` in ${h} answers`} across ${e.length} ${e.length===1?`check`:`checks`}. Latest ${Ut(re)}${se===null?``:`, ${lv(se)}${ce?`, not the same queries`:``}`}.`;Se=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`sr-only`,children:n}),(0,Q.jsx)(Rv,{buckets:R,metric:u,mode:C,series:t,mentionShareScope:z}),L&&t.length>0&&(0,Q.jsx)(`ul`,{className:`trend-legend`,"aria-label":`Engines`,children:t.map((e,t)=>{let n=vs(x,e,u);return(0,Q.jsxs)(`li`,{className:`trend-legend-item`,children:[(0,Q.jsx)(`span`,{className:`trend-legend-swatch`,style:{backgroundColor:fv(e,t)},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`trend-legend-name`,children:dv(e)}),n===null?u===`cited`&&Zo(x,e)&&(0,Q.jsx)(`span`,{className:`trend-legend-value`,children:_v.value}):(0,Q.jsx)(`span`,{className:`trend-legend-value`,children:Ut(n)})]},e)})}),(0,Q.jsx)(`div`,{className:`visibility-trend-chart`,role:`img`,"aria-label":`${te} trend chart over ${e.length} ${e.length===1?`point`:`points`}`,children:(0,Q.jsx)(le,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(ve,{data:e,margin:{top:8,right:20,bottom:0,left:0},children:[(0,Q.jsx)(oe,{stroke:ei,vertical:!1}),(0,Q.jsx)(ue,{dataKey:`date`,tick:Zr,tickLine:!1,axisLine:{stroke:ni},tickFormatter:B,minTickGap:24}),(0,Q.jsx)(ge,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:e=>Ut(e,Je.percent),tick:Zr,tickLine:!1,axisLine:!1,width:48}),(0,Q.jsx)(he,{cursor:{stroke:ni,strokeWidth:1},content:(0,Q.jsx)(Lv,{metric:u,mode:C,buckets:R,basketChanges:j})}),pe.map(e=>(0,Q.jsx)(ye,{x:e,stroke:av,strokeDasharray:`4 4`,strokeWidth:1.5,ifOverflow:`extendDomain`},`setup-change-${e}`)),t.map((e,t)=>(0,Q.jsx)(_e,{type:`monotone`,dataKey:e,name:e,stroke:fv(e,t),strokeDasharray:e===`__mentionShare__`?`5 4`:void 0,strokeWidth:uv(e)?2.5:2,dot:e===`__mentionShare__`?{r:2.75,fill:`var(--chart-tooltip-bg)`,stroke:fv(e,t),strokeWidth:1.5}:{r:2.5,fill:fv(e,t),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:ov},connectNulls:e!==es,isAnimationActive:!1},e))]})})}),pe.length>0&&(0,Q.jsxs)(`p`,{className:`visibility-trend-key`,children:[(0,Q.jsx)(`span`,{className:`visibility-trend-key-swatch`,"aria-hidden":`true`}),`Setup changed`]})]})}}return(0,Q.jsxs)(`div`,{className:`visibility-trend-stack`,children:[(0,Q.jsxs)(`section`,{className:`visibility-trend`,"aria-labelledby":v,children:[(0,Q.jsxs)(`div`,{className:`av-card-head`,children:[(0,Q.jsxs)(`div`,{className:`inline-flex items-center`,children:[(0,Q.jsx)(`h2`,{id:v,className:`av-card-title`,children:`AI answers over time`}),(0,Q.jsx)(X,{text:gv(z)})]}),H?(0,Q.jsx)(`p`,{className:`av-card-meta`,children:_s(H)}):null]}),(0,Q.jsxs)(`div`,{className:`visibility-trend-body`,children:[F?.kind===`change`&&(0,Q.jsx)(`p`,{className:`mb-3 rounded-md border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-copy-13 text-secondary`,children:F.text}),m&&(0,Q.jsx)(`div`,{className:`mb-3`,children:(0,Q.jsx)(Bc,{options:nv,value:f,onChange:p,label:`Query type`})}),me,xe,Se]}),(0,Q.jsx)(El,{items:fe})]}),x&&!S?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Fv,{buckets:R,queryChanges:M,modelRows:N,served:k,pointerNotices:I,truncated:D,incompleteHistory:O,queryName:ee,sweepTimes:o}),(0,Q.jsx)(Iv,{substitutions:A})]}):null]})}var Bv=new Set([qt.queued,qt.running]),Vv={queryPlaceholder:`Write one research query per line`,patternPlaceholder:`best {market} apartments near transit`,patternGuidance:`Write one query pattern per line. For example, “best {market} apartments near transit”.`,inheritedModel:`Use AI Visibility model`,runAction:`Run queries`,savedNote:`Saved separately from tracked queries and AI Visibility metrics.`,historyTitle:`Research history`,historyMore:`Load older runs`,historyLoading:`Loading older runs…`,historyMoreError:`Could not load older research. Try again.`,resultsTitle:`Research results`,emptyHistory:`No saved research.`,resultsEmpty:`Choose a saved run.`,methodologySummary:`How matching works`,methodology:`Brand-name matches use configured project names or domains in answer text. Project-domain citations use source links. Neither verifies property identity.`,stalePreview:`The plan or saved pattern changed after this preview. Your edits are preserved. Regenerate before starting research.`,refreshPreview:`Regenerate preview`,templateProvenance:`Query pattern details`,brandedQuery:`Branded`,discoveryQuery:`Discovery`,unclassifiedQuery:`Unclassified`};function Hv({projectName:e,onReviewForTracking:t,scopeOptions:n,planRevision:r,selectedScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c=[],viewerResearchConfig:l=null}){let u=z(),{account:d,canWrite:f}=si(),p=d?.role===`viewer`&&l!==null,m=!f,h=rt(),[g,_]=(0,Z.useState)(``),[v,y]=(0,Z.useState)(``),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)([]),w=(0,Z.useRef)(null),T=(0,Z.useRef)(!1),[E,D]=(0,Z.useState)(0),O=W({...Mi({client:Y,path:{name:e}}),staleTime:6e4}),k=W({...ki({client:Y}),enabled:!m&&!h,staleTime:6e4}),A={client:Y,path:{name:e},query:{limit:20}},j=ne({...Ri(A),initialData:void 0,initialPageParam:A,getNextPageParam:e=>e.nextCursor?{path:A.path,query:{...A.query,cursor:e.nextCursor}}:void 0,refetchInterval:e=>e.state.data?.pages.some(e=>e.runs.some(e=>Bv.has(e.status)))?3e3:!1}),M=j.isError&&!j.isFetchNextPageError,N=j.data?.pages.at(-1),P=M?[]:[...new Map((j.data?.pages.flatMap(e=>e.runs)??[]).map(e=>[e.id,e])).values()],F=N?.access?.canRun??(f||p),I=N?.access?N.access.dailyRunLimit:p?l.viewerDailyRunLimit:null;(0,Z.useEffect)(()=>{!b&&P[0]&&x(P[0].id)},[P,b]);let ee=P.find(e=>e.id===b)??null,L=W({..._a({client:Y,path:{name:e,runId:b??``}}),enabled:!M&&!!b,refetchInterval:ee&&Bv.has(ee.status)?3e3:!1}),R=M||L.isError?null:L.data??null,te=O.data?.locations??[],B=(0,Z.useMemo)(()=>{if(m)return(N?.providers??[]).filter(e=>e.name!==`openrouter`).map(e=>({...e,catalog:e}));let e=k.data?.providerCatalog??[],t=new Map(e.map(e=>[e.name,e])),n=Ms(e),r=new Map((k.data?.providers??[]).filter(e=>e.configured).map(e=>[e.name,e])),i=[...r.values()].filter(e=>!xc(e.name,n)&&!zn(e.name)&&t.get(e.name)?.mode===`api`).map(e=>({...e,catalog:{...t.get(e.name),defaultModel:e.model||t.get(e.name).defaultModel}})),a=e.filter(e=>Ws(e,Ps)&&r.has(e.connection??e.name)).map(e=>({name:e.name,displayName:e.displayName,configured:!0,defaultModel:e.defaultModel,kind:e.kind,catalog:e})),o=t.get(`openrouter`),s=new Map((N?.providers??[]).filter(e=>zn(e.name)).map(e=>[e.name,e]));if(!r.has(`openrouter`)&&s.size===0)return[...i,...a];let c=[...new Set([...O.data?.providers??[],...s.keys()])].filter(zn).flatMap(n=>{let r=an(n);if(!r)return[];let i=t.get(n),a=s.get(n),c=i??(o?{...o,name:n,displayName:Vo(n,[...e,...s.values()]),modelConfigurable:!1,defaultModel:r,knownModels:o.knownModels.filter(e=>e.id===r)}:a);return c?[{name:n,displayName:Vo(n,[...e,...s.values()]),configured:!0,defaultModel:r,catalog:c}]:[]});return[...i,...c,...a]},[N?.providers,m,O.data?.providers,k.data]),V=!(m?j.isPending:k.isPending)&&B.length===0,H=B.find(e=>e.name===g)??null;(0,Z.useEffect)(()=>{if(!g&&O.data&&!O.isError&&!k.isError){let e=B.filter(e=>!(`kind`in e)||e.kind!==`answer-service`),t=O.data.providers.find(t=>e.some(e=>e.name===t));_(t??e[0]?.name??``)}},[g,B,O.data,O.isError,k.isError]);let re=H?.catalog.modelConfigurable??!1,U=m?H?.catalog.defaultModel:(H?O.data?.providerModels[H.name]:``)||H?.catalog.defaultModel,ae=(re?v.trim():``)||U,oe=H?[...new Map([{id:H.catalog.defaultModel,displayName:Me(H.catalog.defaultModel)},...v.trim()?[{id:v.trim(),displayName:Me(v.trim())}]:[],...H.catalog.knownModels].map(e=>[e.id,e])).values()]:[],se=ie({...Fo(),onSuccess:async e=>{w.current=null,D(e=>e+1),C(e.runs),x(e.runs[0]?.id??null),await iy(u),li({title:`Research batch saved`,detail:`${e.runs.length} ${e.runs.length===1?`run is`:`runs are`} in research history. Nothing was added to tracked queries.`,tone:`positive`,dedupeKey:`research:start:${e.runs.map(e=>e.id).join(`:`)}`,dedupeMode:`replace`})},onError:e=>{li({title:`Could not start research`,detail:e instanceof Error?e.message:`Check the provider, model, and location, then try again.`,tone:`negative`})},onSettled:()=>{T.current=!1}});return(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[h?(0,Q.jsx)(Cs,{className:`surface-card min-w-0`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`This public demo shows saved research results. Running research is unavailable.`})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Gv,{projectName:e,canWrite:f,researchAllowed:F&&!M,limitedAccess:m,isEmbed:K(),scopeOptions:n??[],planRevision:r??i?.planRevision??null,initialScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c,locations:te,defaultLocation:O.data?.defaultLocation??null,providerOptions:B,provider:g,onProviderChange:e=>{_(e),y(``)},resolvedModel:ae,visibilityModel:U,configurableModel:re,model:v,onModelChange:y,modelOptions:oe,settingsReady:m?!j.isPending&&!M:!k.isPending&&!k.isError&&!k.isFetching,projectReady:!O.isPending&&!O.isError&&!O.isFetching,isPending:se.isPending,errorMessage:se.isError?`The request could not be confirmed.`:void 0,onSubmit:(t,n)=>{!F||M||K()||T.current||(w.current?.fingerprint!==n&&(w.current={fingerprint:n,key:crypto.randomUUID()}),T.current=!0,se.mutate({client:Y,path:{name:e},body:{...t,idempotencyKey:w.current.key}}))}},`${e}:${E}`),I!==null&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`Up to `,I,` destination runs per project per day.`]}),!m&&k.isError?(0,Q.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-negative`,children:[(0,Q.jsx)(`p`,{children:`Could not load API providers.`}),(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{k.refetch()},children:`Retry providers`})]}):null,O.isError?(0,Q.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-negative`,children:[(0,Q.jsx)(`p`,{children:`Could not load project locations.`}),(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{O.refetch()},children:`Retry locations`})]}):null,!(m?M:k.isError)&&V&&(0,Q.jsx)(`p`,{className:`rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-copy-14 text-caution`,children:m?`No research engines are available. Ask your Canonry team to configure one.`:`Configure an API provider in Settings before starting research. Browser engines are not available for this workflow.`}),S.length>0&&(0,Q.jsxs)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:[`Saved runs: `,S.map((e,t)=>(0,Q.jsxs)(`span`,{children:[t>0?`, `:``,(0,Q.jsxs)(`a`,{href:`#research-run-${e.id}`,className:`text-link underline`,onClick:()=>x(e.id),children:[e.scope?.label??`Whole site`,e.location?`, ${e.location.label}`:`, No location`]})]},e.id))]})]}),(0,Q.jsxs)(Cs,{className:`surface-card min-w-0`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{children:Vv.historyTitle})}),j.isFetching&&(0,Q.jsx)(J,{tone:`neutral`,children:`Loading`})]}),M?(0,Q.jsxs)(`div`,{role:`alert`,className:`mt-4 text-label-14 text-negative`,children:[(0,Q.jsx)(`p`,{children:`Could not load research history.`}),(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{j.refetch()},children:`Retry history`})]}):j.isPending?(0,Q.jsx)(`p`,{role:`status`,children:`Loading research history…`}):P.length===0?(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-muted`,children:Vv.emptyHistory}):(0,Q.jsx)(`div`,{className:`mt-4 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[760px] [overflow-wrap:anywhere]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Run`}),(0,Q.jsx)(`th`,{children:`Model`}),(0,Q.jsx)(`th`,{children:`Destination`}),(0,Q.jsx)(`th`,{children:`Location`}),(0,Q.jsx)(`th`,{children:`Progress`}),(0,Q.jsx)(`th`,{children:`Status`})]})}),(0,Q.jsx)(`tbody`,{children:P.map(e=>(0,Q.jsxs)(`tr`,{className:b===e.id?`bg-bg-elevated/40`:void 0,children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`text-left text-button-14 text-heading hover:text-link focus:outline-none focus:underline`,onClick:()=>x(e.id),children:ey(e.createdAt)})}),(0,Q.jsxs)(`td`,{className:`text-secondary`,children:[(0,Q.jsx)(`span`,{className:`block`,title:e.provider,children:Vo(e.provider,k.data?.providerCatalog)}),(e.requestedModel??e.resolvedModel)!==an(e.provider)&&(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,title:e.requestedModel??e.resolvedModel,children:Me(e.requestedModel??e.resolvedModel)})]}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.scope?.label??`Whole site`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.location?.label??`No location`}),(0,Q.jsxs)(`td`,{className:`tabular-nums text-secondary`,children:[e.completedQueries+e.failedQueries,`/`,e.totalQueries]}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:ny(e.status),children:e.status})})]},e.id))})]})}),j.isFetchNextPageError&&(0,Q.jsx)(`p`,{role:`alert`,className:`mt-3 text-copy-14 text-negative`,children:Vv.historyMoreError}),j.hasNextPage&&(0,Q.jsx)(q,{className:`mt-3`,variant:`outline`,disabled:j.isFetching,onClick:()=>{j.fetchNextPage()},children:j.isFetchingNextPage?Vv.historyLoading:Vv.historyMore})]})]}),!M&&L.isError?(0,Q.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-negative`,children:[(0,Q.jsx)(`p`,{children:`Could not load saved research results.`}),(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{L.refetch()},children:`Retry results`})]}):!M&&(R||b)?(0,Q.jsx)(Xv,{detail:R,engineLabel:R?Vo(R.provider,k.data?.providerCatalog):void 0,isLoading:L.isFetching,onReviewForTracking:h?void 0:t}):null]})}var Uv=`mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-label-14 text-strong placeholder-mono-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50`,Wv=`__none__`;function Gv(e){let{projectName:t,locations:n,provider:r,resolvedModel:i,planRevision:a}=e,o=e.providerOptions.map(e=>({...e,knownModels:e.catalog.knownModels})),s=an(r),c=[r?Vo(r,o):`Choose an engine`,i&&i!==s?Me(i):i?null:`Choose a model`].filter(Boolean).join(` · `),l=z(),[u,d]=(0,Z.useState)(`once`),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(``),[g,v]=(0,Z.useState)(e.initialScope?`${e.initialScope.kind}:${e.initialScope.key}`:`project`),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)([]),[C,w]=(0,Z.useState)(``),[T,E]=(0,Z.useState)({}),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)([]),[M,N]=(0,Z.useState)(null),[P,F]=(0,Z.useState)(!1),[I,ee]=(0,Z.useState)(!1),[L,R]=(0,Z.useState)(``),[te,ne]=(0,Z.useState)(``),B=(0,Z.useRef)(null),V=(0,Z.useRef)(!1),H=(0,Z.useRef)(null),re=e.initialScope?`${e.initialScope.kind}:${e.initialScope.key}`:`project`;(0,Z.useEffect)(()=>{v(re),O(null)},[re]);let U=e.scopeOptions.filter(e=>e.kind===`market`||e.kind===`property`),W=u===`markets`?`market`:`property`,ae=U.filter(e=>e.kind===W),oe=t=>({kind:t.kind,key:t.id,label:t.label,planRevision:a??e.initialScope?.planRevision??0}),se=e=>e===Wv?null:n.find(t=>t.label===e),ce=y??e.defaultLocation??Wv,le=U.find(e=>`${e.kind}:${e.id}`===g),ue=le?oe(le):null,de=u===`once`?[{scope:ue,location:se(ce)}]:u===`locations`?x.map(e=>({scope:null,location:se(e)})):x.map(e=>ae.find(t=>`${t.kind}:${t.id}`===e)).map(e=>e?{scope:oe(e),location:se(T[`${e.kind}:${e.id}`]??Wv)}:null),fe=[...new Map([...k,...e.templates].map(e=>[e.id,e])).values()],pe=D?fe.find(e=>e.id===D.id):null,me=D!==null&&pe?.version!==D.version,he=u===`once`?f:m,ge=he.split(/\r?\n/).filter(e=>e.trim()),_e=cr(ge),ve=[...new Set([...m.matchAll(/\{([^{}]+)\}/g)].map(e=>e[1]))],ye=/[{}]/.test(m.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,``)),be=[];ge.length||be.push(u===`once`?`Enter at least one query.`:`Enter at least one query pattern.`),ge.some(e=>e.length>4e3)&&be.push(`Keep each query under 4,001 characters.`),u!==`once`&&ye&&be.push(`Use the name buttons to insert a supported variable. Remove unknown or incomplete braces.`),de.length||be.push(u===`locations`?`Select at least one location.`:`Select at least one destination.`),de.some(e=>!e||e.location===void 0)&&be.push(`A selected destination or location is no longer available. Update your selection.`);let xe=u===`once`&&g!==`project`||u===`markets`||u===`properties`;xe&&(e.scopePending||e.scopeError||!a||de.some(e=>!e?.scope))&&be.push(`Load the current published markets and properties before running scoped research.`);let Se=(u===`once`?_e.length:ge.length)*de.length;if(de.length>20&&be.push(`Select at most 20 destinations.`),Se>50&&be.push(`${Se} queries selected. Reduce the selection to 50 or fewer.`),me&&be.push(`This saved pattern changed. Select its current version from Saved patterns.`),u!==`once`&&!ye){for(let e of de)if(e&&e.location!==void 0)try{br(D??{pattern:m,variables:ve},e.scope,e.location)}catch{be.push(`Choose a location for {location}, or use only variables available for ${u===`markets`?`markets`:u===`properties`?`properties`:`locations`}.`);break}}let Ce=JSON.stringify({mode:u,source:he,contexts:de,provider:r,resolvedModel:i,template:D,...xe?{planRevision:a}:{}}),we=M!==null&&M.signature!==Ce,Te=u===`once`?_e.map((e,t)=>({id:String(t),query:e,scope:ue,location:de[0]?.location??null})):M?.rows??[],Ee=Yv(Te),De=[];u!==`once`&&M&&(we&&De.push(`Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup.`),Te.some(e=>!e.query.trim()||e.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(e.query))&&De.push(`Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables.`),Te.some(e=>e.location&&!n.some(t=>JSON.stringify(t)===JSON.stringify(e.location)))&&De.push(`A preview location changed. Regenerate the preview.`),Ee.some(e=>cr(e.queries).length!==e.queries.length)&&De.push(`Remove duplicate queries within each destination and location.`),Ee.length>20&&De.push(`The preview exceeds 20 runs.`));let Oe=e.researchAllowed&&!e.isEmbed&&!e.isPending&&e.settingsReady&&e.projectReady&&!!(r&&i)&&!be.length&&!De.length&&(u===`once`||M!==null),G=()=>({runs:Ee.map(e=>({queries:e.queries,provider:r,model:i,location:e.location,...e.scope?{scope:{kind:e.scope.kind,key:e.scope.key,expectedPlanRevision:e.scope.planRevision}}:{},...e.template?{template:e.template}:{}}))}),ke=()=>{if(F(!0),be.length)return;let e=de.flatMap((e,t)=>ge.map((n,r)=>({id:`${t}:${r}`,scope:e.scope,location:e.location,...D?{template:{templateId:D.id,templateVersion:D.version,bindingLocation:e.location}}:{},query:br({pattern:n,variables:[...new Set([...n.matchAll(/\{([^{}]+)\}/g)].map(e=>e[1]))]},e.scope,e.location).output})));N({signature:Ce,rows:e})},Ae=e=>{d(e),S([]),O(null),w(``),F(!1)},je=e=>{if(ne(``),u===`once`)try{p(br(e,ue,se(ce)).output)}catch{ne(`Select a matching market, property, or location before using this pattern.`);return}else h(e.pattern);O(e)},Ne=e=>{let t=H.current,n=t?.selectionStart??m.length,r=t?.selectionEnd??n;h(`${m.slice(0,n)}{${e}}${m.slice(r)}`),O(null),requestAnimationFrame(()=>{t?.focus(),t?.setSelectionRange(n+e.length+2,n+e.length+2)})},Pe=ie({...fo(),onSuccess:async e=>{let n={id:e.id,version:e.updatedAt,label:e.name,pattern:e.pattern,variables:e.variables};A(t=>[...t.filter(t=>t.id!==e.id),n]),O(n),ee(!1),R(``),ne(``),B.current=null,await l.invalidateQueries({queryKey:Xa({client:Y,path:{name:t}})}),li({title:`Pattern saved`,detail:`Available in Saved patterns. Tracking was not changed.`,tone:`positive`})},onError:()=>ne(`Could not save the pattern. Your text is preserved. Retry to save the same pattern.`),onSettled:()=>{V.current=!1}}),Fe=()=>{if(!e.canWrite||e.isEmbed||V.current)return;let n=u===`once`?f:m,r=u===`once`?[]:ve;if(!L.trim()||!n.trim()||n.length>4e3||u!==`once`&&ye){ne(`Enter a name and a valid pattern of 1 to 4,000 characters.`);return}let i={name:L.trim(),pattern:n,variables:r},a=JSON.stringify(i);B.current?.fingerprint!==a&&(B.current={fingerprint:a,id:crypto.randomUUID()}),V.current=!0,Pe.mutate({client:Y,path:{name:t,templateId:B.current.id},body:i})},Ie=[...new Set([...P||he.trim()?be:[],...De])],Le=fe.filter(e=>{let t=u===`once`?en(ue,se(ce)):en(u===`markets`?{kind:`market`,label:`Market`}:u===`properties`?{kind:`property`,label:`Property`}:null,{label:`Location`});return e.variables.every(e=>t[e]!==void 0)});return(0,Q.jsxs)(Cs,{className:`surface-card min-w-0`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{children:`Test queries`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-prose text-copy-14 text-secondary`,children:`See how an answer engine responds. Results are saved separately from tracked queries and AI Visibility metrics.`})]})}),(0,Q.jsxs)(`fieldset`,{"aria-label":`Research setup`,className:`mt-5 min-w-0 space-y-5`,disabled:e.isPending||Pe.isPending,children:[(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Run mode`}),(0,Q.jsxs)(`select`,{className:Uv,value:u,disabled:e.isPending,onChange:e=>Ae(e.target.value),children:[(0,Q.jsx)(`option`,{value:`once`,children:`Run once`}),(0,Q.jsx)(`option`,{value:`markets`,disabled:!U.some(e=>e.kind===`market`),children:`Repeat across markets`}),(0,Q.jsx)(`option`,{value:`properties`,disabled:!U.some(e=>e.kind===`property`),children:`Repeat across properties`}),(0,Q.jsx)(`option`,{value:`locations`,disabled:!n.length,children:`Repeat across locations`})]})]}),u===`once`&&(0,Q.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(U.length>0||g!==`project`)&&(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Save results under`}),(0,Q.jsxs)(`select`,{className:Uv,value:g,onChange:e=>{v(e.target.value),O(null)},children:[(0,Q.jsx)(`option`,{value:`project`,children:`Whole site`}),g!==`project`&&!le&&(0,Q.jsx)(`option`,{value:g,disabled:!0,children:`Selected destination unavailable`}),U.map(e=>(0,Q.jsxs)(`option`,{value:`${e.kind}:${e.id}`,children:[e.label,` (`,e.kind,`)`]},`${e.kind}:${e.id}`))]})]}),(0,Q.jsx)(Kv,{label:`Answer engine location`,value:ce,locations:n,onChange:e=>{b(e),O(null)}})]}),u!==`once`&&(0,Q.jsxs)(`fieldset`,{className:`space-y-3`,children:[(0,Q.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:u===`locations`?`Select locations`:`Select ${u}`}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Choose each destination explicitly. Each selected destination gets its own saved research run.`}),(0,Q.jsx)(`input`,{type:`search`,"aria-label":`Search destinations`,className:Uv,placeholder:`Search ${u}`,value:C,onChange:e=>w(e.target.value)}),(0,Q.jsx)(`div`,{className:`max-h-72 space-y-2 overflow-y-auto pr-1`,children:(u===`locations`?n.map(e=>({key:e.label,label:e.label})):ae.map(e=>({key:`${e.kind}:${e.id}`,label:e.label}))).filter(e=>e.label.toLocaleLowerCase().includes(C.toLocaleLowerCase())).map(e=>{let t=x.includes(e.key);return(0,Q.jsxs)(`div`,{className:`grid items-center gap-2 border-b border-default pb-2 sm:grid-cols-[minmax(0,1fr)_16rem]`,children:[(0,Q.jsxs)(`label`,{className:`flex min-h-11 items-center gap-3 text-label-14 text-heading`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,onChange:()=>S(n=>t?n.filter(t=>t!==e.key):[...n,e.key])}),e.label]}),t&&u!==`locations`&&(0,Q.jsx)(Kv,{label:`Answer engine location for ${e.label}`,value:T[e.key]??Wv,locations:n,onChange:t=>E(n=>({...n,[e.key]:t}))})]},e.key)})}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[x.length,` selected. A market or property name changes query text, not the answer engine's location.`]})]}),e.scopeError&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-caution`,children:[`Markets and properties could not load. Whole-site and location research remain available. `,(0,Q.jsx)(q,{variant:`outline`,onClick:e.onRetryScope,children:`Retry destinations`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block`,htmlFor:`research-query-editor`,children:(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:u===`once`?`Queries`:`Query pattern`})}),(0,Q.jsx)(`p`,{id:`research-query-guidance`,className:`mt-1 text-copy-14 text-secondary`,children:u===`once`?`Enter one query per line. The answer engine receives exactly this text.`:`Use {${u===`markets`?`market`:u===`properties`?`property`:`location`}} where each name belongs. Preview the resolved queries before running.`}),(0,Q.jsx)(`textarea`,{id:`research-query-editor`,ref:H,className:`${Uv} min-h-32`,"aria-describedby":`research-query-guidance research-query-count`,value:he,placeholder:u===`once`?Vv.queryPlaceholder:u===`markets`?`Best apartments in {market}`:u===`properties`?`What amenities does {property} offer?`:`Best apartments in {location}`,onChange:e=>{u===`once`?p(e.target.value):(h(e.target.value),O(null))}}),u!==`once`&&(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:[(0,Q.jsxs)(q,{size:`sm`,variant:`outline`,onClick:()=>Ne(u===`markets`?`market`:u===`properties`?`property`:`location`),children:[`Insert `,u===`markets`?`market`:u===`properties`?`property`:`location`,` name`]}),(0,Q.jsx)(`span`,{className:`self-center text-label-14 text-secondary`,children:`One pattern per line.`})]}),(0,Q.jsxs)(`p`,{id:`research-query-count`,className:`mt-2 text-copy-14 text-secondary`,children:[Se,` / `,50,` queries`,u===`once`?``:` across ${de.length} destinations`]})]}),u!==`once`&&(0,Q.jsxs)(`details`,{className:`border-t border-default pt-3`,children:[(0,Q.jsxs)(`summary`,{className:`cursor-pointer text-label-14-strong text-heading focus-visible:outline focus-visible:outline-2`,children:[`Saved patterns `,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`(optional)`})]}),(0,Q.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries.`}),Le.length?(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Le.map(e=>(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>je(e),children:e.label},e.id))}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No saved patterns for this selection.`}),D&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`Using: `,D.label]}),e.canWrite&&!e.isEmbed&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>ee(!I),children:I?`Cancel save`:`Save as a pattern`}),I&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[(0,Q.jsxs)(`label`,{className:`min-w-48 flex-1 text-label-14 text-heading`,children:[`Pattern name`,(0,Q.jsx)(`input`,{className:Uv,value:L,maxLength:120,onChange:e=>R(e.target.value)})]}),(0,Q.jsx)(q,{size:`sm`,disabled:Pe.isPending||!L.trim()||!he.trim(),onClick:Fe,children:Pe.isPending?`Saving…`:`Save pattern`})]})]}),te&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:te})]})]}),(0,Q.jsxs)(`div`,{className:`grid gap-4${s?``:` sm:grid-cols-2`}`,children:[(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,children:[`Answer engine`,(0,Q.jsxs)(`select`,{className:Uv,value:r,onChange:t=>e.onProviderChange(t.target.value),children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Choose an answer engine`}),e.providerOptions.map(e=>(0,Q.jsx)(`option`,{value:e.name,children:Vo(e.name,o)},e.name))]})]}),!s&&(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,children:[`Model`,e.limitedAccess?(0,Q.jsxs)(`select`,{className:Uv,value:e.model,disabled:!r||!e.configurableModel,onChange:t=>e.onModelChange(t.target.value),children:[(0,Q.jsxs)(`option`,{value:``,children:[`Use AI Visibility model`,e.visibilityModel?` · ${Me(e.visibilityModel)}`:``]}),e.modelOptions.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.displayName},e.id))]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{"aria-label":`Model`,className:Uv,list:`research-known-models`,placeholder:i??`Choose an answer engine`,value:e.model,disabled:!r||!e.configurableModel,onChange:t=>e.onModelChange(t.target.value)}),(0,Q.jsx)(`datalist`,{id:`research-known-models`,children:e.modelOptions.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.displayName},e.id))})]})]})]}),Ie.length>0&&(0,Q.jsx)(Jv,{errors:Ie}),u!==`once`&&(0,Q.jsxs)(`div`,{className:`space-y-4 border-t border-default pt-4`,children:[(0,Q.jsxs)(q,{variant:`outline`,size:`sm`,disabled:e.isPending||!e.projectReady,onClick:ke,children:[(0,Q.jsx)(_,{size:14}),M?Vv.refreshPreview:`Preview queries`]}),M&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:`Queries to run`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[Te.length,` query executions in `,Ee.length,` saved runs · `,c,`. Edit any query or location below.`]}),(0,Q.jsx)(qv,{rows:Te,locations:n,onChange:(e,t)=>N(n=>n&&{...n,rows:n.rows.map(n=>n.id===e?{...n,...t}:n)})})]})]}),e.errorMessage&&(0,Q.jsxs)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:[e.errorMessage,` Your entries are preserved. Retry unchanged entries to avoid duplicate work.`]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t border-default pt-4`,children:[!e.isEmbed&&(0,Q.jsxs)(q,{size:`sm`,disabled:!Oe,onClick:()=>{if(Oe){let n=G();e.onSubmit(n,JSON.stringify({projectName:t,...n}))}},children:[(0,Q.jsx)(j,{size:14}),e.isPending?`Starting…`:Vv.runAction]}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[u===`once`?`${_e.length} queries`:`${Te.length} reviewed queries`,` · `,c]})]})]})]})}function Kv({label:e,value:t,locations:n,onChange:r}){return(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e}),(0,Q.jsxs)(`select`,{className:Uv,value:t,onChange:e=>r(e.target.value),children:[(0,Q.jsx)(`option`,{value:Wv,children:`No location context`}),n.map(e=>(0,Q.jsx)(`option`,{value:e.label,children:e.label},e.label))]})]})}function qv({rows:e,locations:t,onChange:n}){return(0,Q.jsx)(`ol`,{className:`divide-y divide-default`,children:e.map((e,r)=>(0,Q.jsxs)(`li`,{className:`grid gap-3 py-4 md:grid-cols-[10rem_minmax(0,1fr)_15rem]`,children:[(0,Q.jsxs)(`div`,{className:`text-label-14`,children:[(0,Q.jsxs)(`span`,{className:`block text-secondary`,children:[`Query `,r+1]}),(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e.scope?.label??e.location?.label??`Whole site`}),e.scope&&(0,Q.jsx)(`span`,{className:`block text-secondary`,children:e.scope.kind})]}),(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,children:[`Query`,(0,Q.jsx)(`textarea`,{className:`${Uv} min-h-20`,"aria-label":`Query ${r+1} for ${e.scope?.label??e.location?.label??`Whole site`}`,value:e.query,onChange:t=>n(e.id,{query:t.target.value})})]}),(0,Q.jsx)(Kv,{label:`Location for query ${r+1}`,value:e.location?.label??Wv,locations:t,onChange:r=>n(e.id,{location:t.find(e=>e.label===r)??null})})]},e.id))})}function Jv({errors:e}){return(0,Q.jsx)(`div`,{role:`alert`,className:`text-label-14 text-negative`,children:(0,Q.jsx)(`ul`,{className:`list-disc space-y-1 pl-5`,children:e.map(e=>(0,Q.jsx)(`li`,{children:e},e))})})}function Yv(e){let t=new Map;for(let n of e){let e=JSON.stringify({scope:n.scope,location:n.location,template:n.template}),r=t.get(e)??{scope:n.scope,location:n.location,queries:[],...n.template?{template:n.template}:{}};r.queries.push(n.query),t.set(e,r)}return[...t.values()]}function Xv({detail:e,engineLabel:t,isLoading:n,onReviewForTracking:r}){let[i,a]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{a(e?.queries[0]?.id??null)},[e?.id]);let o=e?.queries.find(e=>e.id===i)??e?.queries[0]??null;return(0,Q.jsxs)(Cs,{id:e?`research-run-${e.id}`:void 0,className:`surface-card min-w-0`,role:`region`,"aria-label":Vv.resultsTitle,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{children:e?`Research run ${ty(e.id)}`:Vv.resultsEmpty})}),e&&(0,Q.jsx)(J,{tone:ny(e.status),children:e.status})]}),e&&(0,Q.jsxs)(`div`,{className:`mt-3 space-y-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`dl`,{className:`flex flex-wrap gap-x-6 gap-y-2 [overflow-wrap:anywhere]`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-14-strong`,children:`Answer engine`}),(0,Q.jsx)(`dd`,{title:e.provider,children:t??Vo(e.provider)})]}),(e.requestedModel??e.resolvedModel)!==an(e.provider)&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-14-strong`,children:`Requested model`}),(0,Q.jsx)(`dd`,{title:e.requestedModel??e.resolvedModel,children:Me(e.requestedModel??e.resolvedModel)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-14-strong`,children:`Location`}),(0,Q.jsx)(`dd`,{children:e.location?.label??`No location`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-14-strong`,children:`Destination`}),(0,Q.jsx)(`dd`,{children:e.scope?.label??`Whole site`})]})]}),e.template&&(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2`,children:Vv.templateProvenance}),(0,Q.jsxs)(`dl`,{className:`mt-2 space-y-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-14-strong`,children:`Saved pattern`}),(0,Q.jsx)(`dd`,{className:`whitespace-pre-wrap`,children:e.template.template})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-14-strong`,children:`Names used`}),(0,Q.jsx)(`dd`,{children:Object.entries(e.template.bindings).map(([e,t])=>`${e}: ${t}`).join(` · `)||`No variables`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-14-strong`,children:`Original resolved text`}),(0,Q.jsx)(`dd`,{className:`whitespace-pre-wrap`,children:e.template.output})]})]}),(0,Q.jsx)(`p`,{className:`mt-2`,children:`The queries below are the final text sent to the answer engine, including any edits.`}),(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13-mono`,children:[e.template.templateId,` · `,e.template.templateVersion]})]}),(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2`,children:Vv.methodologySummary}),(0,Q.jsx)(`p`,{className:`mt-2 max-w-prose text-copy-14`,children:Vv.methodology})]})]}),e?(0,Q.jsxs)(`div`,{className:`mt-4 space-y-4`,children:[(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[760px] [overflow-wrap:anywhere]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Query`}),(0,Q.jsx)(`th`,{children:`Class`}),(0,Q.jsx)(`th`,{children:`Status`}),(0,Q.jsx)(`th`,{children:`Brand-name match`}),(0,Q.jsx)(`th`,{children:`Project domain cited`})]})}),(0,Q.jsx)(`tbody`,{children:e.queries.map(e=>(0,Q.jsxs)(`tr`,{className:o?.id===e.id?`bg-bg-elevated/40`:void 0,children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`text-left text-button-14 text-heading hover:text-link focus:outline-none focus:underline`,onClick:()=>a(e.id),children:e.query})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:e.queryClass===`branded`?`positive`:e.queryClass===`non-brand`?`neutral`:`caution`,children:e.queryClass===`branded`?Vv.brandedQuery:e.queryClass===`non-brand`?Vv.discoveryQuery:Vv.unclassifiedQuery})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:ry(e.status),children:e.status})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:e.answerMentioned===!0?`positive`:e.answerMentioned===!1?`neutral`:e.status===gn.failed?`negative`:`caution`,children:e.answerMentioned===null?e.status===gn.failed?`Unavailable`:`Pending`:e.answerMentioned?`Matched`:`No match`})}),(0,Q.jsx)(`td`,{children:e.citationMeasured===!1&&e.status===gn.completed?(0,Q.jsx)(J,{tone:`neutral`,children:`Not measured`}):(0,Q.jsx)(J,{tone:e.citationState===`cited`?`positive`:e.citationState===`not-cited`?`neutral`:e.status===gn.failed?`negative`:`caution`,children:e.citationState===null?e.status===gn.failed?`Unavailable`:`Pending`:e.citationState===`cited`?`Cited`:`Not cited`})})]},e.id))})]})}),(0,Q.jsx)(Zv,{query:o,scope:e.scope??null,isLoading:n,onReviewForTracking:r})]}):(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-muted`,children:`Select a saved run to inspect each answer and its source links.`})]})}function Zv({query:e,isLoading:t,scope:n,onReviewForTracking:r}){return e?(0,Q.jsxs)(`div`,{className:`min-w-0 space-y-4 border-t border-default pt-4 [overflow-wrap:anywhere]`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Selected query`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14-strong text-heading`,children:e.query})]}),!K()&&r&&(0,Q.jsxs)(`div`,{className:`material-base px-3 py-3`,children:[(0,Q.jsx)(fs,{type:`button`,size:`sm`,onClick:()=>r({researchRunQueryId:e.id,scope:n}),children:`Review for tracking`}),(0,Q.jsx)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:`Only this saved query text enters tracking review. Its answer remains research evidence.`})]}),e.error&&(0,Q.jsx)(`div`,{className:`rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-label-14 text-negative`,children:e.error}),e.error&&e.evidence&&e.answerText?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Partial answer, not measured`}),(0,Q.jsx)(`div`,{className:`mt-1`,children:(0,Q.jsx)(dc,{headingLevel:4,copyable:!0,children:e.answerText})})]}):e.error?null:e.answerText?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Answer`}),(0,Q.jsx)(`div`,{className:`mt-1`,children:(0,Q.jsx)(dc,{headingLevel:4,copyable:!0,children:e.answerText})})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:e.status===gn.failed?`This query did not return an answer.`:e.status===gn[`waiting-upstream`]?`The service is still working on this query as an upstream job${e.upstreamJobId?` (${e.upstreamJobId})`:``}. It is followed by that job and never sent again.`:`The answer will appear here when this query finishes.`}),e.namedCompetitors.length>0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Named in answer`}),(0,Q.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:e.namedCompetitors.map(e=>(0,Q.jsx)(`span`,{className:`mention-chip mention-chip--competitor`,children:e},e))})]}),e.citedCompetitorDomains.length>0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Cited competitor domains`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:`Cited as a source, not merely named in the answer.`}),(0,Q.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:e.citedCompetitorDomains.map(e=>(0,Q.jsx)(`span`,{className:`mention-chip mention-chip--competitor`,children:e.replace(/^www\./,``)},e))})]}),e.groundingSources.length>0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Source links`}),(0,Q.jsx)(`ul`,{className:`mt-2 space-y-3`,children:e.groundingSources.map((e,t)=>(0,Q.jsx)(`li`,{className:`min-w-0`,children:(0,Q.jsx)(Cc,{url:e.uri,title:e.title})},`${e.uri}-${t}`))})]}),e.evidence&&(0,Q.jsx)($v,{evidence:e.evidence})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:t?`Loading saved answers…`:`Select a query to inspect its answer.`})}var Qv={"explicit-citation":`Cited in the answer`,"answer-support":`Used for the answer`,"search-result":`Search result`,"page-read":`Page read`};function $v({evidence:e}){let t=e.sources.filter(e=>e.relationship===`search-result`||e.relationship===`page-read`);return(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Answer service evidence`}),(0,Q.jsxs)(`dl`,{className:`definition-list`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Status`}),(0,Q.jsx)(`dd`,{children:nt(e.completion.status)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Profile`}),(0,Q.jsx)(`dd`,{className:`text-label-12-mono`,children:e.identity.route})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Model`}),(0,Q.jsx)(`dd`,{children:e.identity.disclosedModel?`${e.identity.disclosedModel}${e.identity.disclosedModelKind===`service-tier`?` (service tier)`:``}`:`Not disclosed`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Cost`}),(0,Q.jsx)(`dd`,{children:ot(e.usage.cost)})]}),!e.citationMeasurable&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:`Citations`}),(0,Q.jsx)(`dd`,{children:`Not measured: this service does not tie its sources to the answer.`})]})]}),t.length>0&&(0,Q.jsx)(`ul`,{className:`space-y-3`,children:t.map((e,t)=>(0,Q.jsxs)(`li`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-copy-13 text-muted`,children:Qv[e.relationship]}),(0,Q.jsx)(Cc,{url:e.url,title:e.title??e.url})]},`${e.url}-${t}`))})]})}function ey(e){let t=new Date(e);return Number.isNaN(t.valueOf())?e:new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`}).format(t)}function ty(e){return e.length>8?e.slice(0,8):e}function ny(e){return e===qt.completed?`positive`:e===qt.partial||e===qt[`waiting-upstream`]?`caution`:e===qt.failed?`negative`:`neutral`}function ry(e){return e===gn.completed?`positive`:e===gn.failed?`negative`:e===gn[`waiting-upstream`]?`caution`:`neutral`}async function iy(e){await ui(e,`researchRuns`)}var ay=new Set([`queued`,`seeding`,`probing`]);function oy({projectName:e,queryWorkspace:t,onQueryWorkspaceChange:n,researchMode:r,onResearchModeChange:i,selection:a={measurementScope:`project`,queryClass:`all`},onSelectionChange:o,trackingQueryId:s,onTrackingQueryIdChange:c,publishGuard:l}){let{account:u}=si(),[d,f]=(0,Z.useState)(`tracked`),[p,m]=(0,Z.useState)(`find`),[h,g]=(0,Z.useState)(null),_=u?.role===`viewer`?vn():null,v=dl(u?.role,_),y=fl(t??d,v),b=r??p,x=(0,Z.useId)(),S=e=>{t===void 0&&f(e),n?.(e)};return(0,Q.jsxs)(`section`,{className:`page-section-divider`,"aria-labelledby":`queries-heading`,children:[(0,Q.jsx)(`h2`,{id:`queries-heading`,className:`sr-only`,children:`Queries`}),(0,Q.jsx)(vl,{id:x,label:`Query workspace`,value:y,onChange:S,className:`flex border-b border-default`,tabClassName:sy,activeTabClassName:cy,inactiveTabClassName:ly,options:v?[[`tracked`,`Tracked`],[`research`,`Research`]]:[[`tracked`,`Tracked`]]}),(0,Q.jsx)(`div`,{id:`${x}-panel`,role:`tabpanel`,"aria-labelledby":`${x}-${y}`,tabIndex:0,className:`mt-4`,children:y===`tracked`?(0,Q.jsx)(Ky,{projectName:e,selection:a,onSelectionChange:o,trackingQueryId:s,onTrackingQueryIdChange:c,pendingTrackingSource:h,onPendingTrackingSourceHandled:()=>g(null),publishGuard:l}):(0,Q.jsx)(uy,{projectName:e,selection:a,mode:b,onModeChange:e=>{r===void 0&&m(e),i?.(e)},onReviewSavedSource:(e,t)=>{let n={...a,measurementScope:t?.kind??`project`,measurementScopeKey:t?.key};g({...e,trackingSelection:n}),t!==void 0&&o?.({measurementScope:n.measurementScope,measurementScopeKey:n.measurementScopeKey}),S(`tracked`)},onSelectionChange:o,viewerResearchConfig:_})})]})}var sy=`-mb-px border-b-2 px-3 py-2 text-button-14 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500 focus-visible:ring-inset`,cy=`border-mono-400 text-heading`,ly=`border-transparent text-muted hover:border-strong hover:text-strong`;function uy({projectName:e,selection:t,mode:n,onModeChange:r,onReviewSavedSource:i,viewerResearchConfig:a}){let{canWrite:o}=si(),s=(0,Z.useId)(),c=!o||n===`test`,l=W({...Io({client:Y,path:{name:e}}),enabled:c,staleTime:6e4}),u=W({...bi({client:Y,path:{name:e}}),enabled:c,staleTime:6e4}),d=(0,Z.useMemo)(()=>{let e=l.data;if(!e)return[{id:`project`,label:`Whole site`,kind:`project`,targetCount:0}];let t=new Map(e.targets.map(e=>[e.stableKey,[]]));for(let n of e.groups)for(let e of n.targetKeys)t.get(e)?.push(n.stableKey);let n=new Map(e.markets.map(e=>[e.stableKey,new Set]));for(let r of e.markets)for(let e of r.usageEdges)for(let i of t.get(e.targetKey)??[])n.get(r.stableKey)?.add(i);return[{id:`project`,label:`Whole site`,kind:`project`,targetCount:e.targets.length},...e.groups.map(e=>({id:e.stableKey,label:e.label,kind:`group`,targetCount:e.targetKeys.length,...e.parentGroupKey?{parentGroupIds:[e.parentGroupKey]}:{}})),...e.markets.map(e=>{let t=[...n.get(e.stableKey)??[]];return{id:e.stableKey,label:e.label,kind:`market`,targetCount:0,...t.length?{parentGroupIds:t}:{}}}),...e.targets.map(e=>({id:e.stableKey,label:e.label,kind:`property`,targetCount:1,...t.get(e.stableKey)?.length?{parentGroupIds:t.get(e.stableKey)}:{}}))]},[l.data]),f=(0,Z.useMemo)(()=>(u.data?.templates??[]).map(e=>({id:e.id,version:e.updatedAt,label:e.name,pattern:e.pattern,variables:e.variables})),[u.data]),p={projectName:e,scopeOptions:d,planRevision:l.data?.active?.revision??null,selectedScope:(()=>{let e=d.find(e=>e.kind===t.measurementScope&&e.id===t.measurementScopeKey),n=l.data?.active?.revision;return e&&n&&(e.kind===`market`||e.kind===`property`)?{kind:e.kind,key:e.id,label:e.label,planRevision:n,expectedPlanRevision:n}:(t.measurementScope===`market`||t.measurementScope===`property`)&&t.measurementScopeKey?{kind:t.measurementScope,key:t.measurementScopeKey,label:t.measurementScopeKey,planRevision:n??0,expectedPlanRevision:n??0}:null})(),scopePending:l.isPending||l.isFetching,scopeError:l.isError,onRetryScope:()=>{l.refetch()},templates:f};return o?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(vl,{id:s,label:`Research workspace`,value:n,onChange:r,className:`flex border-b border-default`,tabClassName:sy,activeTabClassName:cy,inactiveTabClassName:ly,options:[[`find`,`Find queries`],[`test`,`Test queries`]]}),(0,Q.jsx)(`div`,{id:`${s}-panel`,role:`tabpanel`,"aria-labelledby":`${s}-${n}`,tabIndex:0,className:`mt-4`,children:n===`find`?(0,Q.jsx)(qy,{projectName:e,onReviewDiscoveryProbe:e=>i({source:`discovery`,discoveryProbeId:e})}):(0,Q.jsx)(Hv,{...p,onReviewForTracking:({researchRunQueryId:e,scope:t})=>i({source:`research`,researchRunQueryId:e},t??null)})})]}):(0,Q.jsx)(Hv,{...p,viewerResearchConfig:a})}function dy({workspace:e,selection:t,onSelectionChange:n,trackingQueryId:r,onTrackingQueryIdChange:i,pendingTrackingSource:a,onPendingTrackingSourceHandled:s,templates:c,preview:l,isPreviewing:u,isCommitting:d,onPreview:p,onCommit:m,publishGuard:h}){let[g,_]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(()=>fy(t)),[x,S]=(0,Z.useState)(null),C=(0,Z.useRef)(null),w=(0,Z.useRef)(null),T=(0,Z.useRef)(!1),E=(0,Z.useRef)(null),D=pl(e,t),O=(0,Z.useMemo)(()=>Sy(e.tracked,t,e.mode),[t,e.mode,e.tracked]),k=O.some(e=>e.provenance!==null),A=$l({rows:O,getSearchText:e=>`${e.queryText} ${e.provenance?.source??``} ${e.assignments.map(e=>e.queryClass??`unknown`).join(` `)}`});(0,Z.useEffect)(()=>{if(D)return;if(!r){E.current=null;return}let n=`${r}:${wy(t)}`;if(E.current===n)return;let i=e.tracked.find(e=>e.queryId===r);i&&(E.current=n,_({kind:`edit`,row:i,audience:e.mode===`advanced`?yy(t):void 0,scopeLabel:by(t,e)}),b(py(i,t)),S(null))},[t,r,D,e]),(0,Z.useEffect)(()=>{if(D||!a)return;let e=fy(a.trackingSelection??t);_({kind:`add`}),b(a.source===`research`?{...e,source:`research`,researchRunQueryId:a.researchRunQueryId}:{...e,source:`discovery`,discoveryProbeId:a.discoveryProbeId}),S(null),s()},[s,a,t,D]),(0,Z.useEffect)(()=>{D&&(_(null),S(null),r!==void 0&&i?.(void 0))},[i,r,D]),(0,Z.useEffect)(()=>{if(!g||g.kind===`remove`)return;let e=C.current;e&&(e.scrollIntoView?.({block:`start`}),e.focus({preventScroll:!0}))},[g]),(0,Z.useEffect)(()=>{T.current&&g===null&&!d&&(w.current?.querySelector(`button`)?.focus(),T.current=!1)},[g,d]);function j(e=`manual`){_({kind:`add`}),b({...fy(t),source:e}),S(null),i?.(void 0)}function M(n){E.current=`${n.queryId}:${wy(t)}`,_({kind:`edit`,row:n,audience:e.mode===`advanced`?yy(t):void 0,scopeLabel:by(t,e)}),b(py(n,t)),S(null),i?.(n.queryId)}function N(n){E.current=`${n.queryId}:${wy(t)}`,_({kind:`remove`,row:n,audience:e.mode===`advanced`?yy(t):void 0,scopeLabel:by(t,e)}),S(null),i?.(n.queryId)}function P(){T.current=!0,_(null),b(fy(t)),S(null),i?.(void 0)}let F=g?my(g,y,e):null,I=g!==null&&g.kind===`add`&&e.mode===`advanced`&&!_y(y),ee=F!==null&&(!I||y.contexts.length>0)&&!u&&!d;return D?(0,Q.jsx)(`div`,{className:`query-tracking-workspace space-y-4`,children:(0,Q.jsxs)(`section`,{"aria-label":`Tracked queries`,className:`py-4 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`p`,{children:[`This saved `,t.measurementScope,` filter is unavailable in the current measurement.`]}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>n?.({measurementScope:`project`,measurementScopeKey:void 0}),children:`Show whole site`})]})}):(0,Q.jsxs)(`div`,{className:`query-tracking-workspace space-y-4`,children:[(0,Q.jsxs)(`section`,{"aria-label":`Tracked queries`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e.mode===`advanced`?(0,Q.jsx)(Cy,{selection:t,onSelectionChange:n}):null,(0,Q.jsx)(eu,{value:A.query,onChange:A.setQuery,label:`Filter tracked queries`,placeholder:`Search tracked queries`,className:`min-w-64 flex-[2]`}),!K()&&(0,Q.jsx)(`div`,{ref:w,children:(0,Q.jsxs)(fs,{type:`button`,size:`sm`,disabled:d,onClick:()=>j(),children:[(0,Q.jsx)(o,{"aria-hidden":`true`,size:14}),`Add query`]})})]}),(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-secondary`,children:[A.totalRows.toLocaleString(`en-US`),` `,A.totalRows===1?`query`:`queries`]}),t.measurementScope===`group`?(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:`Queries belong to properties, so a shared query can also cover other groups.`}):null,e.mode===`advanced`&&!e.active?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-caution`,children:`Publish your measurement setup before running a sweep.`}):null,A.rows.length===0?(0,Q.jsx)(`p`,{className:`mt-5 text-copy-14 text-secondary`,children:A.hasQuery?`No tracked queries match that search.`:`No tracked queries in this scope yet.`}):(0,Q.jsx)(`div`,{className:`mt-5 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`evidence-table measurement-responsive-table table-auto ${e.mode===`advanced`?`tracking-table-advanced min-w-[760px]`:`min-w-[520px]`}`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Query`}),e.mode===`advanced`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`th`,{children:`Scope`}),(0,Q.jsx)(`th`,{className:`tracking-fit-cell`,children:`Class`})]}):null,k?(0,Q.jsx)(`th`,{className:`tracking-fit-cell`,children:`Source`}):null,(0,Q.jsx)(`th`,{className:`tracking-fit-cell`,children:`Measurement`}),(0,Q.jsx)(`th`,{className:`measurement-table-actions`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,Q.jsx)(`tbody`,{children:A.rows.map(n=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tracking-query-cell break-words text-label-14-strong text-heading`,children:n.queryText}),e.mode===`advanced`?(0,Q.jsx)(`td`,{className:`tracking-scope-cell text-secondary`,children:(0,Q.jsx)(Dy,{row:n,workspace:e,selection:t})}):null,e.mode===`advanced`?(0,Q.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,Q.jsx)(ky,{row:n})}):null,k?(0,Q.jsx)(`td`,{className:`whitespace-nowrap text-secondary`,children:Ty(n)}):null,(0,Q.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,Q.jsx)(Ay,{row:n,outsidePlan:e.mode===`advanced`&&n.assignments.length===0})}),(0,Q.jsx)(`td`,{className:`measurement-table-actions whitespace-nowrap text-right`,children:!K()&&(0,Q.jsxs)(`div`,{className:`tracking-row-actions flex min-w-max justify-end gap-2`,children:[(0,Q.jsxs)(fs,{type:`button`,variant:`ghost`,size:`sm`,disabled:d,"aria-label":`Edit ${n.queryText}`,onClick:()=>M(n),children:[(0,Q.jsx)(f,{"aria-hidden":`true`,size:13}),` Edit`]}),(0,Q.jsxs)(fs,{type:`button`,variant:`ghost`,size:`sm`,disabled:d,"aria-label":`Remove ${n.queryText}`,onClick:()=>N(n),children:[(0,Q.jsx)(v,{"aria-hidden":`true`,size:13}),` Remove`]})]})})]},n.queryId))})]})}),(0,Q.jsx)(tu,{page:A.page,pageSize:A.pageSize,visibleRows:A.rows.length,totalRows:A.totalRows,itemLabel:`queries`,onPageChange:A.setPage})]}),g&&!K()&&(0,Q.jsx)(`fieldset`,{disabled:d,"aria-busy":d,className:`m-0 min-w-0 border-0 p-0`,children:(0,Q.jsx)(jy,{workspace:e,templates:c,action:g,draft:y,onDraftChange:e=>{b(e),S(null)},onClose:P,canReview:ee,isPreviewing:u,editorHeadingRef:C,onReview:()=>{F&&(S(F),p(F))}})}),l&&x&&g&&(0,Q.jsx)(Vy,{preview:l,workspace:e,isCommitting:d,sweepActive:h?.sweepActive??!1,onConfirm:ci(async()=>{await m({...x,expectedWorkspaceVersion:l.workspaceVersion,previewToken:l.previewToken,reviewedAt:l.reviewedAt})&&P()})})]})}function fy(e){return{source:`manual`,text:``,templateId:``,templateVersion:``,template:``,researchRunQueryId:``,discoveryProbeId:``,wholeSite:!1,targetKeys:e.measurementScope===`property`&&e.measurementScopeKey?[e.measurementScopeKey]:[],groupKeys:e.measurementScope===`group`&&e.measurementScopeKey?[e.measurementScopeKey]:[],marketKeys:e.measurementScope===`market`&&e.measurementScopeKey?[e.measurementScopeKey]:[],contexts:[],queryClass:`auto`}}function py(e,t){return{...fy(t),text:e.queryText,queryClass:`keep`}}function my(e,t,n){let r=n.mode===`advanced`;if(e.kind===`remove`)return{additions:[],removals:[{queryId:e.row.queryId,...e.audience?{audience:e.audience}:{}}]};if(e.kind===`edit`)return t.text.trim()?{additions:[],removals:[],edits:[{queryId:e.row.queryId,text:t.text.trim(),...e.audience?{audience:e.audience}:{},...r&&t.queryClass!==`keep`?{queryClass:t.queryClass===`auto`?null:t.queryClass}:{}}]}:null;let i=hy(t);if(!i||vy(t)||r&&!t.wholeSite&&t.targetKeys.length+t.groupKeys.length+t.marketKeys.length===0)return null;let a=r?gy(t,n):void 0;return{additions:[{input:i,...a?{audience:a}:{},...r&&!_y(t)&&t.contexts.length>0?{contexts:t.contexts}:{},...r&&t.queryClass!==`auto`&&t.queryClass!==`keep`?{queryClass:t.queryClass}:{}}],removals:[]}}function hy(e){return e.source===`manual`?e.text.trim()?{source:`manual`,text:e.text.trim()}:null:e.source===`template`?e.templateId&&e.templateVersion&&e.template?{source:`template`,templateId:e.templateId,templateVersion:e.templateVersion,template:e.template}:null:e.source===`research`?e.researchRunQueryId?{source:`research`,researchRunQueryId:e.researchRunQueryId}:null:e.discoveryProbeId?{source:`discovery`,discoveryProbeId:e.discoveryProbeId}:null}function gy(e,t){if(e.wholeSite)return{targetKeys:t.targets.map(e=>e.stableKey)};let n={...e.targetKeys.length>0?{targetKeys:e.targetKeys}:{},...e.groupKeys.length>0?{groupKeys:e.groupKeys}:{},...e.marketKeys.length>0?{marketKeys:e.marketKeys}:{}};return Object.keys(n).length>0?n:void 0}function _y(e){return e.marketKeys.length>0&&e.targetKeys.length===0&&e.groupKeys.length===0}function vy(e){return e.source===`template`&&e.template.includes(`{market}`)&&(e.wholeSite||e.marketKeys.length===0)}function yy(e){if(e.measurementScopeKey){if(e.measurementScope===`property`)return{targetKeys:[e.measurementScopeKey]};if(e.measurementScope===`group`)return{groupKeys:[e.measurementScopeKey]};if(e.measurementScope===`market`)return{marketKeys:[e.measurementScopeKey]}}}function by(e,t){let n=(e.measurementScope===`property`?t.targets:e.measurementScope===`group`?t.groups:e.measurementScope===`market`?t.markets:[]).find(t=>t.stableKey===e.measurementScopeKey)?.label;return n?e.measurementScope===`group`?`${n} · Group`:e.measurementScope===`market`?`${n} · Market`:n:`Whole site`}function xy(e,t){return t.queryClass!==`all`&&(e.queryClass??`unknown`)!==t.queryClass?!1:t.measurementScope===`project`||!t.measurementScopeKey?!0:t.measurementScope===`property`?e.targetKey===t.measurementScopeKey:t.measurementScope===`group`?e.groupKeys.includes(t.measurementScopeKey):e.marketKeys.includes(t.measurementScopeKey)}function Sy(e,t,n){return n===`simple`?[...e]:e.filter(e=>e.assignments.length===0?t.measurementScope===`project`&&(t.queryClass===`all`||t.queryClass===`unknown`):e.assignments.some(e=>xy(e,t)))}function Cy({selection:e,onSelectionChange:t}){return(0,Q.jsxs)(`label`,{className:`min-w-40 flex-1`,children:[(0,Q.jsx)(`span`,{className:`mb-1 block text-label-12-strong text-secondary`,children:`Query type`}),(0,Q.jsxs)(`select`,{"aria-label":`Query type`,className:`h-11 w-full rounded-md border border-default bg-surface px-3 text-label-14 text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500`,value:e.queryClass,onChange:e=>t?.({queryClass:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`all`,children:`All query types`}),(0,Q.jsx)(`option`,{value:`non-brand`,children:`Non-brand`}),(0,Q.jsx)(`option`,{value:`branded`,children:`Branded`}),(0,Q.jsx)(`option`,{value:`unknown`,children:`Unclassified`})]})]})}function wy(e){return e.measurementScopeKey&&e.measurementScope!==`project`?`${e.measurementScope}:${e.measurementScopeKey}`:`project`}function Ty(e){switch(e.provenance?.source){case`manual`:return`Manual`;case`template`:return`Template`;case`research`:return`Saved research`;case`discovery`:return`Discovery`;default:return`Not recorded`}}function Ey(e,t,n){let r=new Map(t.targets.map(e=>[e.stableKey,e.label])),i=new Map(t.groups.map(e=>[e.stableKey,e.label])),a=new Map(t.markets.map(e=>[e.stableKey,e.label])),o=new Set(e.assignments.map(e=>e.targetKey));if(o.size===0)return`Whole site`;let s=n?e.assignments.filter(e=>xy(e,n)):e.assignments,c=new Set(s.map(e=>e.targetKey));if(n?.measurementScope===`group`){let e=c.size,t=Math.max(0,o.size-e);return[`${e} ${e===1?`property`:`properties`} in this group`,...t?[`Shared with ${t} other ${t===1?`property`:`properties`}`]:[]].join(` · `)}let l=new Set,u=new Set;for(let e of s)e.groupKeys.forEach(e=>l.add(e)),e.marketKeys.forEach(e=>u.add(e));let d=n?.measurementScope===`property`&&o.has(n.measurementScopeKey??``)?o.size===1?[`This property only`]:[`This property`,`Shared with ${o.size-1} other ${o.size===2?`property`:`properties`}`]:c.size===1?[r.get([...c][0])??[...c][0]]:[`${c.size} properties`],f=l.size===1?i.get([...l][0])??[...l][0]:null,p=u.size===1?a.get([...u][0])??[...u][0]:null;return f&&p&&f===p?d.push(`${f} (group and market)`):(f?d.push(`Group: ${f}`):l.size>1&&d.push(`${l.size} groups`),p?d.push(`Market: ${p}`):u.size>1&&d.push(`${u.size} markets`)),d.join(` · `)}function Dy({row:e,workspace:t,selection:n}){let r=Oy(e,t,n);return(0,Q.jsxs)(`details`,{className:`group min-w-48`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer rounded px-1 py-1 text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500`,children:Ey(e,t,n)}),(0,Q.jsxs)(`div`,{className:`mt-2 material-base p-2 text-label-12 text-secondary`,children:[(0,Q.jsx)(`p`,{className:`text-copy-13-strong text-strong`,children:`Assigned relationships`}),(0,Q.jsx)(`ul`,{className:`mt-1 list-disc space-y-1 pl-4`,children:r.map(e=>(0,Q.jsx)(`li`,{children:e},e))})]})]})}function Oy(e,t,n){let r=new Map(t.targets.map(e=>[e.stableKey,e.label])),i=new Map(t.groups.map(e=>[e.stableKey,e.label])),a=new Map(t.markets.map(e=>[e.stableKey,e.label])),o=e.assignments.filter(e=>xy(e,n)).map(e=>{let t=r.get(e.targetKey)??e.targetKey??`Whole site`,o=n.measurementScope===`group`&&n.measurementScopeKey?e.groupKeys.filter(e=>e===n.measurementScopeKey).map(e=>i.get(e)??e):e.groupKeys.map(e=>i.get(e)??e),s=n.measurementScope===`market`&&n.measurementScopeKey?e.marketKeys.filter(e=>e===n.measurementScopeKey).map(e=>a.get(e)??e):e.marketKeys.map(e=>a.get(e)??e);return[t,o.length?`Groups: ${o.join(`, `)}`:null,s.length?`Markets: ${s.join(`, `)}`:null].filter(e=>e!==null).join(` · `)});return[...new Set(o)].length?[...new Set(o)]:[`Whole site`]}function ky({row:e}){let t=[...new Set(e.assignments.map(e=>e.queryClass??`unknown`))],n=t.join(`, `);return(0,Q.jsx)(J,{tone:t.includes(`unknown`)?`caution`:`neutral`,children:n||`Unknown`})}function Ay({row:e,outsidePlan:t=!1}){return t?(0,Q.jsx)(J,{tone:`neutral`,children:`Not in current plan`}):e.state===`tracked`?(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,Q.jsx)(J,{tone:`positive`,children:`Measured`}),e.lastMeasuredAt?(0,Q.jsx)(`time`,{className:`text-copy-13 text-secondary`,dateTime:e.lastMeasuredAt,title:Jr(e.lastMeasuredAt),children:Dr(e.lastMeasuredAt)}):null]}):(0,Q.jsx)(J,{tone:`caution`,children:`Awaiting check`})}function jy({workspace:e,templates:t,action:n,draft:r,onDraftChange:i,onClose:a,canReview:o,isPreviewing:s,editorHeadingRef:c,onReview:l}){let u=t.length>0,d=u||e.savedSources.research.length>0||e.savedSources.discovery.length>0;return n.kind===`remove`?(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{children:`Remove query`}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[`Remove “`,n.row.queryText,`” from future tracking?`]}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[e.mode===`advanced`?`${n.audience?`Only assignments in ${n.scopeLabel} will be removed.`:`All assignments will be removed.`} `:``,`Earlier results stay unchanged.`]})]})}),(0,Q.jsx)(By,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]}):n.kind===`edit`?(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline gap-4`,children:[(0,Q.jsx)(`h3`,{ref:c,tabIndex:-1,children:`Edit query`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:a,children:`Cancel`})]}),(0,Q.jsxs)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:[e.mode===`advanced`?`${n.audience?`Changes apply only to assignments in ${n.scopeLabel}.`:`Changes apply to every assignment of this query.`} `:``,`Earlier results stay unchanged.`]}),(0,Q.jsxs)(`div`,{className:`mt-4 max-w-2xl space-y-4`,children:[(0,Q.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-text`,children:[(0,Q.jsx)(`span`,{className:`text-label-12-strong text-secondary`,children:`Query text`}),(0,Q.jsx)(`textarea`,{id:`tracking-query-text`,className:`mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-copy-14 text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500`,value:r.text,onChange:e=>i({...r,text:e.target.value})})]}),e.mode===`advanced`&&(0,Q.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-class`,children:[(0,Q.jsx)(`span`,{className:`text-label-12-strong text-secondary`,children:`Classification`}),(0,Q.jsxs)(`select`,{id:`tracking-query-class`,className:`mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500`,value:r.queryClass,onChange:e=>i({...r,queryClass:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`keep`,children:`Keep existing classifications`}),(0,Q.jsx)(`option`,{value:`auto`,children:`Automatic`}),(0,Q.jsx)(`option`,{value:`branded`,children:`Branded`}),(0,Q.jsx)(`option`,{value:`non-brand`,children:`Non-brand`})]})]}),e.mode===`advanced`?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Locations and engines stay unchanged.`}):null]}),(0,Q.jsx)(By,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]}):(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline gap-4`,children:[(0,Q.jsx)(`h3`,{ref:c,tabIndex:-1,children:`Add query`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:a,children:`Cancel`})]}),(0,Q.jsxs)(`div`,{className:`mt-4 grid gap-4 ${e.mode===`advanced`?`lg:grid-cols-[minmax(250px,0.8fr)_minmax(0,1.2fr)]`:`max-w-2xl`}`,children:[(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[r.source===`manual`?(0,Q.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-text`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-secondary`,children:`Query`}),(0,Q.jsx)(`textarea`,{id:`tracking-query-text`,className:`mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-copy-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500`,placeholder:`e.g. How do teams compare AEO platforms?`,value:r.text,onChange:e=>i({...r,text:e.target.value})})]}):null,r.source===`template`?(0,Q.jsx)(My,{templates:t,advanced:e.mode===`advanced`,draft:r,onDraftChange:i}):null,r.source===`research`?(0,Q.jsx)(Ny,{id:`tracking-research-source`,label:`Saved research query`,value:r.researchRunQueryId,options:e.savedSources.research.map(e=>({id:e.researchRunQueryId,label:e.queryText,detail:e.researchRunId})),onChange:e=>i({...r,researchRunQueryId:e})}):null,r.source===`discovery`?(0,Q.jsx)(Ny,{id:`tracking-discovery-source`,label:`Discovery query`,value:r.discoveryProbeId,options:e.savedSources.discovery.map(e=>({id:e.discoveryProbeId,label:e.queryText,detail:e.discoverySessionId})),onChange:e=>i({...r,discoveryProbeId:e})}):null,d?(0,Q.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-source`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-secondary`,children:`Query source`}),(0,Q.jsxs)(`select`,{id:`tracking-query-source`,className:`mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-label-14 text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500`,value:r.source,onChange:e=>i({...r,source:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`manual`,children:`Write a query`}),u?(0,Q.jsx)(`option`,{value:`template`,children:`Saved template`}):null,e.savedSources.research.length>0?(0,Q.jsx)(`option`,{value:`research`,children:`Saved research`}):null,e.savedSources.discovery.length>0?(0,Q.jsx)(`option`,{value:`discovery`,children:`Discovery result`}):null]})]}):null]}),e.mode===`advanced`?(0,Q.jsx)(zy,{workspace:e,draft:r,onDraftChange:i}):null]}),e.mode===`advanced`&&!_y(r)?(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Ry,{workspace:e,draft:r,onDraftChange:i})}):null,e.mode===`advanced`?(0,Q.jsxs)(`details`,{className:`mt-4 border-t border-default text-label-14 text-secondary`,children:[(0,Q.jsx)(`summary`,{className:`min-h-11 cursor-pointer py-3`,children:`Measurement options`}),(0,Q.jsx)(`div`,{className:`grid gap-4 pb-3 sm:grid-cols-2`,children:(0,Q.jsxs)(`div`,{className:`block`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,htmlFor:`tracking-query-class`,children:`Classification`}),(0,Q.jsxs)(`select`,{id:`tracking-query-class`,className:`mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-label-14 text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500`,value:r.queryClass,onChange:e=>i({...r,queryClass:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`auto`,children:`Automatic`}),(0,Q.jsx)(`option`,{value:`branded`,children:`Branded`}),(0,Q.jsx)(`option`,{value:`non-brand`,children:`Non-brand`})]})]})})]}):null,r.source===`research`&&(0,Q.jsx)(`p`,{className:`mt-4 material-base px-3 py-2 text-copy-14 text-secondary`,children:`Only the saved query is added.`}),(0,Q.jsx)(By,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]})}function My({templates:e,advanced:t,draft:n,onDraftChange:r}){return(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`label`,{className:`block`,htmlFor:`tracking-template-source`,children:[(0,Q.jsx)(`span`,{className:`text-label-12-strong text-secondary`,children:`Saved template`}),(0,Q.jsxs)(`select`,{id:`tracking-template-source`,"aria-describedby":vy(n)?`tracking-template-market-required`:void 0,className:`mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-label-14 text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500`,value:n.templateId,onChange:t=>{let i=e.find(e=>e.id===t.target.value);r({...n,templateId:i?.id??``,templateVersion:i?.updatedAt??``,template:i?.pattern??``})},children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a template`}),e.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),n.template?(0,Q.jsx)(`span`,{className:`mt-1 block text-label-12 text-muted`,children:n.template}):null]}),vy(n)?(0,Q.jsx)(`p`,{id:`tracking-template-market-required`,role:`status`,className:`mt-2 text-copy-14 text-caution`,children:t?`Choose a Market under Apply to for this template. A Property alone does not select a market.`:`This template needs a market, and this project has no markets. Write a query instead.`}):null]})}function Ny({id:e,label:t,value:n,options:r,onChange:i}){return(0,Q.jsxs)(`label`,{className:`block`,htmlFor:e,children:[(0,Q.jsx)(`span`,{className:`text-label-12-strong text-secondary`,children:t}),(0,Q.jsxs)(`select`,{id:e,className:`mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-label-14 text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500`,value:n,onChange:e=>i(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a saved query`}),r.map(e=>(0,Q.jsxs)(`option`,{value:e.id,children:[e.label,` · `,e.detail]},e.id))]})]})}function Py(e){return{providers:[...e.providers],models:{...e.models},location:e.location?.label??null}}function Fy(e){return JSON.stringify({providers:[...e.providers].sort(),models:Object.fromEntries(Object.entries(e.models).sort(([e],[t])=>e.localeCompare(t))),location:e.location})}function Iy(e){return[...new Map(e.map(e=>[Fy(e),e])).values()]}function Ly(e){let t=e.providers.map(t=>{let n=e.models[t];return n&&n!==an(t)?`${Vo(t)} (${an(t)?Me(n):n})`:Vo(t)}).join(`, `);return`${e.location??`No location`} · ${t}`}function Ry({workspace:e,draft:t,onDraftChange:n}){let r=(0,Z.useMemo)(()=>Iy([...e.defaultContexts.map(Py),...t.contexts]),[t.contexts,e.defaultContexts]),i=t.contexts.length===1?Fy(t.contexts[0]):t.contexts.length>1?`__existing__`:``;return(0,Q.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-context`,children:[(0,Q.jsx)(`span`,{className:`text-label-12-strong text-secondary`,children:`Location and engines`}),(0,Q.jsxs)(`select`,{id:`tracking-query-context`,"aria-label":`Location and engines`,className:`mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-label-14 text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500`,value:i,onChange:e=>{let i=r.find(t=>Fy(t)===e.target.value),a=e.target.value===`__existing__`?t.contexts:i?[i]:[];n({...t,contexts:a})},children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a location and engines`}),t.contexts.length>1?(0,Q.jsxs)(`option`,{value:`__existing__`,children:[`Keep `,t.contexts.length,` existing contexts`]}):null,r.map(e=>(0,Q.jsx)(`option`,{value:Fy(e),children:Ly(e)},Fy(e)))]}),(0,Q.jsx)(`span`,{className:`mt-1 block text-label-12 text-secondary`,children:r.length===0?`No configured measurement context is available.`:`Choose where this query will be measured.`})]})}function zy({workspace:e,draft:t,onDraftChange:n}){let{canWrite:r}=si(),[i,a]=(0,Z.useState)(``),[o,s]=(0,Z.useState)(()=>t.wholeSite||t.targetKeys.length!==1||t.groupKeys.length>0||t.marketKeys.length>0),c=(0,Z.useMemo)(()=>[...e.targets.map(e=>({kind:`target`,key:e.stableKey,label:e.label,detail:`Property`})),...e.groups.map(e=>({kind:`group`,key:e.stableKey,label:e.label,detail:`Group`})),...e.markets.map(e=>({kind:`market`,key:e.stableKey,label:e.label,detail:`Market`}))],[e.groups,e.markets,e.targets]),l=i.trim().toLocaleLowerCase(),u=l?c.filter(e=>`${e.label} ${e.detail}`.toLocaleLowerCase().includes(l)):c,d=t.targetKeys.length+t.groupKeys.length+t.marketKeys.length>0;function f(e,r,i){let a=e===`target`?`targetKeys`:e===`group`?`groupKeys`:`marketKeys`,o=t[a];n({...t,wholeSite:!1,[a]:i?[...o,r]:o.filter(e=>e!==r)})}function p(e,n){return(e===`target`?t.targetKeys:e===`group`?t.groupKeys:t.marketKeys).includes(n)}if(!o){let n=e.targets.find(e=>e.stableKey===t.targetKeys[0]);return(0,Q.jsxs)(`fieldset`,{className:`self-start material-base p-3`,children:[(0,Q.jsx)(`legend`,{className:`px-1 text-label-12-strong text-secondary`,children:`Apply to`}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-14 text-strong`,children:[`Property: `,n?.label??t.targetKeys[0]]}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,"aria-label":`Change tracking destination`,onClick:()=>s(!0),children:`Change`})]})]})}return(0,Q.jsxs)(`fieldset`,{className:`material-base p-3`,children:[(0,Q.jsx)(`legend`,{className:`px-1 text-label-12-strong text-secondary`,children:`Apply to`}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Choose where this query should be tracked.`}),r?(0,Q.jsxs)(`label`,{className:`mt-3 flex min-h-9 items-center gap-2 rounded px-1 text-label-14 text-strong`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t.wholeSite,onChange:e=>{n({...t,wholeSite:e.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),`Every Property (`,e.targets.length,`)`]}):null,!t.wholeSite&&!d?(0,Q.jsx)(`p`,{role:`status`,className:`mt-2 text-copy-14 text-caution`,children:`Choose at least one Property, group, or market.`}):null,(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Group: properties grouped together. Market: search context.`}),(0,Q.jsx)(eu,{value:i,onChange:a,label:`Filter assignments`,placeholder:`Search Properties, Groups, Markets`,className:`mt-3`}),(0,Q.jsx)(`div`,{className:`mt-3 max-h-64 space-y-1 overflow-y-auto pr-1`,children:u.length===0?(0,Q.jsx)(`p`,{className:`px-1 py-2 text-copy-14 text-muted`,children:`No assignment matches that search.`}):u.map(e=>(0,Q.jsxs)(`label`,{className:`flex min-h-9 items-center gap-2 rounded px-1 py-1 text-label-14 text-strong hover:bg-surface-hover`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`${e.label}, ${e.detail}`,checked:p(e.kind,e.key),onChange:t=>f(e.kind,e.key,t.target.checked)}),(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e.label}),(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:e.detail})]},`${e.kind}:${e.key}`))})]})}function By({canReview:e,isPreviewing:t,onCancel:n,onReview:r}){return(0,Q.jsxs)(`div`,{className:`mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4`,children:[(0,Q.jsx)(fs,{type:`button`,size:`sm`,disabled:!e,onClick:r,children:t?`Reviewing…`:`Review changes`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:n,children:`Cancel`}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Publishing does not run a check.`})]})}function Vy({preview:e,workspace:t,isCommitting:n,sweepActive:r,onConfirm:i}){let a=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=a.current;e&&(typeof e.scrollIntoView==`function`&&e.scrollIntoView({block:`start`}),e.focus({preventScroll:!0}))},[e]);let o=!e.diff.noOp,s=o?e.mode===`advanced`?`After you publish, AI Visibility keeps showing the last check until the next check. Property pages and competitor results show no numbers until then. Past answers are kept.`:`Changes apply to future checks. Earlier results stay unchanged.`:`This request leaves tracking unchanged.`,c=[{label:`Added`,rows:e.diff.added},{label:`Removed`,rows:e.diff.removed},{label:`Reused`,rows:e.diff.reused}].filter(e=>e.rows.length>0);return(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline gap-4`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{ref:a,tabIndex:-1,children:o?`Confirm tracked query changes`:`No tracking changes`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14-strong text-strong`,children:Hy(e)}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:s})]}),(0,Q.jsx)(J,{tone:o?`caution`:`neutral`,children:o?`Ready to confirm`:`No-op`})]}),c.length>0?(0,Q.jsx)(`div`,{className:`mt-4 space-y-4`,children:c.map(n=>(0,Q.jsx)(Uy,{label:n.label,rows:n.rows,workspace:t,tracked:e.tracked},n.label))}):null,e.diff.unchanged.length>0?(0,Q.jsxs)(`details`,{className:`mt-4 border-t border-default pt-2 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`summary`,{className:`min-h-11 cursor-pointer py-3`,children:[e.diff.unchanged.length,` unchanged `,e.diff.unchanged.length===1?`query`:`queries`]}),(0,Q.jsx)(Uy,{label:`Unchanged`,rows:e.diff.unchanged,workspace:t,tracked:e.tracked})]}):null,(0,Q.jsxs)(`div`,{className:`mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4`,children:[(0,Q.jsx)(fs,{type:`button`,size:`sm`,disabled:!o||n||r,onClick:i,children:n?`Confirming…`:`Confirm changes`}),o&&r?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`A check is queued or running. Publish after it finishes.`}):null]})]})}function Hy(e){let{added:t}=e.diff,n=new Set(e.tracked.map(e=>e.queryId)),r=e.diff.removed.filter(e=>!n.has(e.queryId)),{addedProviderCalls:i,removedProviderCalls:a,nextSweepProviderCalls:o}=e.workload,s=e=>e.toLocaleString(`en-US`);return[t.length>0?`+${s(t.length)} ${t.length===1?`query`:`queries`}`:null,r.length>0?`−${s(r.length)} ${r.length===1?`query`:`queries`}`:null,`+${s(i)} / −${s(a)} answers per check`,`next check asks ${s(o)}`].filter(e=>e!==null).join(` · `)}function Uy({label:e,rows:t,workspace:n,tracked:r}){return(0,Q.jsxs)(`section`,{"aria-label":`${e} queries`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-13-strong text-secondary`,children:[t.length,` `,e.toLocaleLowerCase(),t.length===1?``:`s`]}),(0,Q.jsx)(`ul`,{className:`mt-2 divide-y divide-default`,children:t.map(t=>(0,Q.jsxs)(`li`,{className:`py-2 text-label-14`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:t.queryText}),(0,Q.jsx)(`p`,{className:`mt-1 text-secondary`,children:e===`Removed`?`${t.assignmentCount} ${t.assignmentCount===1?`assignment`:`assignments`} removed`:Gy(t,r,n)}),e===`Added`||e===`Reused`?(0,Q.jsx)(Wy,{row:r.find(e=>e.queryId===t.queryId),workspace:n}):null]},`${e}:${t.queryId}`))})]})}function Wy({row:e,workspace:t}){if(!e?.assignments.length)return null;let n=new Set(e.assignments.map(e=>e.targetKey)).size;return(0,Q.jsxs)(`details`,{className:`mt-2 text-secondary`,children:[(0,Q.jsxs)(`summary`,{className:`min-h-11 cursor-pointer py-3 text-label-14-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500`,children:[`Classifications · `,n,` `,n===1?`property`:`properties`]}),(0,Q.jsx)(`ul`,{className:`mt-1 max-h-40 space-y-1 overflow-y-auto`,children:e.assignments.map((e,n)=>{let r=t.targets.find(t=>t.stableKey===e.targetKey)?.label??e.targetKey,i=e.queryClass===`branded`?`Branded`:e.queryClass===`non-brand`?`Non-brand`:`Unknown`,a=e.contexts.map(e=>Ly(Py(e))).join(`; `);return(0,Q.jsx)(`li`,{children:[r,i,a].filter(Boolean).join(` · `)},`${e.targetKey}:${n}`)})})]})}function Gy(e,t,n){let r=t.find(t=>t.queryId===e.queryId);if(!r)return`${e.assignmentCount} ${e.assignmentCount===1?`assignment`:`assignments`}`;let i=Iy(r.assignments.flatMap(e=>e.contexts).map(Py)),a=i.length===1?Ly(i[0]):i.length>1?`${i.length} contexts`:null;return[Ey(r,n),a].filter(e=>e!==null).join(` · `)}function Ky({projectName:e,selection:t={measurementScope:`project`,queryClass:`all`},onSelectionChange:n,trackingQueryId:r,onTrackingQueryIdChange:i,pendingTrackingSource:a,onPendingTrackingSourceHandled:o,publishGuard:s}){let c=z(),[l,u]=(0,Z.useState)(null),d=W({...Io({client:Y,path:{name:e}})}),f=W({...bi({client:Y,path:{name:e}}),staleTime:6e4}),p=ie({...ca(),onSuccess:e=>u(e),onError:async t=>{u(null),await c.invalidateQueries({queryKey:Ci({client:Y,path:{name:e}})}),li({title:`Could not review tracking changes`,detail:t instanceof Error?t.message:`Update the draft and review it again.`,tone:`negative`})}}),m=ie({...Yi(),onSuccess:async t=>{u(null),i?.(void 0),await hi(c,e),li({title:t.committed?`Tracked queries updated`:`No tracked-query change`,detail:t.committed&&t.mode===`advanced`?`New numbers after the next check.`:void 0,tone:t.committed?`positive`:`neutral`,dedupeKey:`query-tracking:commit:${e}`,dedupeMode:`replace`})},onError:async t=>{u(null),await hi(c,e),li({title:`Could not confirm tracking changes`,detail:t instanceof Error?t.message:`The review may be stale. Review the changes again.`,tone:`negative`})}});return d.isLoading?(0,Q.jsx)(Cs,{className:`surface-card`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading tracked queries…`})}):d.isError||!d.data?(0,Q.jsxs)(Cs,{className:`surface-card`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative`,children:`Could not load tracked queries.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void d.refetch(),children:`Try again`})]}):(0,Q.jsx)(dy,{workspace:d.data,selection:t,onSelectionChange:n,trackingQueryId:r,onTrackingQueryIdChange:i,pendingTrackingSource:a,onPendingTrackingSourceHandled:o,publishGuard:s,templates:f.data?.templates??[],preview:l,isPreviewing:p.isPending,isCommitting:m.isPending,onPreview:t=>{u(null),p.mutate({client:Y,path:{name:e},body:{...t,expectedWorkspaceVersion:d.data.workspaceVersion}})},onCommit:async t=>{try{return await m.mutateAsync({client:Y,path:{name:e},body:t}),!0}catch{return!1}}})}function qy({projectName:e,onReviewDiscoveryProbe:t}){let n=z(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(`100`),l=W({...Ii({client:Y,path:{name:e},query:{limit:`10`}}),refetchInterval:e=>e.state.data?.some(e=>ay.has(e.status))?3e3:!1}),u=l.data??[];(0,Z.useEffect)(()=>{!r&&u[0]&&i(u[0].id)},[r,u]);let d=u.find(e=>e.id===r)??null,f=W({...ha({client:Y,path:{name:e,id:r??``}}),enabled:!!r,refetchInterval:d&&ay.has(d.status)?3e3:!1}),p=f.data??null,m=ie({mutationFn:()=>{let t={},n=a.trim();n&&(t.icpDescription=n);let r=Number.parseInt(s,10);return Number.isFinite(r)&&r>0&&(t.maxProbes=r),$t(e,t)},onSuccess:async t=>{i(t.sessionId),o(``),await eb(n,e,t.sessionId),li({title:`Discovery started`,detail:`Run ${$y(t.sessionId)} is testing questions your customers might ask.`,tone:`neutral`,dedupeKey:`discovery:start:${t.sessionId}`,dedupeMode:`replace`})},onError:e=>{li({title:`Discovery failed to start`,detail:e instanceof Error?e.message:`Could not start discovery.`,tone:`negative`})}}),h=p??d,g=(0,Z.useMemo)(()=>(p?.probes??[]).slice(0,30),[p?.probes]);async function v(){try{let t=await l.refetch();if(t.error)throw t.error;let n=t.data?.length??0;li({title:`Discovery sessions refreshed`,detail:`${n} recent session${n===1?``:`s`} loaded.`,tone:`positive`,dedupeKey:`discovery:refresh:${e}`,dedupeMode:`replace`})}catch(t){li({title:`Discovery refresh failed`,detail:t instanceof Error?t.message:`Could not reload discovery sessions.`,tone:`negative`,dedupeKey:`discovery:refresh:${e}`,dedupeMode:`replace`})}}return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(`h2`,{children:`Describe your customer`}),(0,Q.jsx)(X,{text:`Generate questions your customers might ask, check current visibility, then choose which queries to track.`}),(0,Q.jsx)(J,{tone:`neutral`,children:`Runs on Gemini`})]}),(0,Q.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:l.isFetching,onClick:()=>void v(),children:[(0,Q.jsx)(_,{className:`size-3.5 ${l.isFetching?`animate-spin`:``}`,"aria-hidden":`true`}),`Refresh`]})]}),(0,Q.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]`,children:[(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[(0,Q.jsx)(Cs,{className:`surface-card`,children:(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`label`,{htmlFor:`discovery-customer-profile`,className:`text-label-14 text-secondary`,children:`Who is your ideal customer?`}),(0,Q.jsx)(X,{text:`Leave blank to use the customer profile saved on this project.`})]}),(0,Q.jsx)(`textarea`,{id:`discovery-customer-profile`,className:`mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-copy-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,placeholder:`e.g. Small e-commerce stores that want AI-powered customer support.`,value:a,onChange:e=>o(e.target.value)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`label`,{htmlFor:`discovery-probe-limit`,className:`text-label-14 text-secondary`,children:`Questions to test`}),(0,Q.jsx)(X,{text:`More questions means broader coverage but a longer run. The default is 100.`})]}),(0,Q.jsx)(`input`,{id:`discovery-probe-limit`,className:`mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,inputMode:`numeric`,value:s,onChange:e=>c(e.target.value)})]}),!K()&&(0,Q.jsxs)(fs,{type:`button`,size:`sm`,disabled:m.isPending,onClick:()=>m.mutate(),children:[(0,Q.jsx)(j,{size:14}),m.isPending?`Starting…`:`Find queries`]})]})}),(u.length>0||l.isPending||l.isError)&&(0,Q.jsxs)(`section`,{children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`h3`,{children:`Recent runs`}),l.isFetching&&(0,Q.jsx)(J,{tone:`neutral`,children:`Loading`})]}),l.isError?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:`Could not load discovery runs. Refresh to try again.`}):u.length===0?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-muted`,children:`Loading discovery runs…`}):(0,Q.jsx)(`div`,{className:`space-y-2`,children:u.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${r===e.id?`border-mono-600 bg-bg-elevated/70`:`border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40`}`,onClick:()=>i(e.id),children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:$y(e.id)}),(0,Q.jsx)(J,{tone:Yy(e.status),children:e.status})]}),(0,Q.jsxs)(`div`,{className:`mt-2 grid grid-cols-3 gap-2 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Cited queries `,e.citedCount??0]}),(0,Q.jsxs)(`span`,{children:[`Worth tracking `,e.aspirationalCount??0]}),(0,Q.jsxs)(`span`,{children:[`Skip `,e.wastedCount??0]})]})]},e.id))})]})]}),(0,Q.jsx)(`div`,{className:`space-y-4`,children:h?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`h3`,{children:[`Run `,$y(h.id)]}),(0,Q.jsx)(J,{tone:Yy(h.status),children:h.status})]}),(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[(0,Q.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-4`,children:[(0,Q.jsx)(Jy,{label:`Questions tested`,value:h.probeCount??0}),(0,Q.jsx)(Jy,{label:`Cited queries`,value:h.citedCount??0,tone:`positive`}),(0,Q.jsx)(Jy,{label:`Worth tracking`,value:h.aspirationalCount??0,tone:`caution`}),(0,Q.jsx)(Jy,{label:`Skip`,value:h.wastedCount??0,tone:`negative`})]}),h.error&&(0,Q.jsx)(`div`,{className:`rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-label-14 text-negative`,children:h.error}),h.warning&&(0,Q.jsx)(`div`,{className:`rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-label-14 text-caution`,children:h.warning}),h.icpDescription&&(0,Q.jsxs)(`div`,{className:`material-base px-3 py-2`,children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Customer profile`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-neutral`,children:h.icpDescription})]}),h.competitorMap.length>0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`mb-2 text-copy-14-strong text-secondary`,children:`Sites that keep getting cited`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:h.competitorMap.slice(0,8).map(e=>(0,Q.jsxs)(`span`,{className:`rounded-md border border-default bg-bg px-2 py-1 text-label-12 text-neutral`,children:[e.domain,` `,(0,Q.jsx)(`span`,{className:`text-muted`,children:e.hits})]},e.domain))})]})]})]}),(0,Q.jsxs)(`section`,{className:`border-t border-default pt-4`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{children:`Results`}),(0,Q.jsx)(X,{text:`Choose a Cited query or Worth tracking result to review for tracking. The review keeps its saved discovery source and lets you choose scope before confirming. Research does not add competitors or start a check.`})]}),f.isFetching&&(0,Q.jsx)(J,{tone:`neutral`,children:`Loading`})]}),g.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Results show up here once the run starts testing questions.`}):(0,Q.jsx)(`div`,{className:`evidence-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Question`}),(0,Q.jsx)(`th`,{children:`Result`}),(0,Q.jsx)(`th`,{children:`Sites cited`}),(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Tracking review`})})]})}),(0,Q.jsx)(`tbody`,{children:g.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.query}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:Xy(e.bucket),children:Qy(e.bucket)})}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.citedDomains.length>0?e.citedDomains.slice(0,3).join(`, `):`-`}),(0,Q.jsx)(`td`,{className:`whitespace-nowrap text-right`,children:!K()&&t&&(e.bucket===`cited`||e.bucket===`aspirational`)&&(0,Q.jsx)(fs,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>t(e.id),children:`Review for tracking`})})]},e.id))})]})})]})]}):(0,Q.jsxs)(`div`,{className:`px-4 py-8 text-center`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Results will appear here`}),(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Find queries to review their answers and choose what to track.`})]})})]})]})}function Jy({label:e,value:t,tone:n=`neutral`}){return(0,Q.jsxs)(`div`,{className:`material-base px-4 py-3`,children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:e}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-24-strong tabular-nums ${n===`positive`?`text-positive`:n===`caution`?`text-caution`:n===`negative`?`text-negative`:`text-heading`}`,children:t})]})}function Yy(e){return e===`completed`?`positive`:e===`failed`?`negative`:ay.has(e)?`caution`:`neutral`}function Xy(e){return e===`cited`?`positive`:e===`aspirational`?`caution`:e===`wasted-surface`?`negative`:`neutral`}var Zy={cited:`Cited queries`,aspirational:`Worth tracking`,"wasted-surface":`Skip`};function Qy(e){return e?Zy[e]:`Not classified`}function $y(e){return e.length>8?e.slice(0,8):e}async function eb(e,t,n){await Promise.all([ui(e,`discovery`),e.invalidateQueries({queryKey:pa({client:Y})})])}var tb=4e3,nb={heading:`Queries`,count:(e,t)=>`${e} of ${t} ${e===1?`query`:`queries`}`,nextCheck:`New queries show results after the next check`,inputLabel:`Add a query`,placeholder:`Add a query customers would ask`,add:`Add`,adding:`Adding…`,remove:`Remove`,removing:`Removing…`,added:e=>`Added “${e}”.`,removed:e=>`Removed “${e}”.`,undo:`Undo`,duplicate:`You already track this query.`,limit:e=>`Your plan tracks up to ${e} queries. Remove one to add another.`,failed:`Couldn’t save. Try again.`,loading:`Loading your queries…`,loadFailed:`Couldn’t load your queries.`,retry:`Try again`,empty:`No queries yet.`,agencyManaged:`Your agency manages these queries.`};function rb(e){return`canonry:embed-query-draft:${e}`}function ib(e){try{return window.sessionStorage.getItem(rb(e))??``}catch{return``}}function ab(e,t){try{t?window.sessionStorage.setItem(rb(e),t):window.sessionStorage.removeItem(rb(e))}catch{}}function ob(e,t){return e.trim().replace(/\s+/g,` `).toLocaleLowerCase()===t.trim().replace(/\s+/g,` `).toLocaleLowerCase()}function sb({projectName:e,limit:t}){let n=z(),r=Io({client:Y,path:{name:e}}),i=W(r),[a,o]=(0,Z.useState)(()=>ib(e)),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(new Map),p=(0,Z.useRef)(null),m=i.data?.tracked??[],h=i.data?.mode===`simple`,g=m.length>=t;(0,Z.useEffect)(()=>{let e=p.current;if(e===null||s!==null)return;p.current=null;let t=m[Math.min(e,m.length-1)],n=t?f.current.get(t.queryId):void 0;n?n.focus():d.current?.focus()},[s,m]);async function _(t){let a=i.data?.workspaceVersion;for(let i=0;i<2;i+=1){(!a||i>0)&&(a=(await n.fetchQuery({...r,staleTime:0})).workspaceVersion);try{let n=await je(()=>It({client:Y,path:{name:e},body:{...t,expectedWorkspaceVersion:a}}));return n.diff.noOp?`unchanged`:(await je(()=>Ue({client:Y,path:{name:e},body:{...t,expectedWorkspaceVersion:n.workspaceVersion,previewToken:n.previewToken,reviewedAt:n.reviewedAt}})),`saved`)}catch(e){if(e instanceof Ln&&e.code===`EMBED_QUERY_LIMIT`)return`limit`;if(i===0&&e instanceof Ln&&e.code===`QUERY_TRACKING_PREVIEW_STALE`)continue;throw e}}throw Error(`The query list kept changing.`)}async function y(r,i){if(m.some(e=>ob(e.queryText,r)))return u({kind:`error`,text:nb.duplicate}),!1;c(i),u(null);try{let i=await _({additions:[{input:{source:`manual`,text:r}}],removals:[]});return i===`unchanged`?(u({kind:`error`,text:nb.duplicate}),!1):i===`limit`?(u({kind:`error`,text:nb.limit(t)}),!1):(await hi(n,e),u({kind:`added`,query:r}),!0)}catch{return u({kind:`error`,text:nb.failed}),!1}finally{c(null)}}async function b(t){t.preventDefault();let n=a.trim();n&&s===null&&!g&&await y(n,`add`)&&(o(``),ab(e,``),d.current?.focus())}async function x(t,r){if(s===null){c({removing:t.queryId}),u(null);try{await _({additions:[],removals:[{queryId:t.queryId}]}),await hi(n,e),p.current=r,u({kind:`removed`,query:t.queryText})}catch{u({kind:`error`,text:nb.failed})}finally{c(null)}}}async function S(e){s===null&&await y(e,`undo`)&&d.current?.focus()}if(i.isLoading)return(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,role:`status`,children:nb.loading});if(i.isError||!i.data)return(0,Q.jsxs)(`div`,{role:`alert`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative`,children:nb.loadFailed}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void i.refetch(),children:nb.retry})]});let C=l?.kind===`error`?l.text:null,w=`embed-query-line`;return(0,Q.jsxs)(`section`,{"aria-labelledby":`embed-queries-heading`,children:[(0,Q.jsx)(`header`,{children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{id:`embed-queries-heading`,className:`text-heading-20 text-heading`,children:nb.heading}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[(0,Q.jsx)(`span`,{className:`text-copy-14-strong text-strong`,children:nb.count(m.length,t)}),` · `,h?nb.nextCheck:nb.agencyManaged]})]})}),h?(0,Q.jsxs)(`form`,{className:`mt-4 flex max-w-2xl gap-2`,onSubmit:e=>void b(e),"aria-busy":s===`add`,children:[(0,Q.jsx)(`label`,{htmlFor:`embed-query-input`,className:`sr-only`,children:nb.inputLabel}),(0,Q.jsx)(`input`,{ref:d,id:`embed-query-input`,type:`text`,className:`h-9 min-w-0 flex-1 rounded-md pointer-coarse:h-11 border border-default bg-surface px-3 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500 aria-disabled:opacity-50 aria-[invalid=true]:border-negative-500`,placeholder:nb.placeholder,maxLength:tb,value:a,readOnly:g||s!==null,"aria-disabled":g||void 0,"aria-invalid":C?!0:void 0,"aria-describedby":w,onChange:t=>{o(t.target.value),ab(e,t.target.value),l?.kind===`error`&&u(null)}}),(0,Q.jsx)(q,{type:`submit`,className:`pointer-coarse:min-h-11`,disabled:g||s!==null||!a.trim(),children:s===`add`?nb.adding:nb.add})]}):null,(0,Q.jsxs)(`div`,{id:w,className:`mt-2 min-h-5 text-label-14`,children:[C?(0,Q.jsx)(`p`,{className:`text-negative`,role:`alert`,children:C}):null,(0,Q.jsxs)(`p`,{className:`text-secondary`,role:`status`,children:[l?.kind===`removed`?(0,Q.jsxs)(Q.Fragment,{children:[nb.removed(l.query),` `,(0,Q.jsx)(`button`,{type:`button`,className:`inline-flex items-center text-link hover:underline pointer-coarse:min-h-11 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500 disabled:opacity-50`,disabled:s!==null||g,onClick:()=>void S(l.query),children:s===`undo`?nb.adding:nb.undo})]}):l?.kind===`added`?(0,Q.jsx)(`span`,{className:`sr-only`,children:nb.added(l.query)}):null,h&&g&&!C?(0,Q.jsx)(`span`,{className:`block`,children:nb.limit(t)}):null]})]}),m.length===0?(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:nb.empty}):(0,Q.jsx)(`ul`,{className:`mt-4 divide-y divide-default border-y border-default`,"aria-label":`Tracked queries`,children:m.map((e,t)=>{let n=typeof s==`object`&&s?.removing===e.queryId;return(0,Q.jsxs)(`li`,{className:`flex items-center justify-between gap-4 py-2`,children:[(0,Q.jsx)(`span`,{className:`min-w-0 break-words text-label-14-strong text-heading`,children:e.queryText}),h?(0,Q.jsxs)(q,{ref:t=>{t?f.current.set(e.queryId,t):f.current.delete(e.queryId)},type:`button`,variant:`ghost`,size:`sm`,className:`pointer-coarse:min-h-11`,"aria-label":`${nb.remove} ${e.queryText}`,disabled:s!==null,onClick:()=>void x(e,t),children:[(0,Q.jsx)(v,{"aria-hidden":`true`,size:13}),n?nb.removing:nb.remove]}):null]},e.queryId)})})]})}var cb=/^www\./i;function lb(e){if(!e)return null;try{return new URL(e).hostname}catch{return null}}function ub(e){return e.trim().toLowerCase().replace(cb,``)}function db(e,t){if(!t)return!1;try{return ub(new URL(e).hostname)===ub(t)}catch{return!1}}function fb(e,t){if(!e)return``;if(!db(e,t))return e;let n=new URL(e),r=`${n.pathname}${n.search}${n.hash}`;return r===``?`/`:r}function pb(e){let t=lb(e);return t?ub(t):null}function mb(e,t,n){if(!e||n.length<2||db(e,t))return null;let r;try{r=new URL(e)}catch{return null}let i=ub(r.hostname);if(!n.some(e=>ub(e)===i))return null;let a=`${r.pathname}${r.search}${r.hash}`;return{site:i,path:a===``?`/`:a}}function hb(e,t){return fb(e.url,t)||e.path||`/`}var gb=n(((e,t)=>{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n<l;++n)r(u[n],this,t);return!0};function d(e,t,n,r){var i,o,s;if(l(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),s=o[t]),s===void 0)s=o[t]=n,++e._eventsCount;else if(typeof s==`function`?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=u(e),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function _(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function v(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function y(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}x(e,t,a,{once:!0}),t!==`error`&&b(e,i,{once:!0})})}function b(e,t,n){typeof e.on==`function`&&x(e,`error`,t,n)}function x(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}})),_b=gb();function vb(){let e=arguments[0];for(let t=1,n=arguments.length;t<n;t++)if(arguments[t])for(let n in arguments[t])e[n]=arguments[t][n];return e}var yb=vb;typeof Object.assign==`function`&&(yb=Object.assign);function bb(e,t,n,r){let i=e._nodes.get(t),a=null;return i&&(a=r===`mixed`?i.out&&i.out[n]||i.undirected&&i.undirected[n]:r===`directed`?i.out&&i.out[n]:i.undirected&&i.undirected[n]),a}function xb(e){return typeof e==`object`&&!!e}function Sb(e){let t;for(t in e)return!1;return!0}function Cb(e,t,n){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!0,value:n})}function wb(e,t,n){let r={enumerable:!0,configurable:!0};typeof n==`function`?r.get=n:(r.value=n,r.writable=!1),Object.defineProperty(e,t,r)}function Tb(e){return!(!xb(e)||e.attributes&&!Array.isArray(e.attributes))}function Eb(){let e=Math.floor(Math.random()*256)&255;return()=>e++}function Db(){let e=arguments,t=null,n=-1;return{[Symbol.iterator](){return this},next(){let r=null;do{if(t===null){if(n++,n>=e.length)return{done:!0};t=e[n][Symbol.iterator]()}if(r=t.next(),r.done)t=null;else break}while(1);return r}}}function Ob(){return{[Symbol.iterator](){return this},next(){return{done:!0}}}}var kb=class extends Error{constructor(e){super(),this.name=`GraphError`,this.message=e}},Ab=class e extends kb{constructor(t){super(t),this.name=`InvalidArgumentsGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}},$=class e extends kb{constructor(t){super(t),this.name=`NotFoundGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}},jb=class e extends kb{constructor(t){super(t),this.name=`UsageGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}};function Mb(e,t){this.key=e,this.attributes=t,this.clear()}Mb.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.undirectedDegree=0,this.undirectedLoops=0,this.directedLoops=0,this.in={},this.out={},this.undirected={}};function Nb(e,t){this.key=e,this.attributes=t,this.clear()}Nb.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}};function Pb(e,t){this.key=e,this.attributes=t,this.clear()}Pb.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}};function Fb(e,t,n,r,i){this.key=t,this.attributes=i,this.undirected=e,this.source=n,this.target=r}Fb.prototype.attach=function(){let e=`out`,t=`in`;this.undirected&&(e=t=`undirected`);let n=this.source.key,r=this.target.key;this.source[e][r]=this,!(this.undirected&&n===r)&&(this.target[t][n]=this)},Fb.prototype.attachMulti=function(){let e=`out`,t=`in`,n=this.source.key,r=this.target.key;this.undirected&&(e=t=`undirected`);let i=this.source[e],a=i[r];a===void 0?(i[r]=this,this.undirected&&n===r||(this.target[t][n]=this)):(a.previous=this,this.next=a,i[r]=this,this.target[t][n]=this)},Fb.prototype.detach=function(){let e=this.source.key,t=this.target.key,n=`out`,r=`in`;this.undirected&&(n=r=`undirected`),delete this.source[n][t],delete this.target[r][e]},Fb.prototype.detachMulti=function(){let e=this.source.key,t=this.target.key,n=`out`,r=`in`;this.undirected&&(n=r=`undirected`),this.previous===void 0?this.next===void 0?(delete this.source[n][t],delete this.target[r][e]):(this.next.previous=void 0,this.source[n][t]=this.next,this.target[r][e]=this.next):(this.previous.next=this.next,this.next!==void 0&&(this.next.previous=this.previous))};var Ib=0,Lb=1,Rb=2,zb=3;function Bb(e,t,n,r,i,a,o){let s,c,l,u;if(r=``+r,n===Ib){if(s=e._nodes.get(r),!s)throw new $(`Graph.${t}: could not find the "${r}" node in the graph.`);l=i,u=a}else if(n===zb){if(i=``+i,c=e._edges.get(i),!c)throw new $(`Graph.${t}: could not find the "${i}" edge in the graph.`);let n=c.source.key,d=c.target.key;if(r===n)s=c.target;else if(r===d)s=c.source;else throw new $(`Graph.${t}: the "${r}" node is not attached to the "${i}" edge (${n}, ${d}).`);l=a,u=o}else{if(c=e._edges.get(r),!c)throw new $(`Graph.${t}: could not find the "${r}" edge in the graph.`);s=n===Lb?c.source:c.target,l=i,u=a}return[s,l,u]}function Vb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Bb(this,t,n,e,r,i);return a.attributes[o]}}function Hb(e,t,n){e.prototype[t]=function(e,r){let[i]=Bb(this,t,n,e,r);return i.attributes}}function Ub(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Bb(this,t,n,e,r,i);return a.attributes.hasOwnProperty(o)}}function Wb(e,t,n){e.prototype[t]=function(e,r,i,a){let[o,s,c]=Bb(this,t,n,e,r,i,a);return o.attributes[s]=c,this.emit(`nodeAttributesUpdated`,{key:o.key,type:`set`,attributes:o.attributes,name:s}),this}}function Gb(e,t,n){e.prototype[t]=function(e,r,i,a){let[o,s,c]=Bb(this,t,n,e,r,i,a);if(typeof c!=`function`)throw new Ab(`Graph.${t}: updater should be a function.`);let l=o.attributes;return l[s]=c(l[s]),this.emit(`nodeAttributesUpdated`,{key:o.key,type:`set`,attributes:o.attributes,name:s}),this}}function Kb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Bb(this,t,n,e,r,i);return delete a.attributes[o],this.emit(`nodeAttributesUpdated`,{key:a.key,type:`remove`,attributes:a.attributes,name:o}),this}}function qb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Bb(this,t,n,e,r,i);if(!xb(o))throw new Ab(`Graph.${t}: provided attributes are not a plain object.`);return a.attributes=o,this.emit(`nodeAttributesUpdated`,{key:a.key,type:`replace`,attributes:a.attributes}),this}}function Jb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Bb(this,t,n,e,r,i);if(!xb(o))throw new Ab(`Graph.${t}: provided attributes are not a plain object.`);return yb(a.attributes,o),this.emit(`nodeAttributesUpdated`,{key:a.key,type:`merge`,attributes:a.attributes,data:o}),this}}function Yb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Bb(this,t,n,e,r,i);if(typeof o!=`function`)throw new Ab(`Graph.${t}: provided updater is not a function.`);return a.attributes=o(a.attributes),this.emit(`nodeAttributesUpdated`,{key:a.key,type:`update`,attributes:a.attributes}),this}}var Xb=[{name:e=>`get${e}Attribute`,attacher:Vb},{name:e=>`get${e}Attributes`,attacher:Hb},{name:e=>`has${e}Attribute`,attacher:Ub},{name:e=>`set${e}Attribute`,attacher:Wb},{name:e=>`update${e}Attribute`,attacher:Gb},{name:e=>`remove${e}Attribute`,attacher:Kb},{name:e=>`replace${e}Attributes`,attacher:qb},{name:e=>`merge${e}Attributes`,attacher:Jb},{name:e=>`update${e}Attributes`,attacher:Yb}];function Zb(e){Xb.forEach(function({name:t,attacher:n}){n(e,t(`Node`),Ib),n(e,t(`Source`),Lb),n(e,t(`Target`),Rb),n(e,t(`Opposite`),zb)})}function Qb(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new jb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new jb(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let a=``+e,o=``+r;if(r=arguments[2],i=bb(this,a,o,n),!i)throw new $(`Graph.${t}: could not find an edge for the given path ("${a}" - "${o}").`)}else{if(n!==`mixed`)throw new jb(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(e=``+e,i=this._edges.get(e),!i)throw new $(`Graph.${t}: could not find the "${e}" edge in the graph.`)}return i.attributes[r]}}function $b(e,t,n){e.prototype[t]=function(e){let r;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new jb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>1){if(this.multi)throw new jb(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let i=``+e,a=``+arguments[1];if(r=bb(this,i,a,n),!r)throw new $(`Graph.${t}: could not find an edge for the given path ("${i}" - "${a}").`)}else{if(n!==`mixed`)throw new jb(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(e=``+e,r=this._edges.get(e),!r)throw new $(`Graph.${t}: could not find the "${e}" edge in the graph.`)}return r.attributes}}function ex(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new jb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new jb(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let a=``+e,o=``+r;if(r=arguments[2],i=bb(this,a,o,n),!i)throw new $(`Graph.${t}: could not find an edge for the given path ("${a}" - "${o}").`)}else{if(n!==`mixed`)throw new jb(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(e=``+e,i=this._edges.get(e),!i)throw new $(`Graph.${t}: could not find the "${e}" edge in the graph.`)}return i.attributes.hasOwnProperty(r)}}function tx(e,t,n){e.prototype[t]=function(e,r,i){let a;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new jb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new jb(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let o=``+e,s=``+r;if(r=arguments[2],i=arguments[3],a=bb(this,o,s,n),!a)throw new $(`Graph.${t}: could not find an edge for the given path ("${o}" - "${s}").`)}else{if(n!==`mixed`)throw new jb(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(e=``+e,a=this._edges.get(e),!a)throw new $(`Graph.${t}: could not find the "${e}" edge in the graph.`)}return a.attributes[r]=i,this.emit(`edgeAttributesUpdated`,{key:a.key,type:`set`,attributes:a.attributes,name:r}),this}}function nx(e,t,n){e.prototype[t]=function(e,r,i){let a;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new jb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new jb(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let o=``+e,s=``+r;if(r=arguments[2],i=arguments[3],a=bb(this,o,s,n),!a)throw new $(`Graph.${t}: could not find an edge for the given path ("${o}" - "${s}").`)}else{if(n!==`mixed`)throw new jb(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(e=``+e,a=this._edges.get(e),!a)throw new $(`Graph.${t}: could not find the "${e}" edge in the graph.`)}if(typeof i!=`function`)throw new Ab(`Graph.${t}: updater should be a function.`);return a.attributes[r]=i(a.attributes[r]),this.emit(`edgeAttributesUpdated`,{key:a.key,type:`set`,attributes:a.attributes,name:r}),this}}function rx(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new jb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new jb(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let a=``+e,o=``+r;if(r=arguments[2],i=bb(this,a,o,n),!i)throw new $(`Graph.${t}: could not find an edge for the given path ("${a}" - "${o}").`)}else{if(n!==`mixed`)throw new jb(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(e=``+e,i=this._edges.get(e),!i)throw new $(`Graph.${t}: could not find the "${e}" edge in the graph.`)}return delete i.attributes[r],this.emit(`edgeAttributesUpdated`,{key:i.key,type:`remove`,attributes:i.attributes,name:r}),this}}function ix(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new jb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new jb(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let a=``+e,o=``+r;if(r=arguments[2],i=bb(this,a,o,n),!i)throw new $(`Graph.${t}: could not find an edge for the given path ("${a}" - "${o}").`)}else{if(n!==`mixed`)throw new jb(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(e=``+e,i=this._edges.get(e),!i)throw new $(`Graph.${t}: could not find the "${e}" edge in the graph.`)}if(!xb(r))throw new Ab(`Graph.${t}: provided attributes are not a plain object.`);return i.attributes=r,this.emit(`edgeAttributesUpdated`,{key:i.key,type:`replace`,attributes:i.attributes}),this}}function ax(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new jb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new jb(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let a=``+e,o=``+r;if(r=arguments[2],i=bb(this,a,o,n),!i)throw new $(`Graph.${t}: could not find an edge for the given path ("${a}" - "${o}").`)}else{if(n!==`mixed`)throw new jb(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(e=``+e,i=this._edges.get(e),!i)throw new $(`Graph.${t}: could not find the "${e}" edge in the graph.`)}if(!xb(r))throw new Ab(`Graph.${t}: provided attributes are not a plain object.`);return yb(i.attributes,r),this.emit(`edgeAttributesUpdated`,{key:i.key,type:`merge`,attributes:i.attributes,data:r}),this}}function ox(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new jb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new jb(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let a=``+e,o=``+r;if(r=arguments[2],i=bb(this,a,o,n),!i)throw new $(`Graph.${t}: could not find an edge for the given path ("${a}" - "${o}").`)}else{if(n!==`mixed`)throw new jb(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(e=``+e,i=this._edges.get(e),!i)throw new $(`Graph.${t}: could not find the "${e}" edge in the graph.`)}if(typeof r!=`function`)throw new Ab(`Graph.${t}: provided updater is not a function.`);return i.attributes=r(i.attributes),this.emit(`edgeAttributesUpdated`,{key:i.key,type:`update`,attributes:i.attributes}),this}}var sx=[{name:e=>`get${e}Attribute`,attacher:Qb},{name:e=>`get${e}Attributes`,attacher:$b},{name:e=>`has${e}Attribute`,attacher:ex},{name:e=>`set${e}Attribute`,attacher:tx},{name:e=>`update${e}Attribute`,attacher:nx},{name:e=>`remove${e}Attribute`,attacher:rx},{name:e=>`replace${e}Attributes`,attacher:ix},{name:e=>`merge${e}Attributes`,attacher:ax},{name:e=>`update${e}Attributes`,attacher:ox}];function cx(e){sx.forEach(function({name:t,attacher:n}){n(e,t(`Edge`),`mixed`),n(e,t(`DirectedEdge`),`directed`),n(e,t(`UndirectedEdge`),`undirected`)})}var lx=[{name:`edges`,type:`mixed`},{name:`inEdges`,type:`directed`,direction:`in`},{name:`outEdges`,type:`directed`,direction:`out`},{name:`inboundEdges`,type:`mixed`,direction:`in`},{name:`outboundEdges`,type:`mixed`,direction:`out`},{name:`directedEdges`,type:`directed`},{name:`undirectedEdges`,type:`undirected`}];function ux(e,t,n,r){let i=!1;for(let a in t){if(a===r)continue;let o=t[a];if(i=n(o.key,o.attributes,o.source.key,o.target.key,o.source.attributes,o.target.attributes,o.undirected),e&&i)return o.key}}function dx(e,t,n,r){let i,a,o,s=!1;for(let c in t)if(c!==r){i=t[c];do{if(a=i.source,o=i.target,s=n(i.key,i.attributes,a.key,o.key,a.attributes,o.attributes,i.undirected),e&&s)return i.key;i=i.next}while(i!==void 0)}}function fx(e,t){let n=Object.keys(e),r=n.length,i,a=0;return{[Symbol.iterator](){return this},next(){do if(i)i=i.next;else{if(a>=r)return{done:!0};let o=n[a++];if(o===t){i=void 0;continue}i=e[o]}while(!i);return{done:!1,value:{edge:i.key,attributes:i.attributes,source:i.source.key,target:i.target.key,sourceAttributes:i.source.attributes,targetAttributes:i.target.attributes,undirected:i.undirected}}}}}function px(e,t,n,r){let i=t[n];if(!i)return;let a=i.source,o=i.target;if(r(i.key,i.attributes,a.key,o.key,a.attributes,o.attributes,i.undirected)&&e)return i.key}function mx(e,t,n,r){let i=t[n];if(!i)return;let a=!1;do{if(a=r(i.key,i.attributes,i.source.key,i.target.key,i.source.attributes,i.target.attributes,i.undirected),e&&a)return i.key;i=i.next}while(i!==void 0)}function hx(e,t){let n=e[t];if(n.next!==void 0)return{[Symbol.iterator](){return this},next(){if(!n)return{done:!0};let e={edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected};return n=n.next,{done:!1,value:e}}};let r=!1;return{[Symbol.iterator](){return this},next(){return r===!0?{done:!0}:(r=!0,{done:!1,value:{edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected}})}}}function gx(e,t){if(e.size===0)return[];if(t===`mixed`||t===e.type)return Array.from(e._edges.keys());let n=t===`undirected`?e.undirectedSize:e.directedSize,r=Array(n),i=t===`undirected`,a=e._edges.values(),o=0,s,c;for(;s=a.next(),s.done!==!0;)c=s.value,c.undirected===i&&(r[o++]=c.key);return r}function _x(e,t,n,r){if(t.size===0)return;let i=n!==`mixed`&&n!==t.type,a=n===`undirected`,o,s,c=!1,l=t._edges.values();for(;o=l.next(),o.done!==!0;){if(s=o.value,i&&s.undirected!==a)continue;let{key:t,attributes:n,source:l,target:u}=s;if(c=r(t,n,l.key,u.key,l.attributes,u.attributes,s.undirected),e&&c)return t}}function vx(e,t){if(e.size===0)return Ob();let n=t!==`mixed`&&t!==e.type,r=t===`undirected`,i=e._edges.values();return{[Symbol.iterator](){return this},next(){let e,t;for(;;){if(e=i.next(),e.done)return e;if(t=e.value,!(n&&t.undirected!==r))break}return{value:{edge:t.key,attributes:t.attributes,source:t.source.key,target:t.target.key,sourceAttributes:t.source.attributes,targetAttributes:t.target.attributes,undirected:t.undirected},done:!1}}}}function yx(e,t,n,r,i,a){let o=t?dx:ux,s;if(n!==`undirected`&&(r!==`out`&&(s=o(e,i.in,a),e&&s)||r!==`in`&&(s=o(e,i.out,a,r?void 0:i.key),e&&s))||n!==`directed`&&(s=o(e,i.undirected,a),e&&s))return s}function bx(e,t,n,r){let i=[];return yx(!1,e,t,n,r,function(e){i.push(e)}),i}function xx(e,t,n){let r=Ob();return e!==`undirected`&&(t!==`out`&&n.in!==void 0&&(r=Db(r,fx(n.in))),t!==`in`&&n.out!==void 0&&(r=Db(r,fx(n.out,t?void 0:n.key)))),e!==`directed`&&n.undirected!==void 0&&(r=Db(r,fx(n.undirected))),r}function Sx(e,t,n,r,i,a,o){let s=n?mx:px,c;if(t!==`undirected`&&(i.in!==void 0&&r!==`out`&&(c=s(e,i.in,a,o),e&&c)||i.out!==void 0&&r!==`in`&&(r||i.key!==a)&&(c=s(e,i.out,a,o),e&&c))||t!==`directed`&&i.undirected!==void 0&&(c=s(e,i.undirected,a,o),e&&c))return c}function Cx(e,t,n,r,i){let a=[];return Sx(!1,e,t,n,r,i,function(e){a.push(e)}),a}function wx(e,t,n,r){let i=Ob();return e!==`undirected`&&(n.in!==void 0&&t!==`out`&&r in n.in&&(i=Db(i,hx(n.in,r))),n.out!==void 0&&t!==`in`&&r in n.out&&(t||n.key!==r)&&(i=Db(i,hx(n.out,r)))),e!==`directed`&&n.undirected!==void 0&&r in n.undirected&&(i=Db(i,hx(n.undirected,r))),i}function Tx(e,t){let{name:n,type:r,direction:i}=t;e.prototype[n]=function(e,t){if(r!==`mixed`&&this.type!==`mixed`&&r!==this.type)return[];if(!arguments.length)return gx(this,r);if(arguments.length===1){e=``+e;let t=this._nodes.get(e);if(t===void 0)throw new $(`Graph.${n}: could not find the "${e}" node in the graph.`);return bx(this.multi,r===`mixed`?this.type:r,i,t)}if(arguments.length===2){e=``+e,t=``+t;let a=this._nodes.get(e);if(!a)throw new $(`Graph.${n}: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new $(`Graph.${n}: could not find the "${t}" target node in the graph.`);return Cx(r,this.multi,i,a,t)}throw new Ab(`Graph.${n}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function Ex(e,t){let{name:n,type:r,direction:i}=t,a=`forEach`+n[0].toUpperCase()+n.slice(1,-1);e.prototype[a]=function(e,t,n){if(r===`mixed`||this.type===`mixed`||r===this.type){if(arguments.length===1)return n=e,_x(!1,this,r,n);if(arguments.length===2){e=``+e,n=t;let o=this._nodes.get(e);if(o===void 0)throw new $(`Graph.${a}: could not find the "${e}" node in the graph.`);return yx(!1,this.multi,r===`mixed`?this.type:r,i,o,n)}if(arguments.length===3){e=``+e,t=``+t;let o=this._nodes.get(e);if(!o)throw new $(`Graph.${a}: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new $(`Graph.${a}: could not find the "${t}" target node in the graph.`);return Sx(!1,r,this.multi,i,o,t,n)}throw new Ab(`Graph.${a}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`)}};let o=`map`+n[0].toUpperCase()+n.slice(1);e.prototype[o]=function(){let e=Array.prototype.slice.call(arguments),t=e.pop(),n;if(e.length===0){let i=0;r!==`directed`&&(i+=this.undirectedSize),r!==`undirected`&&(i+=this.directedSize),n=Array(i);let a=0;e.push((e,r,i,o,s,c,l)=>{n[a++]=t(e,r,i,o,s,c,l)})}else n=[],e.push((e,r,i,a,o,s,c)=>{n.push(t(e,r,i,a,o,s,c))});return this[a].apply(this,e),n};let s=`filter`+n[0].toUpperCase()+n.slice(1);e.prototype[s]=function(){let e=Array.prototype.slice.call(arguments),t=e.pop(),n=[];return e.push((e,r,i,a,o,s,c)=>{t(e,r,i,a,o,s,c)&&n.push(e)}),this[a].apply(this,e),n};let c=`reduce`+n[0].toUpperCase()+n.slice(1);e.prototype[c]=function(){let e=Array.prototype.slice.call(arguments);if(e.length<2||e.length>4)throw new Ab(`Graph.${c}: invalid number of arguments (expecting 2, 3 or 4 and got ${e.length}).`);if(typeof e[e.length-1]==`function`&&typeof e[e.length-2]!=`function`)throw new Ab(`Graph.${c}: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let t,n;e.length===2?(t=e[0],n=e[1],e=[]):e.length===3?(t=e[1],n=e[2],e=[e[0]]):e.length===4&&(t=e[2],n=e[3],e=[e[0],e[1]]);let r=n;return e.push((e,n,i,a,o,s,c)=>{r=t(r,e,n,i,a,o,s,c)}),this[a].apply(this,e),r}}function Dx(e,t){let{name:n,type:r,direction:i}=t,a=`find`+n[0].toUpperCase()+n.slice(1,-1);e.prototype[a]=function(e,t,n){if(r!==`mixed`&&this.type!==`mixed`&&r!==this.type)return!1;if(arguments.length===1)return n=e,_x(!0,this,r,n);if(arguments.length===2){e=``+e,n=t;let o=this._nodes.get(e);if(o===void 0)throw new $(`Graph.${a}: could not find the "${e}" node in the graph.`);return yx(!0,this.multi,r===`mixed`?this.type:r,i,o,n)}if(arguments.length===3){e=``+e,t=``+t;let o=this._nodes.get(e);if(!o)throw new $(`Graph.${a}: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new $(`Graph.${a}: could not find the "${t}" target node in the graph.`);return Sx(!0,r,this.multi,i,o,t,n)}throw new Ab(`Graph.${a}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`)};let o=`some`+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(){let e=Array.prototype.slice.call(arguments),t=e.pop();return e.push((e,n,r,i,a,o,s)=>t(e,n,r,i,a,o,s)),!!this[a].apply(this,e)};let s=`every`+n[0].toUpperCase()+n.slice(1,-1);e.prototype[s]=function(){let e=Array.prototype.slice.call(arguments),t=e.pop();return e.push((e,n,r,i,a,o,s)=>!t(e,n,r,i,a,o,s)),!this[a].apply(this,e)}}function Ox(e,t){let{name:n,type:r,direction:i}=t,a=n.slice(0,-1)+`Entries`;e.prototype[a]=function(e,t){if(r!==`mixed`&&this.type!==`mixed`&&r!==this.type)return Ob();if(!arguments.length)return vx(this,r);if(arguments.length===1){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.${a}: could not find the "${e}" node in the graph.`);return xx(r,i,t)}if(arguments.length===2){e=``+e,t=``+t;let n=this._nodes.get(e);if(!n)throw new $(`Graph.${a}: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new $(`Graph.${a}: could not find the "${t}" target node in the graph.`);return wx(r,i,n,t)}throw new Ab(`Graph.${a}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function kx(e){lx.forEach(t=>{Tx(e,t),Ex(e,t),Dx(e,t),Ox(e,t)})}var Ax=[{name:`neighbors`,type:`mixed`},{name:`inNeighbors`,type:`directed`,direction:`in`},{name:`outNeighbors`,type:`directed`,direction:`out`},{name:`inboundNeighbors`,type:`mixed`,direction:`in`},{name:`outboundNeighbors`,type:`mixed`,direction:`out`},{name:`directedNeighbors`,type:`directed`},{name:`undirectedNeighbors`,type:`undirected`}];function jx(){this.A=null,this.B=null}jx.prototype.wrap=function(e){this.A===null?this.A=e:this.B===null&&(this.B=e)},jx.prototype.has=function(e){return this.A!==null&&e in this.A||this.B!==null&&e in this.B};function Mx(e,t,n,r,i){for(let a in r){let o=r[a],s=o.source,c=o.target,l=s===n?c:s;if(t&&t.has(l.key))continue;let u=i(l.key,l.attributes);if(e&&u)return l.key}}function Nx(e,t,n,r,i){if(t!==`mixed`){if(t===`undirected`)return Mx(e,null,r,r.undirected,i);if(typeof n==`string`)return Mx(e,null,r,r[n],i)}let a=new jx,o;if(t!==`undirected`){if(n!==`out`){if(o=Mx(e,null,r,r.in,i),e&&o)return o;a.wrap(r.in)}if(n!==`in`){if(o=Mx(e,a,r,r.out,i),e&&o)return o;a.wrap(r.out)}}if(t!==`directed`&&(o=Mx(e,a,r,r.undirected,i),e&&o))return o}function Px(e,t,n){if(e!==`mixed`){if(e===`undirected`)return Object.keys(n.undirected);if(typeof t==`string`)return Object.keys(n[t])}let r=[];return Nx(!1,e,t,n,function(e){r.push(e)}),r}function Fx(e,t,n){let r=Object.keys(n),i=r.length,a=0;return{[Symbol.iterator](){return this},next(){let o=null;do{if(a>=i)return e&&e.wrap(n),{done:!0};let s=n[r[a++]],c=s.source,l=s.target;o=c===t?l:c,e&&e.has(o.key)&&(o=null)}while(o===null);return{done:!1,value:{neighbor:o.key,attributes:o.attributes}}}}}function Ix(e,t,n){if(e!==`mixed`){if(e===`undirected`)return Fx(null,n,n.undirected);if(typeof t==`string`)return Fx(null,n,n[t])}let r=Ob(),i=new jx;return e!==`undirected`&&(t!==`out`&&(r=Db(r,Fx(i,n,n.in))),t!==`in`&&(r=Db(r,Fx(i,n,n.out)))),e!==`directed`&&(r=Db(r,Fx(i,n,n.undirected))),r}function Lx(e,t){let{name:n,type:r,direction:i}=t;e.prototype[n]=function(e){if(r!==`mixed`&&this.type!==`mixed`&&r!==this.type)return[];e=``+e;let t=this._nodes.get(e);if(t===void 0)throw new $(`Graph.${n}: could not find the "${e}" node in the graph.`);return Px(r===`mixed`?this.type:r,i,t)}}function Rx(e,t){let{name:n,type:r,direction:i}=t,a=`forEach`+n[0].toUpperCase()+n.slice(1,-1);e.prototype[a]=function(e,t){if(r!==`mixed`&&this.type!==`mixed`&&r!==this.type)return;e=``+e;let n=this._nodes.get(e);if(n===void 0)throw new $(`Graph.${a}: could not find the "${e}" node in the graph.`);Nx(!1,r===`mixed`?this.type:r,i,n,t)};let o=`map`+n[0].toUpperCase()+n.slice(1);e.prototype[o]=function(e,t){let n=[];return this[a](e,(e,r)=>{n.push(t(e,r))}),n};let s=`filter`+n[0].toUpperCase()+n.slice(1);e.prototype[s]=function(e,t){let n=[];return this[a](e,(e,r)=>{t(e,r)&&n.push(e)}),n};let c=`reduce`+n[0].toUpperCase()+n.slice(1);e.prototype[c]=function(e,t,n){if(arguments.length<3)throw new Ab(`Graph.${c}: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let r=n;return this[a](e,(e,n)=>{r=t(r,e,n)}),r}}function zx(e,t){let{name:n,type:r,direction:i}=t,a=n[0].toUpperCase()+n.slice(1,-1),o=`find`+a;e.prototype[o]=function(e,t){if(r!==`mixed`&&this.type!==`mixed`&&r!==this.type)return;e=``+e;let n=this._nodes.get(e);if(n===void 0)throw new $(`Graph.${o}: could not find the "${e}" node in the graph.`);return Nx(!0,r===`mixed`?this.type:r,i,n,t)};let s=`some`+a;e.prototype[s]=function(e,t){return!!this[o](e,t)};let c=`every`+a;e.prototype[c]=function(e,t){return!this[o](e,(e,n)=>!t(e,n))}}function Bx(e,t){let{name:n,type:r,direction:i}=t,a=n.slice(0,-1)+`Entries`;e.prototype[a]=function(e){if(r!==`mixed`&&this.type!==`mixed`&&r!==this.type)return Ob();e=``+e;let t=this._nodes.get(e);if(t===void 0)throw new $(`Graph.${a}: could not find the "${e}" node in the graph.`);return Ix(r===`mixed`?this.type:r,i,t)}}function Vx(e){Ax.forEach(t=>{Lx(e,t),Rx(e,t),zx(e,t),Bx(e,t)})}function Hx(e,t,n,r,i){let a=r._nodes.values(),o=r.type,s,c,l,u,d,f,p;for(;s=a.next(),s.done!==!0;){let r=!1;if(c=s.value,o!==`undirected`)for(l in u=c.out,u){d=u[l];do{if(f=d.target,r=!0,p=i(c.key,f.key,c.attributes,f.attributes,d.key,d.attributes,d.undirected),e&&p)return d;d=d.next}while(d)}if(o!==`directed`){for(l in u=c.undirected,u)if(!(t&&c.key>l)){d=u[l];do{if(f=d.target,f.key!==l&&(f=d.source),r=!0,p=i(c.key,f.key,c.attributes,f.attributes,d.key,d.attributes,d.undirected),e&&p)return d;d=d.next}while(d)}}if(n&&!r&&(p=i(c.key,null,c.attributes,null,null,null,null),e&&p))return null}}function Ux(e,t){let n={key:e};return Sb(t.attributes)||(n.attributes=yb({},t.attributes)),n}function Wx(e,t,n){let r={key:t,source:n.source.key,target:n.target.key};return Sb(n.attributes)||(r.attributes=yb({},n.attributes)),e===`mixed`&&n.undirected&&(r.undirected=!0),r}function Gx(e){if(!xb(e))throw new Ab(`Graph.import: invalid serialized node. A serialized node should be a plain object with at least a "key" property.`);if(!(`key`in e))throw new Ab(`Graph.import: serialized node is missing its key.`);if(`attributes`in e&&(!xb(e.attributes)||e.attributes===null))throw new Ab(`Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.`)}function Kx(e){if(!xb(e))throw new Ab(`Graph.import: invalid serialized edge. A serialized edge should be a plain object with at least a "source" & "target" property.`);if(!(`source`in e))throw new Ab(`Graph.import: serialized edge is missing its source.`);if(!(`target`in e))throw new Ab(`Graph.import: serialized edge is missing its target.`);if(`attributes`in e&&(!xb(e.attributes)||e.attributes===null))throw new Ab(`Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.`);if(`undirected`in e&&typeof e.undirected!=`boolean`)throw new Ab(`Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.`)}var qx=Eb(),Jx=new Set([`directed`,`undirected`,`mixed`]),Yx=new Set([`domain`,`_events`,`_eventsCount`,`_maxListeners`]),Xx=[{name:e=>`${e}Edge`,generateKey:!0},{name:e=>`${e}DirectedEdge`,generateKey:!0,type:`directed`},{name:e=>`${e}UndirectedEdge`,generateKey:!0,type:`undirected`},{name:e=>`${e}EdgeWithKey`},{name:e=>`${e}DirectedEdgeWithKey`,type:`directed`},{name:e=>`${e}UndirectedEdgeWithKey`,type:`undirected`}],Zx={allowSelfLoops:!0,multi:!1,type:`mixed`};function Qx(e,t,n){if(n&&!xb(n))throw new Ab(`Graph.addNode: invalid attributes. Expecting an object but got "${n}"`);if(t=``+t,n||={},e._nodes.has(t))throw new jb(`Graph.addNode: the "${t}" node already exist in the graph.`);let r=new e.NodeDataClass(t,n);return e._nodes.set(t,r),e.emit(`nodeAdded`,{key:t,attributes:n}),r}function $x(e,t,n){let r=new e.NodeDataClass(t,n);return e._nodes.set(t,r),e.emit(`nodeAdded`,{key:t,attributes:n}),r}function eS(e,t,n,r,i,a,o,s){if(!r&&e.type===`undirected`)throw new jb(`Graph.${t}: you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.`);if(r&&e.type===`directed`)throw new jb(`Graph.${t}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);if(s&&!xb(s))throw new Ab(`Graph.${t}: invalid attributes. Expecting an object but got "${s}"`);if(a=``+a,o=``+o,s||={},!e.allowSelfLoops&&a===o)throw new jb(`Graph.${t}: source & target are the same ("${a}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);let c=e._nodes.get(a),l=e._nodes.get(o);if(!c)throw new $(`Graph.${t}: source node "${a}" not found.`);if(!l)throw new $(`Graph.${t}: target node "${o}" not found.`);let u={key:null,undirected:r,source:a,target:o,attributes:s};if(n)i=e._edgeKeyGenerator();else if(i=``+i,e._edges.has(i))throw new jb(`Graph.${t}: the "${i}" edge already exists in the graph.`);if(!e.multi&&(r?c.undirected[o]!==void 0:c.out[o]!==void 0))throw new jb(`Graph.${t}: an edge linking "${a}" to "${o}" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option.`);let d=new Fb(r,i,c,l,s);e._edges.set(i,d);let f=a===o;return r?(c.undirectedDegree++,l.undirectedDegree++,f&&(c.undirectedLoops++,e._undirectedSelfLoopCount++)):(c.outDegree++,l.inDegree++,f&&(c.directedLoops++,e._directedSelfLoopCount++)),e.multi?d.attachMulti():d.attach(),r?e._undirectedSize++:e._directedSize++,u.key=i,e.emit(`edgeAdded`,u),i}function tS(e,t,n,r,i,a,o,s,c){if(!r&&e.type===`undirected`)throw new jb(`Graph.${t}: you cannot merge/update a directed edge to an undirected graph. Use the #.mergeEdge/#.updateEdge or #.addUndirectedEdge instead.`);if(r&&e.type===`directed`)throw new jb(`Graph.${t}: you cannot merge/update an undirected edge to a directed graph. Use the #.mergeEdge/#.updateEdge or #.addDirectedEdge instead.`);if(s){if(c){if(typeof s!=`function`)throw new Ab(`Graph.${t}: invalid updater function. Expecting a function but got "${s}"`)}else if(!xb(s))throw new Ab(`Graph.${t}: invalid attributes. Expecting an object but got "${s}"`)}a=``+a,o=``+o;let l;if(c&&(l=s,s=void 0),!e.allowSelfLoops&&a===o)throw new jb(`Graph.${t}: source & target are the same ("${a}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);let u=e._nodes.get(a),d=e._nodes.get(o),f,p;if(!n&&(f=e._edges.get(i),f)){if((f.source.key!==a||f.target.key!==o)&&(!r||f.source.key!==o||f.target.key!==a))throw new jb(`Graph.${t}: inconsistency detected when attempting to merge the "${i}" edge with "${a}" source & "${o}" target vs. ("${f.source.key}", "${f.target.key}").`);p=f}if(!p&&!e.multi&&u&&(p=r?u.undirected[o]:u.out[o]),p){let t=[p.key,!1,!1,!1];if(c?!l:!s)return t;if(c){let t=p.attributes;p.attributes=l(t),e.emit(`edgeAttributesUpdated`,{type:`replace`,key:p.key,attributes:p.attributes})}else yb(p.attributes,s),e.emit(`edgeAttributesUpdated`,{type:`merge`,key:p.key,attributes:p.attributes,data:s});return t}s||={},c&&l&&(s=l(s));let m={key:null,undirected:r,source:a,target:o,attributes:s};if(n)i=e._edgeKeyGenerator();else if(i=``+i,e._edges.has(i))throw new jb(`Graph.${t}: the "${i}" edge already exists in the graph.`);let h=!1,g=!1;u||(u=$x(e,a,{}),h=!0,a===o&&(d=u,g=!0)),d||(d=$x(e,o,{}),g=!0),f=new Fb(r,i,u,d,s),e._edges.set(i,f);let _=a===o;return r?(u.undirectedDegree++,d.undirectedDegree++,_&&(u.undirectedLoops++,e._undirectedSelfLoopCount++)):(u.outDegree++,d.inDegree++,_&&(u.directedLoops++,e._directedSelfLoopCount++)),e.multi?f.attachMulti():f.attach(),r?e._undirectedSize++:e._directedSize++,m.key=i,e.emit(`edgeAdded`,m),[i,!0,h,g]}function nS(e,t){e._edges.delete(t.key);let{source:n,target:r,attributes:i}=t,a=t.undirected,o=n===r;a?(n.undirectedDegree--,r.undirectedDegree--,o&&(n.undirectedLoops--,e._undirectedSelfLoopCount--)):(n.outDegree--,r.inDegree--,o&&(n.directedLoops--,e._directedSelfLoopCount--)),e.multi?t.detachMulti():t.detach(),a?e._undirectedSize--:e._directedSize--,e.emit(`edgeDropped`,{key:t.key,attributes:i,source:n.key,target:r.key,undirected:a})}var rS=class e extends _b.EventEmitter{constructor(e){if(super(),e=yb({},Zx,e),typeof e.multi!=`boolean`)throw new Ab(`Graph.constructor: invalid 'multi' option. Expecting a boolean but got "${e.multi}".`);if(!Jx.has(e.type))throw new Ab(`Graph.constructor: invalid 'type' option. Should be one of "mixed", "directed" or "undirected" but got "${e.type}".`);if(typeof e.allowSelfLoops!=`boolean`)throw new Ab(`Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got "${e.allowSelfLoops}".`);let t=e.type===`mixed`?Mb:e.type===`directed`?Nb:Pb;Cb(this,`NodeDataClass`,t);let n=`geid_`+qx()+`_`,r=0;Cb(this,`_attributes`,{}),Cb(this,`_nodes`,new Map),Cb(this,`_edges`,new Map),Cb(this,`_directedSize`,0),Cb(this,`_undirectedSize`,0),Cb(this,`_directedSelfLoopCount`,0),Cb(this,`_undirectedSelfLoopCount`,0),Cb(this,`_edgeKeyGenerator`,()=>{let e;do e=n+r++;while(this._edges.has(e));return e}),Cb(this,`_options`,e),Yx.forEach(e=>Cb(this,e,this[e])),wb(this,`order`,()=>this._nodes.size),wb(this,`size`,()=>this._edges.size),wb(this,`directedSize`,()=>this._directedSize),wb(this,`undirectedSize`,()=>this._undirectedSize),wb(this,`selfLoopCount`,()=>this._directedSelfLoopCount+this._undirectedSelfLoopCount),wb(this,`directedSelfLoopCount`,()=>this._directedSelfLoopCount),wb(this,`undirectedSelfLoopCount`,()=>this._undirectedSelfLoopCount),wb(this,`multi`,this._options.multi),wb(this,`type`,this._options.type),wb(this,`allowSelfLoops`,this._options.allowSelfLoops),wb(this,`implementation`,()=>`graphology`)}_resetInstanceCounters(){this._directedSize=0,this._undirectedSize=0,this._directedSelfLoopCount=0,this._undirectedSelfLoopCount=0}hasNode(e){return this._nodes.has(``+e)}hasDirectedEdge(e,t){if(this.type===`undirected`)return!1;if(arguments.length===1){let t=``+e,n=this._edges.get(t);return!!n&&!n.undirected}if(arguments.length===2){e=``+e,t=``+t;let n=this._nodes.get(e);return n?n.out.hasOwnProperty(t):!1}throw new Ab(`Graph.hasDirectedEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}hasUndirectedEdge(e,t){if(this.type===`directed`)return!1;if(arguments.length===1){let t=``+e,n=this._edges.get(t);return!!n&&n.undirected}if(arguments.length===2){e=``+e,t=``+t;let n=this._nodes.get(e);return n?n.undirected.hasOwnProperty(t):!1}throw new Ab(`Graph.hasDirectedEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}hasEdge(e,t){if(arguments.length===1){let t=``+e;return this._edges.has(t)}if(arguments.length===2){e=``+e,t=``+t;let n=this._nodes.get(e);return n?n.out!==void 0&&n.out.hasOwnProperty(t)||n.undirected!==void 0&&n.undirected.hasOwnProperty(t):!1}throw new Ab(`Graph.hasEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}directedEdge(e,t){if(this.type===`undirected`)return;if(e=``+e,t=``+t,this.multi)throw new jb(`Graph.directedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.directedEdges instead.`);let n=this._nodes.get(e);if(!n)throw new $(`Graph.directedEdge: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new $(`Graph.directedEdge: could not find the "${t}" target node in the graph.`);let r=n.out&&n.out[t]||void 0;if(r)return r.key}undirectedEdge(e,t){if(this.type===`directed`)return;if(e=``+e,t=``+t,this.multi)throw new jb(`Graph.undirectedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.undirectedEdges instead.`);let n=this._nodes.get(e);if(!n)throw new $(`Graph.undirectedEdge: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new $(`Graph.undirectedEdge: could not find the "${t}" target node in the graph.`);let r=n.undirected&&n.undirected[t]||void 0;if(r)return r.key}edge(e,t){if(this.multi)throw new jb(`Graph.edge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.edges instead.`);e=``+e,t=``+t;let n=this._nodes.get(e);if(!n)throw new $(`Graph.edge: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new $(`Graph.edge: could not find the "${t}" target node in the graph.`);let r=n.out&&n.out[t]||n.undirected&&n.undirected[t]||void 0;if(r)return r.key}areDirectedNeighbors(e,t){e=``+e,t=``+t;let n=this._nodes.get(e);if(!n)throw new $(`Graph.areDirectedNeighbors: could not find the "${e}" node in the graph.`);return this.type===`undirected`?!1:t in n.in||t in n.out}areOutNeighbors(e,t){e=``+e,t=``+t;let n=this._nodes.get(e);if(!n)throw new $(`Graph.areOutNeighbors: could not find the "${e}" node in the graph.`);return this.type!==`undirected`&&t in n.out}areInNeighbors(e,t){e=``+e,t=``+t;let n=this._nodes.get(e);if(!n)throw new $(`Graph.areInNeighbors: could not find the "${e}" node in the graph.`);return this.type!==`undirected`&&t in n.in}areUndirectedNeighbors(e,t){e=``+e,t=``+t;let n=this._nodes.get(e);if(!n)throw new $(`Graph.areUndirectedNeighbors: could not find the "${e}" node in the graph.`);return this.type!==`directed`&&t in n.undirected}areNeighbors(e,t){e=``+e,t=``+t;let n=this._nodes.get(e);if(!n)throw new $(`Graph.areNeighbors: could not find the "${e}" node in the graph.`);return this.type!==`undirected`&&(t in n.in||t in n.out)||this.type!==`directed`&&t in n.undirected}areInboundNeighbors(e,t){e=``+e,t=``+t;let n=this._nodes.get(e);if(!n)throw new $(`Graph.areInboundNeighbors: could not find the "${e}" node in the graph.`);return this.type!==`undirected`&&t in n.in||this.type!==`directed`&&t in n.undirected}areOutboundNeighbors(e,t){e=``+e,t=``+t;let n=this._nodes.get(e);if(!n)throw new $(`Graph.areOutboundNeighbors: could not find the "${e}" node in the graph.`);return this.type!==`undirected`&&t in n.out||this.type!==`directed`&&t in n.undirected}inDegree(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.inDegree: could not find the "${e}" node in the graph.`);return this.type===`undirected`?0:t.inDegree}outDegree(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.outDegree: could not find the "${e}" node in the graph.`);return this.type===`undirected`?0:t.outDegree}directedDegree(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.directedDegree: could not find the "${e}" node in the graph.`);return this.type===`undirected`?0:t.inDegree+t.outDegree}undirectedDegree(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.undirectedDegree: could not find the "${e}" node in the graph.`);return this.type===`directed`?0:t.undirectedDegree}inboundDegree(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.inboundDegree: could not find the "${e}" node in the graph.`);let n=0;return this.type!==`directed`&&(n+=t.undirectedDegree),this.type!==`undirected`&&(n+=t.inDegree),n}outboundDegree(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.outboundDegree: could not find the "${e}" node in the graph.`);let n=0;return this.type!==`directed`&&(n+=t.undirectedDegree),this.type!==`undirected`&&(n+=t.outDegree),n}degree(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.degree: could not find the "${e}" node in the graph.`);let n=0;return this.type!==`directed`&&(n+=t.undirectedDegree),this.type!==`undirected`&&(n+=t.inDegree+t.outDegree),n}inDegreeWithoutSelfLoops(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.inDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);return this.type===`undirected`?0:t.inDegree-t.directedLoops}outDegreeWithoutSelfLoops(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.outDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);return this.type===`undirected`?0:t.outDegree-t.directedLoops}directedDegreeWithoutSelfLoops(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.directedDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);return this.type===`undirected`?0:t.inDegree+t.outDegree-t.directedLoops*2}undirectedDegreeWithoutSelfLoops(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.undirectedDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);return this.type===`directed`?0:t.undirectedDegree-t.undirectedLoops*2}inboundDegreeWithoutSelfLoops(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.inboundDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);let n=0,r=0;return this.type!==`directed`&&(n+=t.undirectedDegree,r+=t.undirectedLoops*2),this.type!==`undirected`&&(n+=t.inDegree,r+=t.directedLoops),n-r}outboundDegreeWithoutSelfLoops(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.outboundDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);let n=0,r=0;return this.type!==`directed`&&(n+=t.undirectedDegree,r+=t.undirectedLoops*2),this.type!==`undirected`&&(n+=t.outDegree,r+=t.directedLoops),n-r}degreeWithoutSelfLoops(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.degreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);let n=0,r=0;return this.type!==`directed`&&(n+=t.undirectedDegree,r+=t.undirectedLoops*2),this.type!==`undirected`&&(n+=t.inDegree+t.outDegree,r+=t.directedLoops*2),n-r}source(e){e=``+e;let t=this._edges.get(e);if(!t)throw new $(`Graph.source: could not find the "${e}" edge in the graph.`);return t.source.key}target(e){e=``+e;let t=this._edges.get(e);if(!t)throw new $(`Graph.target: could not find the "${e}" edge in the graph.`);return t.target.key}extremities(e){e=``+e;let t=this._edges.get(e);if(!t)throw new $(`Graph.extremities: could not find the "${e}" edge in the graph.`);return[t.source.key,t.target.key]}opposite(e,t){e=``+e,t=``+t;let n=this._edges.get(t);if(!n)throw new $(`Graph.opposite: could not find the "${t}" edge in the graph.`);let r=n.source.key,i=n.target.key;if(e===r)return i;if(e===i)return r;throw new $(`Graph.opposite: the "${e}" node is not attached to the "${t}" edge (${r}, ${i}).`)}hasExtremity(e,t){e=``+e,t=``+t;let n=this._edges.get(e);if(!n)throw new $(`Graph.hasExtremity: could not find the "${e}" edge in the graph.`);return n.source.key===t||n.target.key===t}isUndirected(e){e=``+e;let t=this._edges.get(e);if(!t)throw new $(`Graph.isUndirected: could not find the "${e}" edge in the graph.`);return t.undirected}isDirected(e){e=``+e;let t=this._edges.get(e);if(!t)throw new $(`Graph.isDirected: could not find the "${e}" edge in the graph.`);return!t.undirected}isSelfLoop(e){e=``+e;let t=this._edges.get(e);if(!t)throw new $(`Graph.isSelfLoop: could not find the "${e}" edge in the graph.`);return t.source===t.target}addNode(e,t){return Qx(this,e,t).key}mergeNode(e,t){if(t&&!xb(t))throw new Ab(`Graph.mergeNode: invalid attributes. Expecting an object but got "${t}"`);e=``+e,t||={};let n=this._nodes.get(e);return n?(t&&(yb(n.attributes,t),this.emit(`nodeAttributesUpdated`,{type:`merge`,key:e,attributes:n.attributes,data:t})),[e,!1]):(n=new this.NodeDataClass(e,t),this._nodes.set(e,n),this.emit(`nodeAdded`,{key:e,attributes:t}),[e,!0])}updateNode(e,t){if(t&&typeof t!=`function`)throw new Ab(`Graph.updateNode: invalid updater function. Expecting a function but got "${t}"`);e=``+e;let n=this._nodes.get(e);if(n){if(t){let r=n.attributes;n.attributes=t(r),this.emit(`nodeAttributesUpdated`,{type:`replace`,key:e,attributes:n.attributes})}return[e,!1]}let r=t?t({}):{};return n=new this.NodeDataClass(e,r),this._nodes.set(e,n),this.emit(`nodeAdded`,{key:e,attributes:r}),[e,!0]}dropNode(e){e=``+e;let t=this._nodes.get(e);if(!t)throw new $(`Graph.dropNode: could not find the "${e}" node in the graph.`);let n;if(this.type!==`undirected`){for(let e in t.out){n=t.out[e];do nS(this,n),n=n.next;while(n)}for(let e in t.in){n=t.in[e];do nS(this,n),n=n.next;while(n)}}if(this.type!==`directed`)for(let e in t.undirected){n=t.undirected[e];do nS(this,n),n=n.next;while(n)}this._nodes.delete(e),this.emit(`nodeDropped`,{key:e,attributes:t.attributes})}dropEdge(e){let t;if(arguments.length>1){let e=``+arguments[0],n=``+arguments[1];if(t=bb(this,e,n,this.type),!t)throw new $(`Graph.dropEdge: could not find the "${e}" -> "${n}" edge in the graph.`)}else if(e=``+e,t=this._edges.get(e),!t)throw new $(`Graph.dropEdge: could not find the "${e}" edge in the graph.`);return nS(this,t),this}dropDirectedEdge(e,t){if(arguments.length<2)throw new jb(`Graph.dropDirectedEdge: it does not make sense to try and drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.`);if(this.multi)throw new jb(`Graph.dropDirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.`);e=``+e,t=``+t;let n=bb(this,e,t,`directed`);if(!n)throw new $(`Graph.dropDirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return nS(this,n),this}dropUndirectedEdge(e,t){if(arguments.length<2)throw new jb(`Graph.dropUndirectedEdge: it does not make sense to drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.`);if(this.multi)throw new jb(`Graph.dropUndirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.`);let n=bb(this,e,t,`undirected`);if(!n)throw new $(`Graph.dropUndirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return nS(this,n),this}clear(){this._edges.clear(),this._nodes.clear(),this._resetInstanceCounters(),this.emit(`cleared`)}clearEdges(){let e=this._nodes.values(),t;for(;t=e.next(),t.done!==!0;)t.value.clear();this._edges.clear(),this._resetInstanceCounters(),this.emit(`edgesCleared`)}getAttribute(e){return this._attributes[e]}getAttributes(){return this._attributes}hasAttribute(e){return this._attributes.hasOwnProperty(e)}setAttribute(e,t){return this._attributes[e]=t,this.emit(`attributesUpdated`,{type:`set`,attributes:this._attributes,name:e}),this}updateAttribute(e,t){if(typeof t!=`function`)throw new Ab(`Graph.updateAttribute: updater should be a function.`);let n=this._attributes[e];return this._attributes[e]=t(n),this.emit(`attributesUpdated`,{type:`set`,attributes:this._attributes,name:e}),this}removeAttribute(e){return delete this._attributes[e],this.emit(`attributesUpdated`,{type:`remove`,attributes:this._attributes,name:e}),this}replaceAttributes(e){if(!xb(e))throw new Ab(`Graph.replaceAttributes: provided attributes are not a plain object.`);return this._attributes=e,this.emit(`attributesUpdated`,{type:`replace`,attributes:this._attributes}),this}mergeAttributes(e){if(!xb(e))throw new Ab(`Graph.mergeAttributes: provided attributes are not a plain object.`);return yb(this._attributes,e),this.emit(`attributesUpdated`,{type:`merge`,attributes:this._attributes,data:e}),this}updateAttributes(e){if(typeof e!=`function`)throw new Ab(`Graph.updateAttributes: provided updater is not a function.`);return this._attributes=e(this._attributes),this.emit(`attributesUpdated`,{type:`update`,attributes:this._attributes}),this}updateEachNodeAttributes(e,t){if(typeof e!=`function`)throw new Ab(`Graph.updateEachNodeAttributes: expecting an updater function.`);if(t&&!Tb(t))throw new Ab(`Graph.updateEachNodeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}`);let n=this._nodes.values(),r,i;for(;r=n.next(),r.done!==!0;)i=r.value,i.attributes=e(i.key,i.attributes);this.emit(`eachNodeAttributesUpdated`,{hints:t||null})}updateEachEdgeAttributes(e,t){if(typeof e!=`function`)throw new Ab(`Graph.updateEachEdgeAttributes: expecting an updater function.`);if(t&&!Tb(t))throw new Ab(`Graph.updateEachEdgeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}`);let n=this._edges.values(),r,i,a,o;for(;r=n.next(),r.done!==!0;)i=r.value,a=i.source,o=i.target,i.attributes=e(i.key,i.attributes,a.key,o.key,a.attributes,o.attributes,i.undirected);this.emit(`eachEdgeAttributesUpdated`,{hints:t||null})}forEachAdjacencyEntry(e){if(typeof e!=`function`)throw new Ab(`Graph.forEachAdjacencyEntry: expecting a callback.`);Hx(!1,!1,!1,this,e)}forEachAdjacencyEntryWithOrphans(e){if(typeof e!=`function`)throw new Ab(`Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.`);Hx(!1,!1,!0,this,e)}forEachAssymetricAdjacencyEntry(e){if(typeof e!=`function`)throw new Ab(`Graph.forEachAssymetricAdjacencyEntry: expecting a callback.`);Hx(!1,!0,!1,this,e)}forEachAssymetricAdjacencyEntryWithOrphans(e){if(typeof e!=`function`)throw new Ab(`Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.`);Hx(!1,!0,!0,this,e)}nodes(){return Array.from(this._nodes.keys())}forEachNode(e){if(typeof e!=`function`)throw new Ab(`Graph.forEachNode: expecting a callback.`);let t=this._nodes.values(),n,r;for(;n=t.next(),n.done!==!0;)r=n.value,e(r.key,r.attributes)}findNode(e){if(typeof e!=`function`)throw new Ab(`Graph.findNode: expecting a callback.`);let t=this._nodes.values(),n,r;for(;n=t.next(),n.done!==!0;)if(r=n.value,e(r.key,r.attributes))return r.key}mapNodes(e){if(typeof e!=`function`)throw new Ab(`Graph.mapNode: expecting a callback.`);let t=this._nodes.values(),n,r,i=Array(this.order),a=0;for(;n=t.next(),n.done!==!0;)r=n.value,i[a++]=e(r.key,r.attributes);return i}someNode(e){if(typeof e!=`function`)throw new Ab(`Graph.someNode: expecting a callback.`);let t=this._nodes.values(),n,r;for(;n=t.next(),n.done!==!0;)if(r=n.value,e(r.key,r.attributes))return!0;return!1}everyNode(e){if(typeof e!=`function`)throw new Ab(`Graph.everyNode: expecting a callback.`);let t=this._nodes.values(),n,r;for(;n=t.next(),n.done!==!0;)if(r=n.value,!e(r.key,r.attributes))return!1;return!0}filterNodes(e){if(typeof e!=`function`)throw new Ab(`Graph.filterNodes: expecting a callback.`);let t=this._nodes.values(),n,r,i=[];for(;n=t.next(),n.done!==!0;)r=n.value,e(r.key,r.attributes)&&i.push(r.key);return i}reduceNodes(e,t){if(typeof e!=`function`)throw new Ab(`Graph.reduceNodes: expecting a callback.`);if(arguments.length<2)throw new Ab(`Graph.reduceNodes: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let n=t,r=this._nodes.values(),i,a;for(;i=r.next(),i.done!==!0;)a=i.value,n=e(n,a.key,a.attributes);return n}nodeEntries(){let e=this._nodes.values();return{[Symbol.iterator](){return this},next(){let t=e.next();if(t.done)return t;let n=t.value;return{value:{node:n.key,attributes:n.attributes},done:!1}}}}export(){let e=Array(this._nodes.size),t=0;this._nodes.forEach((n,r)=>{e[t++]=Ux(r,n)});let n=Array(this._edges.size);return t=0,this._edges.forEach((e,r)=>{n[t++]=Wx(this.type,r,e)}),{options:{type:this.type,multi:this.multi,allowSelfLoops:this.allowSelfLoops},attributes:this.getAttributes(),nodes:e,edges:n}}import(t,n=!1){if(t instanceof e)return t.forEachNode((e,t)=>{n?this.mergeNode(e,t):this.addNode(e,t)}),t.forEachEdge((e,t,r,i,a,o,s)=>{n?s?this.mergeUndirectedEdgeWithKey(e,r,i,t):this.mergeDirectedEdgeWithKey(e,r,i,t):s?this.addUndirectedEdgeWithKey(e,r,i,t):this.addDirectedEdgeWithKey(e,r,i,t)}),this;if(!xb(t))throw new Ab(`Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.`);if(t.attributes){if(!xb(t.attributes))throw new Ab(`Graph.import: invalid attributes. Expecting a plain object.`);n?this.mergeAttributes(t.attributes):this.replaceAttributes(t.attributes)}let r,i,a,o,s;if(t.nodes){if(a=t.nodes,!Array.isArray(a))throw new Ab(`Graph.import: invalid nodes. Expecting an array.`);for(r=0,i=a.length;r<i;r++){o=a[r],Gx(o);let{key:e,attributes:t}=o;n?this.mergeNode(e,t):this.addNode(e,t)}}if(t.edges){let e=!1;if(this.type===`undirected`&&(e=!0),a=t.edges,!Array.isArray(a))throw new Ab(`Graph.import: invalid edges. Expecting an array.`);for(r=0,i=a.length;r<i;r++){s=a[r],Kx(s);let{source:t,target:i,attributes:o,undirected:c=e}=s,l;`key`in s?(l=n?c?this.mergeUndirectedEdgeWithKey:this.mergeDirectedEdgeWithKey:c?this.addUndirectedEdgeWithKey:this.addDirectedEdgeWithKey,l.call(this,s.key,t,i,o)):(l=n?c?this.mergeUndirectedEdge:this.mergeDirectedEdge:c?this.addUndirectedEdge:this.addDirectedEdge,l.call(this,t,i,o))}}return this}nullCopy(t){let n=new e(yb({},this._options,t));return n.replaceAttributes(yb({},this.getAttributes())),n}emptyCopy(e){let t=this.nullCopy(e);return this._nodes.forEach((e,n)=>{let r=yb({},e.attributes);e=new t.NodeDataClass(n,r),t._nodes.set(n,e)}),t}copy(e){if(e||={},typeof e.type==`string`&&e.type!==this.type&&e.type!==`mixed`)throw new jb(`Graph.copy: cannot create an incompatible copy from "${this.type}" type to "${e.type}" because this would mean losing information about the current graph.`);if(typeof e.multi==`boolean`&&e.multi!==this.multi&&e.multi!==!0)throw new jb(`Graph.copy: cannot create an incompatible copy by downgrading a multi graph to a simple one because this would mean losing information about the current graph.`);if(typeof e.allowSelfLoops==`boolean`&&e.allowSelfLoops!==this.allowSelfLoops&&e.allowSelfLoops!==!0)throw new jb(`Graph.copy: cannot create an incompatible copy from a graph allowing self loops to one that does not because this would mean losing information about the current graph.`);let t=this.emptyCopy(e),n=this._edges.values(),r,i;for(;r=n.next(),r.done!==!0;)i=r.value,eS(t,`copy`,!1,i.undirected,i.key,i.source.key,i.target.key,yb({},i.attributes));return t}toJSON(){return this.export()}toString(){return`[object Graph]`}inspect(){let e={};this._nodes.forEach((t,n)=>{e[n]=t.attributes});let t={},n={};this._edges.forEach((e,r)=>{let i=e.undirected?`--`:`->`,a=``,o=e.source.key,s=e.target.key,c;e.undirected&&o>s&&(c=o,o=s,s=c);let l=`(${o})${i}(${s})`;r.startsWith(`geid_`)?this.multi&&(n[l]===void 0?n[l]=0:n[l]++,a+=`${n[l]}. `):a+=`[${r}]: `,a+=l,t[a]=e.attributes});let r={};for(let e in this)this.hasOwnProperty(e)&&!Yx.has(e)&&typeof this[e]!=`function`&&typeof e!=`symbol`&&(r[e]=this[e]);return r.attributes=this._attributes,r.nodes=e,r.edges=t,Cb(r,`constructor`,this.constructor),r}};typeof Symbol<`u`&&(rS.prototype[Symbol.for(`nodejs.util.inspect.custom`)]=rS.prototype.inspect),Xx.forEach(e=>{[`add`,`merge`,`update`].forEach(t=>{let n=e.name(t),r=t===`add`?eS:tS;e.generateKey?rS.prototype[n]=function(i,a,o){return r(this,n,!0,(e.type||this.type)===`undirected`,null,i,a,o,t===`update`)}:rS.prototype[n]=function(i,a,o,s){return r(this,n,!1,(e.type||this.type)===`undirected`,i,a,o,s,t===`update`)}})}),Zb(rS),cx(rS),kx(rS),Vx(rS);var iS=class extends rS{constructor(e){let t=yb({type:`directed`},e);if(`multi`in t&&t.multi!==!1)throw new Ab(`DirectedGraph.from: inconsistent indication that the graph should be multi in given options!`);if(t.type!==`directed`)throw new Ab(`DirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},aS=class extends rS{constructor(e){let t=yb({type:`undirected`},e);if(`multi`in t&&t.multi!==!1)throw new Ab(`UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!`);if(t.type!==`undirected`)throw new Ab(`UndirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},oS=class extends rS{constructor(e){let t=yb({multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new Ab(`MultiGraph.from: inconsistent indication that the graph should be simple in given options!`);super(t)}},sS=class extends rS{constructor(e){let t=yb({type:`directed`,multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new Ab(`MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!`);if(t.type!==`directed`)throw new Ab(`MultiDirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},cS=class extends rS{constructor(e){let t=yb({type:`undirected`,multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new Ab(`MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!`);if(t.type!==`undirected`)throw new Ab(`MultiUndirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}};function lS(e){e.from=function(t,n){let r=new e(yb({},t.options,n));return r.import(t),r}}lS(rS),lS(iS),lS(aS),lS(oS),lS(sS),lS(cS),rS.Graph=rS,rS.DirectedGraph=iS,rS.UndirectedGraph=aS,rS.MultiGraph=oS,rS.MultiDirectedGraph=sS,rS.MultiUndirectedGraph=cS,rS.InvalidArgumentsGraphError=Ab,rS.NotFoundGraphError=$,rS.UsageGraphError=jb;var uS={eligible:{property:`--chart-site-health-eligible`,fallback:`#56b4e9`},hidden:{property:`--chart-site-health-hidden`,fallback:`#e69f00`},resource:{property:`--chart-site-health-resource`,fallback:`#d4d4d8`},redirect:{property:`--chart-site-health-redirect`,fallback:`#9aa7b8`},failed:{property:`--chart-site-health-failed`,fallback:`#d55e00`},unchecked:{property:`--chart-site-health-unchecked`,fallback:`#a1a1aa`}},dS={property:`--chart-neutral-text-dim`,fallback:`#71717a`},fS=2.5,pS=200,mS=3,hS=1.6;function gS(e){let t=pS/Math.max(pS,e);return Math.max(mS,9*t**.25)}function _S(e){return gS(e)*hS}var vS={eligible:uS.eligible,hidden:uS.hidden,resource:uS.resource,redirect:uS.redirect,failed:uS.failed,unchecked:uS.unchecked,dimmedNode:{property:`--chart-neutral-text-dim`,fallback:`#71717a`},edge:dS,edgeDimmed:{property:`--chart-neutral-text-faint`,fallback:`#52525b`},edgeActive:{property:`--chart-neutral-text`,fallback:`#a1a1aa`},label:{property:`--chart-tooltip-label`,fallback:`#e4e4e7`},background:{property:`--chart-tooltip-bg`,fallback:`#18181b`}},yS=/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i,bS=/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(?:\s*,\s*(?:0|1|0?\.\d+))?\s*\)$/;function xS(e){return yS.test(e)||bS.test(e)}var SS=50,CS=.75,wS=[{maxRatio:.2,budget:1/0},{maxRatio:.45,budget:60},{maxRatio:CS,budget:24}];function TS(e){for(let t of wS)if(e<=t.maxRatio)return t.budget;return 1}function ES(e){return Math.max(0,Math.min(1,(e.linkScoreNormalized??0)/100))}function DS(e){return e.healthState?e.healthState:ir(e)}function OS(e){switch(e){case`eligible`:return`Indexable`;case`hidden`:return`Hidden`;case`resource`:return`Not a page`;case`redirect`:return`Moved`;case`failed`:return`Broken`;case`unchecked`:return`Not checked`}}function kS(e){switch(e){case`eligible`:return`Indexable`;case`hidden`:return`Hidden or points elsewhere`;case`resource`:return`Not a page`;case`redirect`:return`Moved`;case`failed`:return`Broken`;case`unchecked`:return`Not checked`}}function AS(e){switch(e){case`eligible`:return`AI and search engines are allowed to index this page`;case`hidden`:return`This page tells them not to index it, or points them to another page`;case`resource`:return`A file rather than a page, such as a text file or a PDF. Answer engines can still read it`;case`redirect`:return`This address sends visitors to another page`;case`failed`:return`This page could not be loaded`;case`unchecked`:return`This page was found but not checked`}}function jS(e){switch(e){case`eligible`:return`●`;case`hidden`:return`◆`;case`resource`:return`▪`;case`redirect`:return`↗`;case`failed`:return`×`;case`unchecked`:return`○`}}function MS(e,t){return!!t&&e.nodeKey===t}function NS(e,t=!1,n=1){let r=gS(n),i=fS+Math.sqrt(ES(e))*(r-fS);return t?Math.max(_S(n),i):i}function PS(e,t){switch(e){case`eligible`:return t.eligible;case`hidden`:return t.hidden;case`resource`:return t.resource;case`redirect`:return t.redirect;case`failed`:return t.failed;case`unchecked`:return t.unchecked}}function FS(e){return .35+Math.min(1.65,Math.log2(Math.max(1,e)+1)*.28)}function IS(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)}function LS(e,t,n,r=null){let i=new sS({allowSelfLoops:!0}),a=new Map;for(let t of e)a.has(t.nodeKey)||a.set(t.nodeKey,t);for(let e of[...a.values()].sort((e,t)=>st(e.nodeKey,t.nodeKey))){if(!IS(e))continue;let t=DS(e),o=PS(t,n),s=jS(t),c=MS(e,r);i.addNode(e.nodeKey,{x:e.x,y:e.y,size:NS(e,c,a.size),color:o,baseColor:o,label:`${s} ${e.path||`/`}`,nodeKey:e.nodeKey,url:e.url,path:e.path,depth:e.depth,status:t,glyph:s,labelVisibility:c||e.depth===0||e.path.trim()===`/`?`visible`:`auto`,zIndex:c?2:+(e.depth===0),isRoot:c})}let o=new Set;for(let e of[...t].sort((e,t)=>st(e.edgeKey,t.edgeKey)))!o.has(e.edgeKey)&&e.targetNodeKey&&i.hasNode(e.sourceNodeKey)&&i.hasNode(e.targetNodeKey)&&(o.add(e.edgeKey),i.addDirectedEdgeWithKey(e.edgeKey,e.sourceNodeKey,e.targetNodeKey,{size:FS(e.occurrences),color:n.edge,baseColor:n.edge,followable:e.followable,occurrences:e.occurrences,isTemplate:e.isTemplate===!0,type:`line`,zIndex:0}));return{graph:i,layoutAvailable:e.length===0||i.order>0,omittedNodes:Math.max(0,e.length-i.order),omittedEdges:Math.max(0,t.length-i.size)}}function RS(e,t,n=SS){let r=t.trim().toLocaleLowerCase(),i=Math.max(0,Math.min(SS,Math.floor(n)));return[...e].sort((e,t)=>st(e.path||e.url,t.path||t.url)||st(e.nodeKey,t.nodeKey)).filter(e=>IS(e)?!r||`${e.path}\n${e.url}\n${e.nodeKey}`.toLocaleLowerCase().includes(r):!1).slice(0,i)}function zS(e,t,n,r,i=!0){let a=t&&e.hasNode(t)?t:null,o=typeof n==`function`?n:()=>n,s=e.nodes().sort((t,n)=>{let r=e.getNodeAttributes(t),i=e.getNodeAttributes(n);return Number(i.isRoot)-Number(r.isRoot)||i.size-r.size||(r.depth??2**53-1)-(i.depth??2**53-1)||st(r.path,i.path)||st(t,n)}),c=new Map(s.map((e,t)=>[e,t])),l=new Set(a?e.neighbors(a).filter(e=>e!==a).sort((e,t)=>(c.get(e)??0)-(c.get(t)??0)).slice(0,8):[]);return{nodeReducer:(t,n)=>{let i={x:n.x,y:n.y,size:n.size,color:n.color,label:n.label,labelVisibility:n.labelVisibility,zIndex:n.zIndex},s=o(),u=s>CS;if(n.isRoot)return t===a?{...i,size:n.size*1.35,labelVisibility:`visible`,zIndex:3}:{...i,labelVisibility:`visible`};if(a)return t===a?{...i,size:n.size*1.35,labelVisibility:`visible`,zIndex:3}:e.areNeighbors(t,a)?u?l.has(t)?{...i,labelVisibility:`auto`}:{...i,labelVisibility:`auto`,label:``}:i:{...i,color:r.dimmedNode,labelVisibility:`auto`,label:``,zIndex:0};let d=TS(s);return d===1/0?i:(c.get(t)??2**53-1)<d?{...i,labelVisibility:`visible`}:{...i,labelVisibility:`auto`,label:``}},edgeReducer:(t,n)=>{let s={size:n.size,color:n.color,zIndex:n.zIndex};if(n.isTemplate&&!i)return{...s,visibility:`hidden`};let c=o()>CS,[l,u]=e.extremities(t);return a&&(l===a||u===a)?{...s,color:r.edgeActive,size:Math.max(1.4,n.size),zIndex:2}:c?{...s,visibility:`hidden`}:a?{...s,color:r.edgeDimmed,size:Math.min(.45,n.size),zIndex:0}:s}}}var BS={"layout-failed":{heading:`Map could not be built`,detail:`The map could not be created for this scan. Run a new scan to try again.`},"no-crawl":{heading:`No map yet`,detail:`This scan has no map yet. Run a new scan to create one.`},"legacy-snapshot":{heading:`No map yet`,detail:`This scan has no map yet. Run a new scan to create one.`},"details-unavailable":{heading:`No map yet`,detail:`This scan has no map yet. Run a new scan to create one.`},"empty-crawl":{heading:`No pages to map`,detail:`This scan found no pages to put on a map. Run a new scan to try again.`}};function VS(e){return(e&&BS[e])??BS[`no-crawl`]}var HS=class extends Z.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){console.error(`[SiteGraphSigma] the map failed to render`,e,t.componentStack),$e({kind:`render`,error:e,component:`site-graph`})}componentDidUpdate(e){this.state.failed&&e.resetToken!==this.props.resetToken&&this.setState({failed:!1})}render(){return this.state.failed?this.props.fallback:this.props.children}},US=220;function WS(){return typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches?0:US}function GS(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function KS(e,t,n){let r=window.getComputedStyle(e).getPropertyValue(t).trim();if(r&&!r.includes(`var(`)&&xS(r))return r;let i=document.createElement(`span`);i.style.position=`absolute`,i.style.visibility=`hidden`,i.style.color=`var(${t})`,e.appendChild(i);let a=window.getComputedStyle(i).color.trim();return i.remove(),a&&!a.includes(`var(`)&&xS(a)?a:n}function qS(e){let t=t=>{let n=vS[t];return KS(e,n.property,n.fallback)};return{eligible:t(`eligible`),hidden:t(`hidden`),resource:t(`resource`),redirect:t(`redirect`),failed:t(`failed`),unchecked:t(`unchecked`),dimmedNode:t(`dimmedNode`),edge:t(`edge`),edgeDimmed:t(`edgeDimmed`),edgeActive:t(`edgeActive`),label:t(`label`),background:t(`background`)}}function JS(){if(typeof document>`u`)return!1;try{return!!document.createElement(`canvas`).getContext(`webgl2`)}catch{return!1}}function YS({onOpenInventory:e}){return(0,Q.jsx)(`div`,{className:`flex h-full min-h-80 items-center justify-center px-6 text-center`,children:(0,Q.jsxs)(`div`,{className:`max-w-md`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:`Interactive map unavailable`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`This browser could not start WebGL. The page inventory remains available for the complete crawl.`}),e&&(0,Q.jsx)(q,{type:`button`,variant:`secondary`,size:`sm`,className:`mt-4`,onClick:e,children:`Open page inventory`})]})})}function XS({onRetry:e}){return(0,Q.jsx)(`div`,{className:`flex h-full min-h-80 items-center justify-center px-6 text-center`,role:`alert`,children:(0,Q.jsxs)(`div`,{className:`max-w-md`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:`The map could not be drawn`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Something went wrong while drawing this map. The page inventory below is unaffected.`}),(0,Q.jsx)(q,{variant:`secondary`,size:`sm`,className:`mt-4`,onClick:e,children:`Try again`})]})})}function ZS({setReducers:e,reactSigma:t,graph:n,theme:r,selectedNodeKey:i,showTemplateLinks:a,onSelectNodeKey:o,onHoverNode:s,onCameraReady:c}){let{useSigma:l,useRegisterEvents:u,useCamera:d}=t,f=l(),p=u(),{zoomIn:m,zoomOut:h,reset:g,gotoNode:_}=d(),[v,y]=(0,Z.useState)(null),b=v??i,x=(0,Z.useRef)(null),S=(0,Z.useRef)({overview:!0,budget:NaN});return(0,Z.useEffect)(()=>()=>{x.current!==null&&cancelAnimationFrame(x.current)},[]),(0,Z.useEffect)(()=>{let e=WS();return c({zoomIn:()=>m({duration:e}),zoomOut:()=>h({duration:e}),reset:()=>g({duration:e}),gotoNode:t=>_(t,{duration:e})}),()=>c(null)},[_,c,g,m,h]),(0,Z.useEffect)(()=>{p({enterNode:({node:e,event:t})=>{y(e),s({nodeKey:e,left:Number.isFinite(t.x)?t.x+14:20,top:Number.isFinite(t.y)?t.y+14:20})},leaveNode:()=>{y(null),s(null)},clickNode:({node:e})=>o(e),clickStage:()=>s(null),updated:()=>{x.current===null&&(x.current=requestAnimationFrame(()=>{x.current=null;let e=f.getCamera().getState().ratio>CS,t=TS(f.getCamera().getState().ratio);(e!==S.current.overview||t!==S.current.budget)&&(S.current={overview:e,budget:t},f.refresh())}))}})},[s,o,p,f]),(0,Z.useEffect)(()=>{if(f.getGraph()!==n)return;e(zS(n,b,()=>f.getCamera().getState().ratio,r,a));let t=f.getCamera().getState().ratio;S.current={overview:t>CS,budget:TS(t)},f.refresh()},[b,n,a,f,r,e]),null}function QS({nodes:e,edges:t,layoutState:n=`ready`,layoutUnavailableReason:r,rootNodeKey:a=null,showTemplateLinks:s=!0,selectedNodeKey:c,onSelectNode:l,onOpenInventory:d,ariaLabel:f,className:p}){let m=(0,Z.useRef)(null),h=(0,Z.useRef)(null),g=(0,Z.useRef)(null),_=(0,Z.useId)(),v=(0,Z.useId)(),y=(0,Z.useId)(),[b,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(`checking`),[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(null),[j,M]=(0,Z.useState)(null),[N,P]=(0,Z.useState)(``),[F,I]=(0,Z.useState)(!1),[ee,L]=(0,Z.useState)(0),[R,z]=(0,Z.useState)(``),[te,ne]=(0,Z.useState)(0),B=(0,Z.useRef)(null),V=(0,Z.useDeferredValue)(N),H=c===void 0?k:c,re=(0,Z.useMemo)(()=>new Map(e.map(e=>[e.nodeKey,e])),[e]),U=(0,Z.useMemo)(()=>lb(a?re.get(a)?.url:null),[re,a]),ie=(0,Z.useCallback)(e=>hb(e,U),[U]),W=H?re.get(H)??null:null,ae=j?re.get(j.nodeKey)??null:null,oe=(0,Z.useMemo)(()=>RS(e,V),[V,e]),se=e.some(e=>Number.isFinite(e.x)&&Number.isFinite(e.y)),ce=(0,Z.useMemo)(()=>b?LS(e,t,b,a):null,[t,e,a,b]),le=(0,Z.useMemo)(()=>{if(!b||!ce)return null;let e=zS(ce.graph,null,1,b,!1);return{options:{nodeReducer:(t,n,r)=>e.nodeReducer(t,r),edgeReducer:(t,n,r)=>e.edgeReducer(t,r),settings:{allowInvalidContainer:!0,enableCameraPanning:!0,enableCameraZooming:!0,enableCameraRotation:!1,enableEdgeEvents:!1,hideEdgesOnMove:!0,hideLabelsOnMove:!0,itemSizesReference:`screen`,labelDensity:.07,labelGridCellSize:140,labelRenderedSizeThreshold:8,maxCameraRatio:12,minCameraRatio:.04,minEdgeThickness:.35,renderEdgeLabels:!1,renderLabels:!0,stagePadding:42},styles:{nodes:{x:{attribute:`x`},y:{attribute:`y`},size:{attribute:`size`},label:{attribute:`label`},depth:{whenState:`isHovered`,then:`topNodes`,else:`nodes`},visibility:`visible`,backdropVisibility:{whenState:`isHovered`,then:`visible`,else:`hidden`},color:{attribute:`color`,defaultValue:b.unchecked},labelColor:b.label,labelFont:`600 Geist Variable, Geist, sans-serif`,labelSize:13,labelPosition:`right`,backdropColor:b.background,backdropBorderColor:b.edgeActive,backdropBorderWidth:1.5,backdropPadding:3,backdropCornerRadius:5,backdropLabelPadding:8},edges:{size:{attribute:`size`},depth:`edges`,visibility:`visible`,color:{attribute:`color`,defaultValue:b.edge},path:`straight`}}},setReducers:t=>{e=t}}},[ce,b]);(0,Z.useEffect)(()=>{let e=m.current;if(!e)return;let t=()=>S(qS(e));if(t(),typeof MutationObserver>`u`)return;let n=new MutationObserver(t);return n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`,`data-theme`,`style`]}),()=>n.disconnect()},[]),(0,Z.useEffect)(()=>{e.length===0||n===`unavailable`||!se?E(`checking`):E(JS()?`ready`:`unavailable`)},[se,n,e.length]),(0,Z.useEffect)(()=>{if(T!==`ready`){w(null);return}let e=!0;return wr(()=>import(`./react-sigma_core.esm.min-DHJ5hJS1.js`).then(t=>{e&&w(t)}),__vite__mapDeps([0,1,2]),import.meta.url).catch(()=>{e&&E(`unavailable`)}),()=>{e=!1}},[T]),(0,Z.useEffect)(()=>{L(0)},[V]);let ue=(0,Z.useCallback)(e=>{g.current=e,O(!!e)},[]),de=(0,Z.useCallback)(e=>{M(e)},[]),fe=(0,Z.useCallback)((e,t)=>{let n=re.get(e);n&&(c===void 0&&A(e),l?.(n),t&&g.current?.gotoNode(e),z(`Focused ${ie(n)}`))},[re,l,ie,c]),pe=(0,Z.useCallback)(e=>{fe(e,!1)},[fe]);(0,Z.useEffect)(()=>{!D||!c||!re.has(c)?c||(B.current=null):B.current!==c&&(g.current?.gotoNode(c),B.current=c)},[D,re,c]);let me=e=>{fe(e.nodeKey,!0),P(ie(e)),I(!1)},he=()=>{window.setTimeout(()=>{document.activeElement!==h.current&&I(!1)},0)},ge=(0,Z.useMemo)(()=>s?t.length:t.filter(e=>e.isTemplate!==!0).length,[t,s]),_e=`Interactive site map showing ${GS(e.length,`page`)} and ${GS(ge,`internal link`)}`,ve=e=>`${v}-${e.replaceAll(/[^\w-]/g,`-`)}`,ye=VS(r);if(n===`unavailable`)return(0,Q.jsx)(`section`,{ref:m,role:`group`,"aria-label":f??_e,className:Xt(`flex min-h-80 items-center justify-center material-base px-6 text-center`,p),children:(0,Q.jsxs)(`div`,{className:`max-w-md`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:ye.heading}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:ye.detail}),d&&(0,Q.jsx)(q,{type:`button`,variant:`secondary`,size:`sm`,className:`mt-4`,onClick:d,children:`Open page inventory`})]})});if(e.length===0)return(0,Q.jsx)(`section`,{ref:m,role:`group`,"aria-label":f??_e,className:Xt(`flex min-h-80 items-center justify-center material-base px-6 text-center`,p),children:(0,Q.jsxs)(`div`,{className:`max-w-md`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No page graph is available for this scan.`}),d&&(0,Q.jsx)(q,{type:`button`,variant:`secondary`,size:`sm`,className:`mt-4`,onClick:d,children:`Open page inventory`})]})});if(!se)return(0,Q.jsx)(`section`,{ref:m,role:`group`,"aria-label":f??_e,className:Xt(`flex min-h-80 items-center justify-center material-base px-6 text-center`,p),children:(0,Q.jsxs)(`div`,{className:`max-w-md`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:ye.heading}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:ye.detail}),d&&(0,Q.jsx)(q,{type:`button`,variant:`secondary`,size:`sm`,className:`mt-4`,onClick:d,children:`Open page inventory`})]})});let be=oe.at(ee),xe=(0,Q.jsx)(XS,{onRetry:()=>ne(e=>e+1)}),Se=C?.SigmaContainer;return(0,Q.jsxs)(`section`,{ref:m,role:`group`,"aria-label":f??_e,"aria-describedby":y,className:Xt(`flex h-[clamp(460px,62vh,680px)] min-h-[460px] flex-col overflow-hidden material-base`,p),children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 border-b border-subtle bg-bg-elevated/70 px-3 py-2`,children:[(0,Q.jsx)(`label`,{htmlFor:_,className:`sr-only`,children:`Focus a page in the site map`}),(0,Q.jsxs)(`div`,{className:`relative min-w-56 max-w-lg flex-1`,children:[(0,Q.jsx)(x,{className:`pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted`,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{id:_,ref:h,role:`combobox`,type:`search`,autoComplete:`off`,"aria-label":`Focus a page in the site map`,"aria-autocomplete":`list`,"aria-controls":v,"aria-expanded":F,"aria-activedescendant":F&&be?ve(be.nodeKey):void 0,value:N,placeholder:W?`Focused: ${ie(W)}`:`Find a page`,className:`h-10 w-full rounded-md border border-base bg-bg py-2 pl-9 pr-3 text-label-14 text-primary placeholder-mono-400 outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onFocus:()=>I(!0),onBlur:he,onChange:e=>{P(e.target.value),I(!0)},onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),I(!0),L(e=>Math.max(0,Math.min(oe.length-1,e+1)))):e.key===`ArrowUp`?(e.preventDefault(),L(e=>Math.max(0,e-1))):e.key===`Enter`&&F&&be?(e.preventDefault(),me(be)):e.key===`Escape`&&I(!1)}}),F&&(0,Q.jsxs)(`div`,{className:`absolute left-0 right-0 top-[calc(100%+0.25rem)] z-30 overflow-hidden material-menu`,children:[(0,Q.jsx)(`div`,{id:v,role:`listbox`,"aria-label":`Matching pages`,className:`max-h-72 overflow-auto py-1`,children:oe.length>0?oe.map((e,t)=>{let n=DS(e);return(0,Q.jsxs)(`button`,{id:ve(e.nodeKey),type:`button`,role:`option`,"aria-selected":t===ee,tabIndex:-1,className:Xt(`flex min-h-11 w-full items-center justify-between gap-3 px-3 py-2 text-left text-button-14 outline-none`,t===ee?`bg-surface-active text-primary`:`text-secondary hover:bg-surface-hover hover:text-primary`),onPointerDown:e=>e.preventDefault(),onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>L(t),onClick:()=>me(e),children:[(0,Q.jsx)(`span`,{className:`min-w-0 truncate font-mono`,children:ie(e)}),(0,Q.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1.5 text-label-13 text-muted`,children:[(0,Q.jsx)(`span`,{className:`text-label-13-mono-strong`,style:{color:`var(${uS[n].property})`},"aria-hidden":`true`,children:jS(n)}),(0,Q.jsx)(`span`,{title:AS(n),children:OS(n)})]})]},e.nodeKey)}):(0,Q.jsx)(`p`,{className:`px-3 py-4 text-copy-14 text-secondary`,children:`No rendered pages match.`})}),oe.length===50&&(0,Q.jsx)(`p`,{className:`border-t border-subtle px-3 py-2 text-copy-13 text-muted`,children:`First 50 matches. Refine the search or use the full page inventory.`})]})]}),(0,Q.jsx)(`span`,{className:`text-label-13 tabular-nums text-muted`,children:`${GS(e.length,`page`)} on the map · ${GS(ge,`link`)} shown`})]}),(0,Q.jsx)(`div`,{className:`relative min-h-0 flex-1 overflow-hidden`,children:T===`unavailable`?(0,Q.jsx)(YS,{onOpenInventory:d}):T===`checking`||!b||!ce||!le||!C||!Se?(0,Q.jsx)(`div`,{className:`flex h-full min-h-80 items-center justify-center px-6 text-center`,role:`status`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Preparing the interactive site map…`})}):(0,Q.jsxs)(HS,{fallback:xe,resetToken:te,children:[(0,Q.jsx)(`div`,{"aria-hidden":`true`,className:`absolute inset-0`,children:(0,Q.jsx)(Se,{graph:ce.graph,className:`relative size-full bg-bg [&_.sigma-container]:size-full`,style:{width:`100%`,height:`100%`,background:b.background},options:le.options,children:(0,Q.jsx)(ZS,{setReducers:le.setReducers,reactSigma:C,graph:ce.graph,theme:b,selectedNodeKey:H,showTemplateLinks:s,onSelectNodeKey:pe,onHoverNode:de,onCameraReady:ue})})}),(0,Q.jsxs)(`div`,{className:`absolute right-3 top-3 z-20 flex flex-col overflow-hidden material-menu`,children:[(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`icon`,className:`rounded-none border-b border-subtle`,"aria-label":`Zoom in`,disabled:!D,onClick:()=>g.current?.zoomIn(),children:(0,Q.jsx)(o,{className:`size-4`,"aria-hidden":`true`})}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`icon`,className:`rounded-none border-b border-subtle`,"aria-label":`Zoom out`,disabled:!D,onClick:()=>g.current?.zoomOut(),children:(0,Q.jsx)(i,{className:`size-4`,"aria-hidden":`true`})}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`icon`,className:`rounded-none`,"aria-label":`Fit site map`,disabled:!D,onClick:()=>g.current?.reset(),children:(0,Q.jsx)(u,{className:`size-4`,"aria-hidden":`true`})})]}),ae&&j&&(0,Q.jsxs)(`div`,{role:`tooltip`,className:`pointer-events-none absolute z-20 max-w-64 material-tooltip px-3 py-2`,style:{left:j.left,top:j.top},children:[(0,Q.jsx)(`p`,{className:`truncate text-copy-13-mono-strong text-heading`,children:ie(ae)}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13-strong text-heading`,children:OS(DS(ae))}),(0,Q.jsx)(`p`,{className:`mt-0.5 text-copy-13 text-secondary`,children:AS(DS(ae))}),ae.depth!=null&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:[GS(ae.depth,`click`),` from home`]}),ae.auditScore!=null&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 tabular-nums text-heading`,children:[`Score `,Math.round(ae.auditScore),`/100`]})]})]})}),(0,Q.jsxs)(`div`,{"aria-label":`Site map legend`,className:`flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-subtle bg-bg-elevated/50 px-3 py-2 text-label-13 text-secondary`,children:[Rn.map(e=>(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,title:AS(e),children:[(0,Q.jsx)(`span`,{className:`w-3 text-center font-mono text-label-16-strong`,style:{color:`var(${uS[e].property})`},"aria-hidden":`true`,children:jS(e)}),kS(e)]},e)),(0,Q.jsx)(`span`,{className:`ml-auto`,children:`Bigger = more linked`}),ce&&(ce.omittedNodes>0||ce.omittedEdges>0)&&(0,Q.jsx)(`span`,{className:`text-caution`,children:`Some records lacked valid layout data.`})]}),(0,Q.jsx)(`p`,{id:y,className:`sr-only`,children:`The WebGL map supports pointer, wheel, and touch navigation. Use the page search to focus a rendered page. Use the full page inventory for an accessible list of every crawled page and its links.`}),(0,Q.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`sr-only`,children:R})]})}var $S={"geographic-signals":`Checks whether pages say where your business operates: your address, service areas, map coordinates, and location details that search engines can read. Useful for businesses serving specific places. Off by default; enabling it adds this check to the Agent Readiness score.`,"agent-skill-exposure":`Checks whether AI agents can understand your forms, discover actions such as site search, and find links to tools or APIs. Reads page information only; it does not submit forms or run actions. Included in the Agent Readiness score by default.`};function eC(e){switch(e.field){case`faq-answer`:return e.question?`FAQ answer to “${e.question}”`:`FAQ answer`;case`faq-question`:return`FAQ`;case`title`:return`Title`;case`h1`:return`H1`;default:return`Page text`}}function tC(e,t){return`Worth ${Ut(e,Je.percent)} of the ${t} score`}function nC(e){return e>=70?`positive`:e>=40?`caution`:`negative`}function rC(e){return e>=70?`pass`:e>=40?`partial`:`fail`}function iC(e){return e===`pass`?`positive`:e===`partial`?`caution`:`negative`}function aC(e){return e===`pass`?`Pass`:e===`partial`?`Partial`:`Fail`}function oC({audit:e,isLoading:t,error:n,onRetry:r}){return(0,Q.jsxs)(`section`,{className:`border-t border-default pt-5`,"aria-labelledby":`site-health-page-audit-heading`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{id:`site-health-page-audit-heading`,className:`text-heading-16 text-heading`,children:`Findings and fixes for this page`})}),t?(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,role:`status`,children:`Loading findings…`}):n?(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center justify-between gap-3 border-y border-negative bg-negative-soft px-4 py-3`,role:`alert`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative`,children:`Findings could not be loaded.`}),(0,Q.jsx)(q,{type:`button`,variant:`secondary`,size:`sm`,onClick:r,children:`Try again`})]}):e?e.state===`no-crawl`?(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:`No Agent Readiness audit scan is available.`}):e.state===`details-unavailable`?(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:`This scan saved its summary, but not the findings for each page.`}):e.state===`not-found`?(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:`This page is not present in the selected scan.`}):e.state===`not-audited`?(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:e.auditState===`url-version`?`This address is a URL version of another page, so it was not scored.`:`This page was found, but it was not scored.`}):(0,Q.jsx)(sC,{audit:e}):(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:`No findings are available for this page.`})]})}function sC({audit:e}){let t=e.factors.filter(e=>e.applicable!==!1&&(e.status!==`pass`||e.findings.some(e=>e.type===`missing`||e.type===`timeout`||e.type===`unreachable`)));return(0,Q.jsxs)(`div`,{className:`mt-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[(0,Q.jsxs)(`span`,{"aria-label":`Score ${Math.round(e.auditScore)} out of 100`,className:`text-heading-24 tabular-nums text-heading`,children:[Math.round(e.auditScore),(0,Q.jsx)(`span`,{className:`text-label-14 text-muted`,children:`/100`})]}),(0,Q.jsx)(J,{tone:nC(e.auditScore),children:aC(rC(e.auditScore))})]}),e.evidenceState===`scores-only`&&(0,Q.jsx)(`p`,{className:`mt-3 border border-caution bg-caution-soft px-3 py-2 text-copy-14 text-caution`,children:`This older scan saved only the scores, not the findings or fixes.`}),e.criticalDefects.length>0&&(0,Q.jsxs)(`section`,{className:`mt-5`,"aria-labelledby":`site-health-critical-defects-heading`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(`h4`,{id:`site-health-critical-defects-heading`,className:`text-heading-14 text-heading`,children:`Problems outside the score`}),(0,Q.jsx)(J,{tone:e.criticalDefects.some(e=>e.severity===`critical`)?`negative`:`caution`,children:e.criticalDefects.length}),(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:`Not counted in the score`})]}),(0,Q.jsx)(`ul`,{className:`mt-2 divide-y divide-default border-y border-default`,children:e.criticalDefects.map(e=>(0,Q.jsxs)(`li`,{className:`py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:e.detail}),(0,Q.jsx)(J,{tone:e.severity===`critical`?`negative`:`caution`,children:e.severity===`critical`?`Critical`:`Warning`})]}),(e.evidence??[]).length>0&&(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1.5`,"aria-label":`Where the page names it`,children:(e.evidence??[]).map((e,t)=>(0,Q.jsxs)(`li`,{className:`text-copy-14 text-secondary`,children:[(0,Q.jsx)(`span`,{className:`text-copy-14-strong text-heading`,children:eC(e)}),` `,(0,Q.jsx)(`q`,{className:`[overflow-wrap:anywhere]`,children:e.snippet})]},`${e.field}-${t}`))}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[(0,Q.jsx)(`span`,{className:`text-copy-14-strong text-heading`,children:`Fix:`}),` `,e.recommendation]})]},e.id))})]}),t.length>0?(0,Q.jsx)(`div`,{className:`mt-5 divide-y divide-default border-y border-default`,children:t.map(t=>(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Q.jsxs)(`details`,{className:`group min-w-0 flex-1 py-1`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-12 cursor-pointer list-none items-center justify-between gap-3 rounded-sm px-1 py-2 outline-none marker:hidden focus-visible:ring-2 focus-visible:ring-mono-400 [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 text-label-14-strong text-heading`,children:[(0,Q.jsx)(m,{className:`size-4 shrink-0 text-muted transition-transform group-open:rotate-90`,"aria-hidden":`true`}),t.name]}),(0,Q.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Q.jsxs)(`span`,{className:`text-label-14 tabular-nums text-heading`,children:[Math.round(t.score),`/100`]}),(0,Q.jsx)(J,{tone:iC(t.status),children:aC(t.status)})]})]}),(0,Q.jsxs)(`div`,{className:`grid gap-4 px-1 pb-4 pt-1 md:grid-cols-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h5`,{className:`text-heading-14 normal-case text-muted`,children:`Evidence`}),t.findings.length>0?(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1.5 text-label-14 text-secondary`,children:t.findings.map((e,t)=>(0,Q.jsx)(`li`,{children:e.message},`${e.code}:${t}`))}):(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:e.evidenceState===`scores-only`?`This scan did not save the findings here.`:`Nothing to report here.`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h5`,{className:`text-heading-14 normal-case text-muted`,children:`Recommended fix`}),t.recommendations.length>0?(0,Q.jsx)(`ol`,{className:`mt-2 list-decimal space-y-1.5 pl-5 text-label-14 text-secondary marker:text-muted`,children:t.recommendations.map(e=>(0,Q.jsx)(`li`,{children:e},e))}):(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:e.evidenceState===`scores-only`?`This scan did not save a fix here.`:`No fix suggested here.`}),typeof t.sharePct==`number`?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-muted`,children:tC(t.sharePct,`page`)}):null]})]})]}),$S[t.id]&&(0,Q.jsx)(`div`,{className:`flex min-h-14 items-center`,children:(0,Q.jsx)(X,{text:$S[t.id],placement:`bottom`})})]},t.id))}):e.criticalDefects.length===0&&e.evidenceState===`complete`?(0,Q.jsx)(`p`,{className:`mt-4 border-y border-positive bg-positive-soft px-4 py-3 text-copy-14 text-positive`,children:`Nothing needs attention on this page.`}):e.criticalDefects.length===0?(0,Q.jsx)(`p`,{className:`mt-4 border-y border-default px-4 py-3 text-copy-14 text-secondary`,children:`This scan saved only the score. Run a new scan to see findings.`}):null]})}var cC=`Not recorded by this scan`,lC=`Not compared with the previous scan, because it scored different sites.`,uC=100,dC=12,fC=[];function pC(e){return Xl(e.url)}function mC(e){return e>=70?`positive`:e>=40?`caution`:`negative`}function hC(e){return e>=70?`text-positive-400`:e>=40?`text-caution-400`:`text-negative-400`}function gC(e){return e===Zn.pass?`positive`:e===Zn.partial?`caution`:`negative`}var _C={[Zn.pass]:`Pass`,[Zn.partial]:`Partial`,[Zn.fail]:`Fail`},vC=`Score is the check's average across scored pages. Worst page is the band of its lowest-scoring page: Fail below 40, Partial 40 to 69, Pass 70 or more. Pages affected counts pages below 70. Checks are listed worst first.`,yC=`Score is the average across audited pages. Status reflects the worst page: fail if any page scores below 40, partial if any page scores 40–69, otherwise pass. Share is how much of the site score the factor controls; the shares add up to 100%, and a dash means the scan did not record them.`,bC={[Zn.fail]:0,[Zn.partial]:1,[Zn.pass]:2};function xC(e){return e.pagesPartial+e.pagesFailing}function SC(e){return[...e].sort((e,t)=>bC[e.status]-bC[t.status]||xC(t)-xC(e)||e.avgScore-t.avgScore)}function CC(e){return e>=70?`Pass`:e>=40?`Partial`:`Fail`}function wC(e){return Xr(Gr(String(e)))}function TC(e){return Ur(Gr(String(e)))}function EC({projectName:e,projectId:t,runId:n,integrated:r=!1}){let{isAdmin:i}=si(),a=wn(Qt[`site-audit`])&&!i,[o,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),h=n===void 0?f:n,[g,v]=(0,Z.useState)(!1),y=(0,Z.useRef)(null),x=W(wo({client:Y,path:{name:e},...h?{query:{runId:h}}:{}})),S=W({...wi({client:Y,path:{name:e},query:{limit:30}}),enabled:!r}),C=W({...To({client:Y,path:{name:e},query:{surface:`site-health`}}),enabled:r}),w=W(jo({client:Y,path:{name:e},query:{limit:uC,sort:`score-asc`,...h?{runId:h}:{}}})),T=W({...Fi({client:Y,path:{name:e},query:{kind:Qt[`site-audit`],limit:10}}),enabled:!r,refetchOnWindowFocus:`always`,refetchInterval:e=>e.state.data?.some(e=>e.status===`queued`||e.status===`running`)?3e3:1e4}),E=Ec(),D=(0,Z.useSyncExternalStore)(Qs,js,js),k=Object.values(D.runs).find(e=>e.kind===Qt[`site-audit`]&&e.projectId===t),A=T.data??[],M=A.find(e=>e.status===`queued`||e.status===`running`),N=A.at(-1),P=E.isPending||!!k||!!M,F=E.isPending?`starting`:M?.status??k?.lastAnnouncedStatus,I=(0,Z.useCallback)(async()=>{r&&C.refetch();let e=await Promise.all([x.refetch(),w.refetch(),...r?[]:[S.refetch()]]),t=e.find(e=>e.error);if(t?.error)throw t.error;return e[0]},[r,w.refetch,x.refetch,S.refetch,C.refetch]);(0,Z.useEffect)(()=>{r||h||!N||N.status!==`completed`&&N.status!==`partial`||x.data?.runId!==N.id&&y.current!==N.id&&(y.current=N.id,I().catch(t=>{li({title:`Agent Readiness auto-refresh failed`,detail:t instanceof Error?t.message:`Could not load the completed scan.`,tone:`negative`,dedupeKey:`technical-aeo:auto-refresh:${e}`,dedupeMode:`replace`})}))},[h,r,N?.id,N?.status,e,I,x.data?.runId]);let ee=async()=>{v(!0);try{let t=await I();li({title:`Agent Readiness refreshed`,detail:P?`The scan is still running. This view will refresh again when it finishes.`:t.data?.hasData?`Latest score is ${t.data.aggregateScore}/100 from ${t.data.pagesAudited} audited page${t.data.pagesAudited===1?``:`s`}.`:`No scan data yet. Run a scan to crawl the sitemap.`,tone:t.data?.hasData?`positive`:`caution`,dedupeKey:`technical-aeo:refresh:${e}`,dedupeMode:`replace`})}catch(t){li({title:`Agent Readiness refresh failed`,detail:t instanceof Error?t.message:`Could not reload Agent Readiness data.`,tone:`negative`,dedupeKey:`technical-aeo:refresh:${e}`,dedupeMode:`replace`})}finally{v(!1)}},L=()=>{(!wn(Qt[`site-audit`])||i)&&E.mutate({projectName:e,projectId:t})},R=F===`running`?`Scan running`:F===`queued`?`Scan queued`:`Starting scan`,z=x.data,te=w.data?.pages??fC,ne=(z?.pagesErrored??0)>0,B=o&&ne,V=$l({rows:(0,Z.useMemo)(()=>B?te.filter(e=>e.status===`error`):te,[te,B]),getSearchText:pC}),H=z?z.pagesAudited>te.length:!1;if((0,Z.useEffect)(()=>{c(!1),u(null)},[h,r]),x.isLoading)return(0,Q.jsxs)(`div`,{className:`flex min-h-40 items-center justify-center gap-2 text-label-14 text-secondary ${r?``:`mt-6`}`,role:`status`,children:[(0,Q.jsx)(s,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading score…`]});if(x.error)return(0,Q.jsxs)(`section`,{className:`flex flex-col gap-4 rounded-md border border-negative bg-negative-soft px-5 py-5 sm:flex-row sm:items-center sm:justify-between ${r?``:`mt-6`}`,role:`alert`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 gap-3`,children:[(0,Q.jsx)(O,{className:`mt-0.5 size-4 shrink-0 text-negative`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{children:[r?(0,Q.jsx)(`h3`,{className:`text-heading-14 text-negative`,children:`Score could not load`}):(0,Q.jsx)(`h2`,{className:`text-heading-14 text-negative`,children:`Score could not load`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`The saved scan could not be read. Try loading it again.`})]})]}),(0,Q.jsxs)(q,{type:`button`,variant:`secondary`,size:`sm`,className:`shrink-0`,onClick:()=>void ee(),disabled:g,children:[(0,Q.jsx)(_,{className:`size-4 ${g?`motion-safe:animate-spin`:``}`,"aria-hidden":`true`}),g?`Trying again…`:`Try again`]})]});if(!z||!z.hasData)return r?(0,Q.jsxs)(`section`,{className:`material-base px-5 py-7 text-center`,children:[(0,Q.jsx)(b,{className:`mx-auto size-7 text-muted`,"aria-hidden":`true`}),(0,Q.jsx)(`h2`,{className:`mt-3 text-heading-16 text-heading`,children:`Score unavailable`}),(0,Q.jsx)(`p`,{className:`mx-auto mt-2 max-w-md text-copy-14 text-secondary`,children:a?tc:`Run a new Agent Readiness audit scan to calculate page-level findings.`})]}):(0,Q.jsxs)(Cs,{className:`surface-card mt-6 p-8 text-center`,children:[(0,Q.jsx)(b,{className:`mx-auto mb-3 h-8 w-8 text-muted`,"aria-hidden":`true`}),(0,Q.jsx)(`h2`,{className:`text-heading-16 text-heading`,children:`No Agent Readiness audit scan yet`}),(0,Q.jsx)(`p`,{className:`supporting-copy mx-auto mt-2 max-w-md`,children:`An Agent Readiness audit scan crawls your sitemap and scores every page for structured data, AI-readable content, crawler access, freshness, and more, then rolls it up into one Agent Readiness score.`}),!K()&&!a&&(0,Q.jsx)(`div`,{className:`mt-5 flex items-center justify-center gap-3`,children:(0,Q.jsxs)(fs,{type:`button`,onClick:L,disabled:P,children:[P?(0,Q.jsx)(s,{className:`mr-1.5 h-4 w-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(j,{className:`mr-1.5 h-4 w-4`,"aria-hidden":`true`}),P?R:`Run first scan`]})}),P?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-muted`,role:`status`,"aria-live":`polite`,children:`The dashboard will refresh automatically when the scan finishes.`}):null]});let re=z.deltaScore==null?null:`${z.deltaScore>=0?`+`:``}${z.deltaScore} vs previous`,U=z.trend===`up`?`positive`:z.trend===`down`?`negative`:`neutral`,ie=re?(0,Q.jsx)(J,{tone:U,children:re}):z.deltaUnavailableReason===`sites-changed`?(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Q.jsx)(J,{tone:`neutral`,children:`Sites changed`}),(0,Q.jsx)(X,{text:lC})]}):null,ae=S.data?.points??[],se=ae.map(e=>({runId:e.runId,date:e.auditedAt,score:e.aggregateScore})),ce=n===void 0&&f!==null,de=te.filter(e=>e.status===`success`),fe=z.factors.filter(e=>xC(e)>0).length,pe=z.runStatus===`partial`,me=z.crossCuttingIssues.some(e=>e.topRecommendations.length>0);function ye(e){let t=[];for(let n of de){let r=n.factors.find(t=>t.id===e);r&&r.score<70&&t.push({url:n.url,score:r.score})}return t.sort((e,t)=>e.score-t.score)}return(0,Q.jsxs)(`div`,{className:r?``:`mt-6`,children:[r?(0,Q.jsxs)(`section`,{className:`flex flex-col gap-3 border-b border-default pb-5 sm:flex-row sm:items-end sm:justify-between`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:pe?`Score so far`:`Agent Readiness score`}),(0,Q.jsxs)(`div`,{className:`mt-1 flex flex-wrap items-center gap-2`,children:[(0,Q.jsxs)(`span`,{"aria-label":pe?`Score so far ${z.aggregateScore} out of 100, from a scan that did not cover the whole site`:`Agent Readiness score ${z.aggregateScore} out of 100`,className:`inline-flex items-baseline gap-1 font-mono tabular-nums ${hC(z.aggregateScore)}`,children:[(0,Q.jsx)(`span`,{className:`text-heading-32`,children:z.aggregateScore}),(0,Q.jsx)(`span`,{className:`text-label-14 text-muted`,children:`/100`})]}),(0,Q.jsx)(J,{tone:mC(z.aggregateScore),children:CC(z.aggregateScore)}),pe?(0,Q.jsx)(J,{tone:`caution`,children:`Part of the site`}):null,ie]}),(z.sites?.length??0)>1&&(0,Q.jsxs)(`details`,{className:`group mt-3`,children:[(0,Q.jsxs)(`summary`,{className:`flex w-fit cursor-pointer list-none items-center gap-1 rounded-sm text-button-14 text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400`,children:[(0,Q.jsx)(m,{className:`size-3.5 transition-transform group-open:rotate-90`,"aria-hidden":`true`}),`By site`]}),(0,Q.jsxs)(`table`,{className:`mt-2 w-full max-w-xl text-left`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`py-1 pr-4 text-left text-label-12-strong text-muted`,children:`Site`}),(0,Q.jsx)(`th`,{scope:`col`,className:`py-1 pr-4 text-right text-label-12-strong text-muted`,children:`Score`}),(0,Q.jsx)(`th`,{scope:`col`,className:`py-1 text-right text-label-12-strong text-muted`,children:`Pages scored`})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-default border-t border-default`,children:(z.sites??[]).map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,className:`py-2 pr-4 text-left text-label-14-mono text-heading`,children:e.host}),e.aggregateScore===null?(0,Q.jsx)(`td`,{className:`py-2 pr-4 text-right text-label-14 text-secondary`,children:`Not scored`}):(0,Q.jsx)(`td`,{className:`py-2 pr-4 text-right text-label-14-mono-strong tabular-nums ${hC(e.aggregateScore)}`,children:e.aggregateScore}),(0,Q.jsx)(`td`,{className:`py-2 text-right text-label-14 tabular-nums text-secondary`,children:e.pagesAudited.toLocaleString()})]},e.host))})]})]})]}),(0,Q.jsxs)(`p`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-copy-14 tabular-nums text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[z.pagesAudited,` page`,z.pagesAudited===1?``:`s`,` scored`]}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-faint`,children:`·`}),(0,Q.jsxs)(`span`,{children:[fe,` check`,fe===1?``:`s`,` with pages below pass`]}),z.pagesErrored>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-faint`,children:`·`}),(0,Q.jsxs)(`span`,{className:`text-negative`,children:[z.pagesErrored,` crawl error`,z.pagesErrored===1?``:`s`]})]}):null]})]}):(0,Q.jsxs)(`section`,{className:`surface-card flex flex-wrap items-start justify-between gap-6 material-base p-6`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:ce?`Agent Readiness history`:`Agent Readiness`}),(0,Q.jsxs)(`div`,{className:`mt-1 flex flex-wrap items-baseline gap-3`,children:[(0,Q.jsx)(`span`,{className:`text-heading-40 tabular-nums ${hC(z.aggregateScore)}`,children:z.aggregateScore}),(0,Q.jsx)(`span`,{className:`text-label-18 text-muted`,children:`/ 100`}),(0,Q.jsx)(J,{tone:mC(z.aggregateScore),children:CC(z.aggregateScore)}),ie,P?(0,Q.jsx)(J,{tone:`neutral`,children:R}):null]}),(0,Q.jsxs)(`p`,{className:`supporting-copy mt-2 tabular-nums`,children:[z.pagesDiscovered,` URL`,z.pagesDiscovered===1?``:`s`,` in sitemap · `,z.pagesAudited,` audited · `,z.pagesSkipped,` skipped · `,z.pagesErrored,` errored`]}),(0,Q.jsxs)(`p`,{className:`mt-1 flex flex-wrap items-center gap-x-1.5 text-copy-13 text-muted`,children:[(0,Q.jsx)(`span`,{className:`text-faint`,children:`Sitemap:`}),(0,Q.jsx)(`a`,{href:z.sitemapUrl??`#`,target:`_blank`,rel:`noreferrer`,className:`max-w-[22rem] truncate text-secondary underline decoration-mono-700 underline-offset-2 hover:text-strong`,children:z.sitemapUrl}),(0,Q.jsx)(X,{text:"Every scan 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 agent-readiness run <project> --sitemap-url <url>`."})]}),z.auditedAt?(0,Q.jsxs)(`p`,{className:`mt-0.5 text-copy-13 text-faint`,children:[`Scanned `,new Date(z.auditedAt).toLocaleString()]}):null,P?(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-muted`,role:`status`,"aria-live":`polite`,children:`Results refresh automatically when this scan finishes.`}):null]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[n===void 0&&ae.length>1?(0,Q.jsxs)(`select`,{"aria-label":`View an Agent Readiness audit scan`,value:f??``,onChange:e=>p(e.target.value||null),className:`min-h-11 rounded-md border border-base bg-bg px-3 text-label-14 text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600`,children:[(0,Q.jsx)(`option`,{value:``,children:`Latest Agent Readiness audit scan`}),[...ae].reverse().slice(1).map(e=>(0,Q.jsxs)(`option`,{value:e.runId,children:[new Date(e.auditedAt).toLocaleDateString(),` · `,e.aggregateScore,`/100`]},e.runId))]}):null,(0,Q.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>void ee(),disabled:g,children:[(0,Q.jsx)(_,{className:`mr-1.5 h-4 w-4 ${g?`motion-safe:animate-spin`:``}`,"aria-hidden":`true`}),g?`Refreshing…`:`Refresh`]}),!K()&&!a&&(0,Q.jsxs)(fs,{type:`button`,size:`sm`,onClick:L,disabled:P,children:[P?(0,Q.jsx)(s,{className:`mr-1.5 h-4 w-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(j,{className:`mr-1.5 h-4 w-4`,"aria-hidden":`true`}),P?R:`Re-run scan`]})]})]}),r?(0,Q.jsx)(DC,{trend:C.data}):null,!r&&se.length>=2?(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsxs)(`div`,{className:`section-head`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Trend`}),(0,Q.jsx)(`h2`,{children:`Agent Readiness score over time`})]}),(0,Q.jsxs)(`div`,{className:`mt-3 h-56`,children:[(0,Q.jsxs)(`p`,{className:`sr-only`,children:[`Agent Readiness scores range from `,Math.min(...se.map(e=>e.score)),` to `,Math.max(...se.map(e=>e.score)),` across `,se.length,` scans. Use the scan selector to inspect a previous scorecard.`]}),(0,Q.jsx)(`div`,{className:`h-full`,"aria-hidden":`true`,children:(0,Q.jsx)(le,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(ve,{data:se,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(oe,{stroke:ei,vertical:!1}),(0,Q.jsx)(ue,{dataKey:`date`,tick:Zr,tickLine:!1,axisLine:{stroke:ni},tickFormatter:wC,minTickGap:24}),(0,Q.jsx)(ge,{domain:[0,100],ticks:[0,25,50,75,100],tick:Zr,tickLine:!1,axisLine:!1,width:32}),(0,Q.jsx)(he,{...ti,cursor:{stroke:ni,strokeWidth:1},labelFormatter:TC,formatter:e=>[`${e}/100`,`Agent Readiness score`]}),(0,Q.jsx)(_e,{type:`monotone`,dataKey:`score`,name:`score`,stroke:Qr.positive,strokeWidth:2.5,dot:{r:2.5,fill:Qr.positive,strokeWidth:0},isAnimationActive:!1})]})})})]})]}):null,(0,Q.jsxs)(`section`,{className:r?`pt-5`:`page-section-divider`,children:[r?(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Findings`}),(0,Q.jsx)(X,{text:vC})]}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:me?`Select a check to see affected pages and recommended fixes.`:`Select a check to see affected pages and score details.`})]}):(0,Q.jsxs)(`div`,{className:`section-head`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Scorecard`}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h2`,{children:`Ranking factors`}),(0,Q.jsx)(X,{text:yC})]})]}),(0,Q.jsx)(`div`,{className:`evidence-table-wrap mt-3`,children:(0,Q.jsxs)(`table`,{className:`evidence-table ${r?`min-w-[42rem]`:``}`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:r?`Check`:`Factor`}),r?null:(0,Q.jsx)(`th`,{className:`text-right`,children:`Share`}),(0,Q.jsx)(`th`,{className:`text-right`,children:r?`Score`:`Avg`}),(0,Q.jsx)(`th`,{children:r?`Worst page`:`Status`}),(0,Q.jsx)(`th`,{children:r?`Pages affected`:`Pass / Partial / Fail`})]})}),(0,Q.jsx)(`tbody`,{children:(r?SC(z.factors):z.factors).map(e=>{let t=l===e.id,n=z.crossCuttingIssues.find(t=>t.factorId===e.id),i=t?ye(e.id):[],a=xC(e),o=e.pagesPassing+a,c=!!n?.topRecommendations.length,f=c&&a>0;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:t?`bg-surface-subtle`:void 0,children:[(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`flex min-h-11 w-full items-center gap-2 text-left text-button-14 text-strong outline-none hover:text-primary focus-visible:text-primary focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-mono-400`,"aria-expanded":t,onClick:()=>u(t?null:e.id),children:[t?(0,Q.jsx)(d,{className:`size-4 shrink-0 text-muted`,"aria-hidden":`true`}):(0,Q.jsx)(m,{className:`size-4 shrink-0 text-muted`,"aria-hidden":`true`}),e.name]}),$S[e.id]&&(0,Q.jsx)(X,{text:$S[e.id],placement:`bottom`})]})}),r?null:(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-muted`,children:typeof e.sharePct==`number`?Ut(e.sharePct,Je.percent):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:Ut(null)}),(0,Q.jsx)(`span`,{className:`sr-only`,children:cC})]})}),(0,Q.jsxs)(`td`,{className:`text-right font-mono tabular-nums text-strong`,children:[e.avgScore,r?(0,Q.jsx)(`span`,{className:`text-muted`,children:`/100`}):null]}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:gC(e.status),children:_C[e.status]})}),r?(0,Q.jsxs)(`td`,{className:`tabular-nums ${a>0?`text-strong`:`text-muted`}`,children:[a,` of `,o]}):(0,Q.jsxs)(`td`,{className:`tabular-nums text-secondary`,children:[(0,Q.jsx)(`span`,{className:`text-positive-400`,children:e.pagesPassing}),` / `,(0,Q.jsx)(`span`,{className:`text-caution-400`,children:e.pagesPartial}),` / `,(0,Q.jsx)(`span`,{className:`text-negative-400`,children:e.pagesFailing})]})]}),t?(0,Q.jsx)(`tr`,{className:`bg-surface-subtle`,children:(0,Q.jsx)(`td`,{colSpan:r?4:5,className:`px-4 pb-5 pt-0`,children:(0,Q.jsxs)(`div`,{className:`grid gap-5 border-t border-subtle pt-4 ${f?`lg:grid-cols-2`:``}`,children:[c&&n?(0,Q.jsxs)(`section`,{"aria-labelledby":`technical-finding-${e.id}-fixes`,children:[(0,Q.jsx)(`h4`,{id:`technical-finding-${e.id}-fixes`,className:`text-heading-14 text-heading`,children:`Recommended fixes`}),(0,Q.jsx)(`ol`,{className:`mt-2 list-decimal space-y-1.5 pl-5 marker:text-muted`,children:n.topRecommendations.map((e,t)=>(0,Q.jsx)(`li`,{className:`pl-1 text-label-14 text-secondary`,children:e},t))}),r&&typeof e.sharePct==`number`?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-muted`,children:tC(e.sharePct,`site`)}):null]}):a===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Every audited page passes this check.`}):null,a>0?(0,Q.jsxs)(`section`,{"aria-labelledby":`technical-finding-${e.id}-pages`,children:[(0,Q.jsxs)(`h4`,{id:`technical-finding-${e.id}-pages`,className:`text-heading-14 text-heading`,children:[`Affected pages (`,a,`)`]}),r&&w.isLoading?(0,Q.jsxs)(`div`,{className:`mt-3 flex items-center gap-2 text-label-14 text-secondary`,role:`status`,children:[(0,Q.jsx)(s,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading affected pages…`]}):r&&w.error?(0,Q.jsxs)(`div`,{className:`mt-3`,role:`alert`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-negative`,children:`Affected pages could not load`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Try loading the affected pages again.`}),(0,Q.jsxs)(q,{type:`button`,variant:`secondary`,size:`sm`,className:`mt-3`,onClick:()=>void w.refetch(),disabled:w.isFetching,children:[w.isFetching?(0,Q.jsx)(s,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(_,{className:`size-4`,"aria-hidden":`true`}),w.isFetching?`Retrying affected pages…`:`Retry affected pages`]})]}):i.length>0?(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1.5`,children:i.slice(0,dC).map(e=>(0,Q.jsxs)(`li`,{className:`flex min-w-0 items-center gap-2 text-label-14`,children:[(0,Q.jsx)(`span`,{className:`w-8 shrink-0 text-right font-mono tabular-nums ${hC(e.score)}`,children:e.score}),(0,Q.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`min-w-0 truncate text-link outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400`,title:e.url,children:e.url})]},e.url))}):(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Page details are not available in the loaded page sample.`}),i.length>dC?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`+ `,i.length-dC,` more below pass`]}):null,H&&(!r||!w.isLoading&&!w.error)?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Showing the worst `,te.length,` audited pages.`]}):null]}):null]})})}):null]},e.id)})})]})})]}),!r&&z.crossCuttingIssues.length>0?(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsxs)(`div`,{className:`section-head`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Opportunities`}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h2`,{children:`Prioritized fixes`}),(0,Q.jsx)(X,{text:`Factors scoring below pass across the most pages, ranked by site-wide impact. Fixing one of these typically lifts many pages at once.`})]})]}),(0,Q.jsx)(`div`,{className:`mt-3 divide-y divide-mono-800/60 overflow-hidden material-base`,children:z.crossCuttingIssues.map(e=>(0,Q.jsxs)(`div`,{className:`p-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e.factorName}),(0,Q.jsx)(J,{tone:mC(e.avgScore),children:CC(e.avgScore)}),(0,Q.jsxs)(`span`,{className:`text-label-12 tabular-nums text-muted`,children:[`avg `,e.avgScore,` · affects `,e.affectedPages,` of `,e.totalPages,` pages (`,Ut(e.affectedPct,Je.percent),`)`]})]}),e.topRecommendations.length>0?(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1`,children:e.topRecommendations.map((e,t)=>(0,Q.jsxs)(`li`,{className:`flex gap-2 text-label-14 text-secondary`,children:[(0,Q.jsx)(`span`,{className:`select-none text-faint`,children:`→`}),(0,Q.jsx)(`span`,{children:e})]},t))}):null]},e.factorId))})]}):null,r?null:(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Pages`}),(0,Q.jsx)(`h2`,{children:`Per-page breakdown`})]}),ne?(0,Q.jsxs)(`div`,{className:`segmented`,role:`group`,"aria-label":`Filter pages`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>{c(!1),V.setPage(1)},"aria-pressed":!B,className:`segmented-option min-h-11 tabular-nums ${B?``:`segmented-option-active`}`,children:[`All `,z.pagesAudited]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>{c(!0),V.setPage(1)},"aria-pressed":B,className:`segmented-option min-h-11 tabular-nums ${B?`segmented-option-active text-negative`:``}`,children:[`Errors `,z.pagesErrored]})]}):null]}),te.length>0?(0,Q.jsx)(eu,{value:V.query,onChange:V.setQuery,label:`Filter audited page URLs`,placeholder:`Filter page URL or query parameters`,className:`mt-3 max-w-md`}):null,V.totalRows===0?(0,Q.jsx)(`p`,{className:`supporting-copy mt-3`,children:V.hasQuery?`No pages match this filter.`:`No pages recorded.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`evidence-table-wrap mt-3`,children:(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-right`,children:`Score`}),(0,Q.jsx)(`th`,{children:`Status`}),(0,Q.jsx)(`th`,{className:`w-full`,children:`URL`})]})}),(0,Q.jsx)(`tbody`,{children:V.rows.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-right tabular-nums`,children:e.status===`error`?(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-negative-400`,children:[(0,Q.jsx)(O,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`err`]}):(0,Q.jsx)(`span`,{className:hC(e.overallScore),children:e.overallScore})}),(0,Q.jsx)(`td`,{children:e.status===`error`?(0,Q.jsx)(J,{tone:`negative`,children:`Error`}):(0,Q.jsx)(J,{tone:mC(e.overallScore),children:CC(e.overallScore)})}),(0,Q.jsx)(`td`,{className:`w-full max-w-0`,children:(0,Q.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`block truncate text-neutral hover:text-heading`,title:e.status===`error`?e.error??e.url:e.url,children:(0,Q.jsx)(Ql,{value:e.url,headLength:54,tailLength:20,title:e.status===`error`?e.error??e.url:e.url})})})]},e.url))})]})}),(0,Q.jsx)(tu,{page:V.page,pageSize:V.pageSize,visibleRows:V.rows.length,totalRows:V.totalRows,onPageChange:V.setPage,itemLabel:V.hasQuery?`matches`:`rows`}),H?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-faint`,children:[`Showing the worst `,te.length,` of `,z.pagesAudited,` audited pages.`]}):null]})]})]})}function DC({trend:e}){let[t,n]=(0,Z.useState)(`score`),r=e?.groups.find(e=>e.key===`site-health`);if(!r)return null;let i=r.figures.map(e=>({key:e.key,label:e.label,value:e.value===null?`—`:e.value.toLocaleString(),detail:e.unit===$n.score&&e.value!==null?`/100`:void 0,change:zu(e.change,e.unit),series:Vu(e)})),a=r.figures.find(e=>e.key===`score`),o=a?.series[0],s=a?.series.at(-1);return!o||!s||!i.some(e=>e.key===`score`&&Mu(e))?null:(0,Q.jsx)(`section`,{"aria-label":`Agent Readiness over time`,className:`border-b border-default py-5`,children:(0,Q.jsx)(qu,{name:`Agent Readiness figures`,groups:[{key:`site-health`,label:`Every scan`,basis:Bu(r.figures),figures:i}],selected:[t],onSelect:n,cadence:`scan`,instants:!0,span:Hu(o,s)})})}var OC=[{id:`map`,label:`Map`},{id:`inventory`,label:`Pages`},{id:`technical`,label:`Score`}],kC={map:`Explore how pages, site sections, and internal links fit together.`,inventory:`Review discovered pages and the links that shape their visibility.`,technical:`Prioritize findings and inspect the pages that need work.`},AC=[{id:`all`,label:`All pages`,healthState:void 0},{id:`hidden`,label:`Hidden pages`,healthState:En.hidden}];function jC(e,t,n){return MC(fb(e,n)||t)}function MC(e){let t=e.indexOf(`?`);if(t<0)return{path:e,query:null};let n=e.slice(t),r=n;try{r=decodeURIComponent(n.replaceAll(`+`,` `))}catch{r=n}return{path:e.slice(0,t),query:r}}function NC(e){return e?e.urlVersions+(e.urlVersionsNotFetched??0):null}function PC(e,t=!1){let n=`${$C(e)} URL version${e===1?``:`s`} skipped${t?` in this scan`:``}`;return{label:n,text:`${n}. These addresses add parameters, such as a filter, to a page and name that page as canonical, so they are copies of it. The scan does not score them or list them here.`}}var FC={[rn.metaRobotsNoindex]:`Hidden by meta robots tag`,[rn.xRobotsNoindex]:`Hidden by X-Robots-Tag header`,[rn.robotsDisallow]:`Blocked by robots.txt`,[rn.redirectTerminal]:`Redirects to another page`,[rn.canonicalToOther]:`Points to another page as canonical`,[rn.notHtmlOrUnavailable]:`Not an HTML page, so it was not scored`},IC=new Map(Object.entries(FC));function LC(e){return IC.get(e)??e}var RC=20,zC=200,BC=100,VC=100,HC=50,UC=xn,WC=Jn,GC=new Intl.NumberFormat,KC=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}),qC={eligible:`positive`,hidden:`caution`,resource:`neutral`,redirect:`neutral`,failed:`negative`,unchecked:`neutral`};function JC(e){if(!e)return`Date unavailable`;let t=new Date(e);return Number.isNaN(t.getTime())?`Date unavailable`:KC.format(t)}function YC(e){return e.replaceAll(`_`,` `).replaceAll(`-`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function XC(e){let t=DS(e);return{label:OS(t),tone:qC[t]}}function ZC(e){return e==null?`Not scored`:Ut(e,Je.percent)}function QC(e){return e.auditScore==null?`Not checked`:`${Math.round(e.auditScore)}/100`}function $C(e){return e==null?`Not available`:GC.format(e)}var ew={clicksFromHome:`How many clicks it takes to reach this page from the home page, following links.`,linksIn:`How many other pages link to this page.`,linksOut:`How many other pages this page links to.`,linkImportance:`How much link value flows to this page, based on how many pages link to it and how important those pages are. Shown relative to the highest page on this site, which is 100%.`,technicalScore:`How well this page is set up for AI and search engines to read, from 0 to 100. Open a page to see what it is marked down for.`,linkTimes:`How many times this link appears on the page it comes from.`,pagesFound:`How many pages this scan discovered, whether or not it could load them.`,pagesChecked:`How many of the pages it found this scan actually loaded.`,internalLinks:`How many links between pages on this site the scan recorded.`},tw=new Set([`clicksFromHome`,`linkImportance`,`internalLinks`,`pagesFound`,`pagesChecked`]);function nw(e,t){let n=ew[e];return tw.has(e)?e===`pagesFound`||e===`pagesChecked`?`${n} Hiding menu and footer links does not change it.`:`${n} This always counts every link, including menu and footer.`:e===`technicalScore`||e===`linkTimes`?n:t?`${n} Right now this counts only links written in your page text. Menu and footer links are hidden.`:`${n} This counts every link, including menu and footer.`}function rw(e,t){return`${GC.format(e)} ${t}${e===1?``:`s`}`}function iw(e,t){if(!e||!t)return null;try{let n=new URL(e),r=new URL(t),i=e=>e.hostname.toLowerCase().replace(/\.$/,``).replace(/^www\./,``);return i(n)===i(r)?null:{requested:n.host,effective:r.host}}catch{return null}}function aw(e){return e===`completed`?`positive`:e===`partial`||e===`queued`||e===`running`?`caution`:e===`failed`||e===`cancelled`?`negative`:`neutral`}function ow(e){return e?.hasData?e.runStatus===hr.partial?`Score so far ${e.aggregateScore}/100`:e.runStatus===hr.completed?`Score ${e.aggregateScore}/100`:null:null}var sw=`Latest scan`,cw=`Shows the most complete scan from the latest day with results. Choose a dated entry to view another scan.`;function lw(e){let t=JC(e.finishedAt??e.startedAt??e.createdAt),n=!e.hasCrawlData&&(e.status===hr.completed||e.status===hr.partial)?` · Score only`:``;return`${t} · ${YC(e.status)}${n}`}var uw=gc,dw=[{value:null,label:`Default (10 clicks)`},{value:1,label:`1 click from the home page`},{value:2,label:`2 clicks`},{value:3,label:`3 clicks`},{value:5,label:`5 clicks`},{value:20,label:`20 clicks`},{value:50,label:`50 clicks`},{value:100,label:`100 clicks (maximum)`}],fw={"max-pages":`Raise the page budget in Scan settings.`,"max-edges":`Raise the page budget in Scan settings.`,"max-fetches":`Raise the page budget in Scan settings.`,"max-duration":`Try a smaller scan in Scan settings.`,"max-depth":`Raise the crawl depth in Scan settings.`};function pw(e){return e?fw[e]??null:null}var mw={applied:`This scan told menu and footer links apart by how often the same link repeats across pages. It cannot spot a link written into the page text when its wording matches the menu. Run a new scan to read the page layout instead.`,"applied-placement":`This scan read where each link sits in the page, so links in the page text are separated from the menu, header, and footer even when they use the same wording.`,"applied-placement-with-ubiquity":`This scan read where each link sits in the page. Some pages mark out no menu or main area, so those links fall back to how often the link repeats across pages, which can miss a link written into the page text.`,"applied-placement-partial":`This scan read where each link sits in the page. Some pages mark out no menu or main area, and this scan found fewer than 15 pages, so nothing could tell those links apart. They are counted as links in your page text, which is what a link no rule marked as menu, header, or footer means here.`,"unavailable-too-few-pages":`This scan found fewer than 15 pages and did not read where each link sits in the page. On a site that small every link is on most pages, so menu and footer links cannot be told apart from the rest.`,"unavailable-legacy-scan":`This scan ran before menu and footer links were separated. Run a new scan to split them out.`},hw=new Map(Object.entries(mw));function gw(e){return e===null?``:hw.get(e)??mw[`unavailable-legacy-scan`]}var _w=`Scroll to zoom. Click a page to inspect it.`,vw=`Observed links to and from this page in the selected scan.`,yw=`Page positions on this map were set before menu and footer links were separated. Run a new scan to update them.`;function bw(e){if(e.filterUnavailable)return`All ${rw(e.totalEdgeCount,`link`)} shown.`;let t=`${GC.format(e.contentEdgeCount)} link${e.contentEdgeCount===1?``:`s`} in your page text`,n=GC.format(e.templateEdgeCount);return e.showTemplateLinks?`${t}, ${n} menu and footer.`:`${t}. ${n} menu and footer link${e.templateEdgeCount===1?``:`s`} hidden.`}var xw=`Menu, header, and footer links repeat on every page, so they say nothing about which pages relate to each other. Links written in your page text do.`;function Sw(e,t){let n=[xw,gw(e)];return t.staleLayout&&n.push(yw),n.filter(Boolean).join(` `)}function Cw(e,t,n){if(e===`disabled`)return{label:`Broken links: not checked`,tone:`neutral`};let r=n??0,i=r>0?`, ${GC.format(r)} unchecked`:``;return e===`complete`?t?{label:`Broken links: ${GC.format(t)} found${i}`,tone:`negative`}:r>0?{label:`Broken links: none found, ${GC.format(r)} unchecked`,tone:`caution`}:{label:`Broken links: none found`,tone:`positive`}:e===`partial`?{label:`Broken links: ${GC.format(t??0)} found so far${i}`,tone:`caution`}:{label:`Broken links: not checked`,tone:`neutral`}}function ww(e){return e.showTemplateLinks||!e.known?{value:$C(e.total),hiddenNote:null,filtered:!1}:{filtered:!0,value:e.truncated?`${$C(e.visible)}+`:$C(e.visible),hiddenNote:e.hidden===0?null:e.truncated?`At least ${$C(e.hidden)} menu and footer hidden`:`${$C(e.hidden)} menu and footer hidden`}}function Tw({label:e,value:t,hiddenNote:n,help:r}){return(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsxs)(`dt`,{className:`flex items-center gap-1 text-label-12 text-muted`,children:[e,(0,Q.jsx)(X,{text:r})]}),(0,Q.jsx)(`dd`,{className:`mt-1 text-label-14-strong tabular-nums text-heading`,children:t}),n&&(0,Q.jsx)(`dd`,{className:`mt-0.5 text-label-12 text-muted`,children:n})]})}function Ew({page:e,inbound:t,outbound:n}){return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(`dl`,{className:`grid grid-cols-2 divide-x divide-y divide-default material-base sm:grid-cols-4 sm:divide-y-0`,children:[(0,Q.jsx)(Tw,{label:`Clicks from home`,value:String(e.depth??`Not reached`),help:nw(`clicksFromHome`,!1)}),(0,Q.jsx)(Tw,{label:`Links in`,value:t.value,hiddenNote:t.hiddenNote,help:nw(`linksIn`,t.filtered)}),(0,Q.jsx)(Tw,{label:`Links out`,value:n.value,hiddenNote:n.hiddenNote,help:nw(`linksOut`,n.filtered)}),(0,Q.jsx)(Tw,{label:`Link importance`,value:ZC(e.linkScoreNormalized),help:nw(`linkImportance`,!1)})]})})}function Dw(e,t,n){return t===0?e===`inbound`?`Nothing links to this page.`:`This page links to nothing.`:`${e===`inbound`?`No links in the page text point here.`:`No links in the page text lead away from here.`} ${n?`At least ${$C(t)} menu and footer links hidden.`:`${rw(t,`menu and footer link`)} hidden.`}`}function Ow({label:e,metric:t}){return(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[e,(0,Q.jsx)(X,{text:nw(t,!1)})]})}function kw({url:e,rootHost:t,siteHosts:n,pageSite:r}){let i=pb(e);if(n.length<2||i===null||!n.includes(i))return(0,Q.jsx)(Q.Fragment,{children:fb(e,t)});let a=e;try{let t=new URL(e);a=`${t.pathname}${t.search}`||`/`}catch{}return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`block truncate`,children:a}),i!==r&&(0,Q.jsx)(`span`,{className:`block truncate text-label-12-mono text-secondary`,children:i})]})}function Aw({direction:e,edges:t,truncated:n,rootHost:r,hiddenTemplateCount:i,siteHosts:a=[],pageUrl:o=null}){let s=pb(o),c=e===`inbound`?`Links in`:`Links out`;return(0,Q.jsxs)(`section`,{className:`min-w-0`,"aria-labelledby":`site-health-${e}-heading`,children:[(0,Q.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-3`,children:[(0,Q.jsxs)(`h4`,{id:`site-health-${e}-heading`,className:`text-heading-14 text-heading`,children:[c,` (`,$C(t.length),`)`]}),n&&(0,Q.jsxs)(`span`,{className:`text-label-12 text-muted`,children:[`First `,VC]})]}),t.length===0?(0,Q.jsx)(`p`,{className:`material-base px-3 py-4 text-copy-14 text-secondary`,children:Dw(e,i,n)}):(0,Q.jsx)(`div`,{className:`evidence-table-wrap max-h-64 overflow-auto`,children:(0,Q.jsxs)(`table`,{className:`evidence-table site-health-table min-w-[420px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Page`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Anchor text`}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(Ow,{label:`Times`,metric:`linkTimes`})})]})}),(0,Q.jsx)(`tbody`,{children:t.map(t=>{let n=e===`inbound`?t.sourceUrl:t.targetUrl;return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-64 truncate font-mono`,title:n,children:(0,Q.jsx)(kw,{url:n,rootHost:r,siteHosts:a,pageSite:s})}),(0,Q.jsx)(`td`,{className:`max-w-52 truncate`,title:t.anchors.join(`, `)||void 0,children:t.anchors.join(`, `)||`No anchor text`}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:$C(t.occurrences)})]},t.edgeKey)})})]})})]})}function jw(e){return e&&`indexabilityReasons`in e?e.indexabilityReasons:[]}function Mw({url:e,path:t,rootHost:n,siteHosts:r}){let i=mb(e,n,r);return i?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`text-secondary`,children:i.site}),i.path]}):(0,Q.jsx)(Q.Fragment,{children:t})}function Nw({page:e,isLoading:t,error:n,inbound:r,outbound:i,inboundTruncated:o,outboundTruncated:c,audit:l,auditLoading:u,auditError:d,onRetryAudit:f,rootHost:p,reasonSource:m,reasonsState:h,onRetryReasons:g,showTemplateLinks:_,siteHosts:v=[]}){if(!e)return(0,Q.jsxs)(`section`,{className:`border-t border-default pt-5`,"aria-label":`Selected page details`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Page links`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Select a page to inspect its internal links and crawl signals.`})]});let y=XC(e),b=jw(m??e),x=m?.urlVersionOf??null,S=_?r:r.filter(e=>!e.isTemplate),C=_?i:i.filter(e=>!e.isTemplate),w=!t&&!n,T=r.length-S.length,E=i.length-C.length,D=ww({total:e.inboundUniqueEdges,visible:S.length,hidden:T,truncated:o,showTemplateLinks:_,known:w}),O=ww({total:e.outboundUniqueEdges,visible:C.length,hidden:E,truncated:c,showTemplateLinks:_,known:w});return(0,Q.jsxs)(`section`,{className:`border-t border-default pt-5`,"aria-labelledby":`site-health-page-inspector-title`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col justify-between gap-3 sm:flex-row sm:items-start`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(`h3`,{id:`site-health-page-inspector-title`,className:`break-words font-mono text-heading-16 text-heading`,children:(0,Q.jsx)(Mw,{url:e.url,path:e.path,rootHost:p,siteHosts:v})}),(0,Q.jsx)(J,{tone:y.tone,children:y.label})]}),(0,Q.jsx)(`p`,{className:`mt-1 break-all text-copy-14 text-secondary`,children:e.url}),h===`loading`?(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,role:`status`,children:`Loading page details…`}):h===`error`?(0,Q.jsxs)(`p`,{className:`mt-2 flex flex-wrap items-center gap-2 text-copy-14 text-negative`,role:`alert`,children:[`Page details could not be loaded, so any reason this page is hidden is unknown.`,(0,Q.jsx)(q,{type:`button`,variant:`secondary`,size:`sm`,onClick:g,children:`Try again`})]}):b.length>0||x?(0,Q.jsxs)(`ul`,{className:`mt-2 flex flex-wrap gap-x-4 gap-y-1 text-label-14 text-secondary`,"aria-label":`Why this page is hidden`,children:[x&&(0,Q.jsx)(`li`,{children:`URL version of ${fb(x,p)}, not scored`}),b.map(e=>(0,Q.jsx)(`li`,{children:LC(e)},e))]}):null]}),(0,Q.jsx)(q,{asChild:!0,variant:`secondary`,size:`sm`,children:(0,Q.jsxs)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,children:[`Open page `,(0,Q.jsx)(a,{className:`size-3.5`,"aria-hidden":`true`})]})})]}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(oC,{audit:l,isLoading:u,error:d,onRetry:f})}),(0,Q.jsxs)(`section`,{className:`mt-5 border-t border-default pt-5`,"aria-labelledby":`site-health-page-links-heading`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Q.jsx)(`h3`,{id:`site-health-page-links-heading`,className:`text-heading-16 text-heading`,children:`Internal links`}),(0,Q.jsx)(X,{text:vw})]}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Ew,{page:e,inbound:D,outbound:O})}),(0,Q.jsx)(`div`,{className:`mt-5`,children:t?(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 py-6 text-label-14 text-secondary`,children:[(0,Q.jsx)(s,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading page links…`]}):n?(0,Q.jsx)(`p`,{className:`rounded-md border border-negative bg-negative-soft px-4 py-3 text-copy-14 text-negative`,role:`alert`,children:`Page links could not be loaded.`}):(0,Q.jsxs)(`div`,{className:`grid gap-5 lg:grid-cols-2`,children:[(0,Q.jsx)(Aw,{direction:`inbound`,edges:S,truncated:o,rootHost:p,hiddenTemplateCount:T,siteHosts:v,pageUrl:e.url}),(0,Q.jsx)(Aw,{direction:`outbound`,edges:C,truncated:c,rootHost:p,hiddenTemplateCount:E,siteHosts:v,pageUrl:e.url})]})})]})]})}function Pw({pages:e,total:t,skippedUrlVersions:n,rootHost:r,selectedNodeKey:i,onSelect:a,hasNextPage:o,isFetchingNextPage:c,onLoadMore:l,filter:u,onFilterChange:d,filterUnavailable:f,sites:p,siteFilter:m,onSiteFilterChange:h}){let[g,_]=(0,Z.useState)(``),v=p.map(e=>e.host),y=g.trim().toLowerCase(),b=(0,Z.useMemo)(()=>y?e.filter(e=>`${e.path} ${e.url}`.toLowerCase().includes(y)):e,[y,e]),S=y.length>0&&(o||e.length<t);return(0,Q.jsxs)(`section`,{"aria-labelledby":`site-health-inventory-heading`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-col justify-between gap-3 sm:flex-row sm:items-end`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{id:`site-health-inventory-heading`,className:`text-heading-16 text-heading`,children:`Pages`}),(0,Q.jsxs)(`div`,{className:`mt-1 flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:u===`all`?`Showing ${$C(e.length)} of ${$C(t)} pages.`:`Showing ${$C(e.length)} of ${$C(t)} hidden pages.`}),n!=null&&n>0&&(0,Q.jsx)(X,{...PC(n,m!==`all`)})]})]}),(0,Q.jsxs)(`div`,{className:`flex w-full flex-wrap items-center gap-2 sm:w-auto`,role:`group`,"aria-label":`Page filters`,children:[p.length>1&&(0,Q.jsxs)(`select`,{"aria-label":`Filter pages by site`,value:m,onChange:e=>h(e.target.value),className:`h-9 rounded-md border border-base bg-bg px-3 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600`,children:[(0,Q.jsx)(`option`,{value:`all`,children:`All sites`}),p.map(e=>(0,Q.jsx)(`option`,{value:e.host,children:e.host},e.host))]}),(0,Q.jsx)(`select`,{"aria-label":`Filter pages by status`,value:u,onChange:e=>{let t=AC.find(t=>t.id===e.target.value);t&&d(t.id)},className:`h-9 rounded-md border border-base bg-bg px-3 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600`,children:AC.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Q.jsxs)(`label`,{className:Xt(`relative block min-w-0 flex-1 sm:w-72 sm:flex-none`,p.length>1&&`basis-full sm:basis-auto`),children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:`Search loaded pages`}),(0,Q.jsx)(x,{className:`pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted`,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{type:`search`,value:g,onChange:e=>_(e.target.value),placeholder:`Search loaded pages`,className:`h-9 w-full rounded-md border border-base bg-bg pl-9 pr-3 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-600`})]})]})]}),(0,Q.jsx)(`div`,{className:`evidence-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`evidence-table site-health-table min-w-[800px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Page`}),(0,Q.jsx)(`th`,{scope:`col`,title:AS(`eligible`),children:`Status`}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(Ow,{label:`Clicks from home`,metric:`clicksFromHome`})}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(Ow,{label:`Links in`,metric:`linksIn`})}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(Ow,{label:`Links out`,metric:`linksOut`})}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(Ow,{label:`Link importance`,metric:`linkImportance`})}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(Ow,{label:`Score`,metric:`technicalScore`})})]})}),(0,Q.jsx)(`tbody`,{children:b.map(e=>{let t=XC(e),n=mb(e.url,r,v),o=n?MC(n.path):jC(e.url,e.path,r),s=n&&m===`all`?n.site:null;return(0,Q.jsxs)(`tr`,{className:i===e.nodeKey?`bg-surface-active`:void 0,children:[(0,Q.jsx)(`td`,{className:`max-w-80`,children:(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>a(e.nodeKey),className:`block max-w-full rounded-sm text-left outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,title:e.url,children:[(0,Q.jsx)(`span`,{className:`block truncate font-mono text-button-14 text-link`,children:o.path}),s&&(0,Q.jsx)(`span`,{className:`block truncate text-label-12-mono text-secondary`,children:s}),o.query&&(0,Q.jsx)(`span`,{className:`line-clamp-2 [overflow-wrap:anywhere] text-label-12-mono text-secondary`,children:o.query})]})}),(0,Q.jsx)(`td`,{title:AS(DS(e)),children:(0,Q.jsx)(J,{tone:t.tone,children:t.label})}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:e.depth??`Not reached`}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:$C(e.inboundUniqueEdges)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:$C(e.outboundUniqueEdges)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:ZC(e.linkScoreNormalized)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:QC(e)})]},e.nodeKey)})})]})}),b.length===0&&(0,Q.jsx)(`p`,{className:`border-x border-b border-default px-4 py-8 text-center text-copy-14 text-secondary`,children:y.length===0?f?`This scan cannot be filtered. Run a new scan to filter its pages.`:u===`hidden`?`No hidden pages were found in this scan.`:`No pages are available.`:S?`No matches in the ${$C(e.length)} loaded pages. Load more pages to continue searching.`:`No pages match this search.`}),o&&(0,Q.jsx)(`div`,{className:`flex justify-center border-x border-b border-default px-4 py-3`,children:(0,Q.jsxs)(q,{variant:`secondary`,size:`sm`,disabled:c,onClick:l,children:[c&&(0,Q.jsx)(s,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),c?`Loading more pages`:`Load more pages`]})})]})}function Fw({projectName:e,runId:t,site:n,section:r,onSelect:i}){let[a,o]=(0,Z.useState)(!1),s=r.pageCount-+!!r.hasPage>0;return(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`div`,{className:`flex min-h-11 items-center gap-1 px-2 py-1`,children:[s?(0,Q.jsx)(`button`,{type:`button`,"aria-label":`${a?`Collapse`:`Expand`} ${r.path}`,"aria-expanded":a,onClick:()=>o(e=>!e),className:`flex size-8 shrink-0 items-center justify-center rounded-sm text-muted outline-none hover:bg-surface-hover hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400`,children:a?(0,Q.jsx)(d,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(m,{className:`size-3.5`,"aria-hidden":`true`})}):(0,Q.jsx)(`span`,{className:`block size-8 shrink-0`,"aria-hidden":`true`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>i(r.path,n),className:`min-w-0 flex-1 break-words rounded-sm py-2 text-left font-mono text-button-14 text-heading outline-none hover:text-link focus-visible:ring-2 focus-visible:ring-mono-400`,children:r.path}),(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12-mono text-muted`,children:$C(r.pageCount)})]}),a&&(0,Q.jsx)(`div`,{className:`ml-6 border-l border-default pl-1`,children:(0,Q.jsx)(Rw,{projectName:e,runId:t,site:n,parentPath:r.path,onSelect:i})})]})}function Iw({page:e,onSelect:t}){return(0,Q.jsx)(`li`,{className:`bg-surface-subtle`,children:(0,Q.jsxs)(`div`,{className:`flex min-h-11 items-center gap-1 px-2 py-1`,children:[(0,Q.jsx)(`span`,{className:`block size-8 shrink-0`,"aria-hidden":`true`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(e.nodeKey),className:`min-w-0 flex-1 break-words rounded-sm py-2 text-left font-mono text-button-14 text-heading outline-none hover:text-link focus-visible:ring-2 focus-visible:ring-mono-400`,children:e.path||`/`}),(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12-mono text-muted`,children:$C(1)})]})})}function Lw({site:e,children:t}){let[n,r]=(0,Z.useState)(!1),i=e.error===null;return(0,Q.jsxs)(`li`,{children:[(0,Q.jsxs)(`div`,{className:`flex min-h-11 items-center gap-1 px-2 py-1`,children:[i?(0,Q.jsx)(`button`,{type:`button`,"aria-label":`${n?`Collapse`:`Expand`} ${e.host}`,"aria-expanded":n,onClick:()=>r(e=>!e),className:`flex size-8 shrink-0 items-center justify-center rounded-sm text-muted outline-none hover:bg-surface-hover hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400`,children:n?(0,Q.jsx)(d,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(m,{className:`size-3.5`,"aria-hidden":`true`})}):(0,Q.jsx)(`span`,{className:`block size-8 shrink-0`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 break-words py-2 text-label-14-strong text-heading`,children:e.host}),i?(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12-mono text-muted`,children:$C(e.pages)}):(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12 text-secondary`,children:`Not reached`})]}),e.error&&(0,Q.jsx)(`p`,{className:`whitespace-pre-line break-words px-3 pb-2 text-copy-14 text-secondary`,children:e.error}),n&&(0,Q.jsx)(`div`,{className:`ml-6 border-l border-default pl-1`,children:t})]})}function Rw({projectName:e,runId:t,site:n,parentPath:r,onSelect:i,rootPage:a,onSelectRootPage:o}){let c={client:Y,path:{name:e},query:{runId:t,parentPath:r,limit:BC,...n?{site:n}:{}}},l=ne({...ua(c),initialPageParam:c,getNextPageParam:e=>e.nextCursor?{path:c.path,query:{...c.query,cursor:e.nextCursor}}:void 0}),u=l.data?.pages.flatMap(e=>e.children)??[];return l.isLoading?(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-4 text-label-14 text-secondary`,role:`status`,children:[(0,Q.jsx)(s,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),` Loading sections…`]}):l.error?(0,Q.jsx)(`p`,{className:`px-3 py-4 text-copy-14 text-negative`,role:`alert`,children:`Site sections could not be loaded.`}):u.length===0&&!a?(0,Q.jsx)(`p`,{className:`px-3 py-4 text-copy-14 text-secondary`,children:`No nested sections were found.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`ul`,{className:`divide-y divide-default`,children:[a&&o&&(0,Q.jsx)(Iw,{page:a,onSelect:o}),u.map(r=>(0,Q.jsx)(Fw,{projectName:e,runId:t,site:n,section:r,onSelect:i},r.path))]}),l.hasNextPage&&(0,Q.jsx)(`div`,{className:`px-3 py-2`,children:(0,Q.jsx)(q,{variant:`ghost`,size:`sm`,disabled:l.isFetchingNextPage,onClick:()=>void l.fetchNextPage(),children:l.isFetchingNextPage?`Loading more sections`:`Load more sections`})})]})}function zw(){return(0,Q.jsx)(`div`,{role:`status`,className:`flex min-h-[420px] items-center justify-center material-base px-6 text-center lg:min-h-[520px]`,children:(0,Q.jsxs)(`div`,{className:`max-w-sm`,children:[(0,Q.jsx)(s,{className:`mx-auto size-5 motion-safe:animate-spin text-muted`,"aria-hidden":`true`}),(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14-strong text-heading`,children:`Preparing the interactive site map`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Page and link data is ready for the graph renderer.`})]})})}function Bw(e){return e===`discovering`?`Discovering pages`:e===`checking`?`Checking pages`:e===`arranging-map`?`Arranging map`:e===`queued`?`Waiting to start`:`Preparing scan`}var Vw=3;function Hw(e){return e===`checking`?1:e===`arranging-map`?2:0}function Uw({phase:e,pagesChecked:t}){let n=Hw(e),i=[`Find pages`,n===1&&t!==null?`Check pages · ${$C(t)}`:`Check pages`,`Build map`];return(0,Q.jsxs)(`div`,{className:`mt-4`,role:`progressbar`,"aria-label":`Scan progress`,"aria-valuemin":0,"aria-valuemax":Vw,"aria-valuenow":n,"aria-valuetext":i[n],children:[(0,Q.jsx)(`div`,{className:`grid grid-cols-[1fr_2fr_1fr] gap-1.5`,"aria-hidden":`true`,children:i.map((e,t)=>(0,Q.jsx)(`div`,{className:`h-2 overflow-hidden rounded-full bg-surface-inset`,children:t<n?(0,Q.jsx)(`div`,{className:`h-full w-full rounded-full bg-positive-400`}):t===n?(0,Q.jsx)(`div`,{className:`h-full w-full rounded-full bg-positive-400/40 motion-safe:animate-pulse`}):null},e))}),(0,Q.jsx)(`div`,{className:`mt-2 grid grid-cols-[1fr_2fr_1fr] gap-1.5 text-label-14`,"aria-hidden":`true`,children:i.map((e,t)=>(0,Q.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1 truncate ${t===n?`text-label-14-strong text-heading`:t<n?`text-secondary`:`text-muted`}`,children:[t<n?(0,Q.jsx)(r,{className:`h-3.5 w-3.5 shrink-0`,"aria-hidden":`true`}):null,(0,Q.jsx)(`span`,{className:`truncate`,children:e})]},e))})]})}function Ww(e){return e!==`completed`&&e!==`partial`&&e!==`failed`&&e!==`cancelled`}function Gw(e){return e===`queued`||e===`discovering`||e===`checking`||e===`arranging-map`}function Kw(e){return e===`completed`||e===`partial`||e===`failed`||e===`cancelled`}function qw(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.code==`string`)return t.code;if(t.error&&typeof t.error==`object`){let e=t.error;return typeof e.code==`string`?e.code:null}return null}function Jw({view:e,children:t}){return(0,Q.jsx)(`div`,{id:`site-health-${e}-panel`,role:`tabpanel`,"aria-labelledby":`site-health-${e}-tab`,className:`min-w-0`,children:t})}function Yw({status:e,progress:t,progressError:n,onRetryProgress:r}){let i=t?.attempt??null,a=t?.phase??e,o=a===`arranging-map`;return(0,Q.jsxs)(`section`,{"aria-label":`Current scan progress`,className:`material-base px-5 py-6`,children:[(0,Q.jsx)(`div`,{className:`flex min-h-6 items-center gap-2`,children:(0,Q.jsx)(`h2`,{className:`text-heading-16 text-heading`,children:o?`Preparing site map`:`Scanning site`})}),(0,Q.jsx)(`p`,{"aria-atomic":`true`,"aria-label":`Current scan progress`,"aria-live":`polite`,role:`status`,className:`sr-only`,children:o?`Arranging map. The scan is complete and its map is being published.`:`${Bw(a)}. The map appears after the scan finishes.`}),(0,Q.jsx)(Uw,{phase:a,pagesChecked:i?.pagesFetched??null}),(0,Q.jsxs)(`dl`,{"aria-label":`Live scan counters`,className:`mt-5 grid grid-cols-2 divide-x divide-y divide-default material-base sm:grid-cols-4 sm:divide-y-0`,children:[(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsx)(`dt`,{className:`text-label-14 text-secondary`,children:`Pages found`}),(0,Q.jsx)(`dd`,{className:`mt-1 font-mono text-label-18-strong tabular-nums text-heading`,children:i?$C(i.pagesDiscovered):`—`})]}),(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsx)(`dt`,{className:`text-label-14 text-secondary`,children:`Pages checked`}),(0,Q.jsx)(`dd`,{className:`mt-1 font-mono text-label-18-strong tabular-nums text-heading`,children:i?$C(i.pagesFetched):`—`})]}),(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsx)(`dt`,{className:`text-label-14 text-secondary`,children:`Links found`}),(0,Q.jsx)(`dd`,{className:`mt-1 font-mono text-label-18-strong tabular-nums text-heading`,children:i?$C(i.edgesDiscovered):`—`})]}),(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsx)(`dt`,{className:`text-label-14 text-secondary`,children:`Pages failed`}),(0,Q.jsx)(`dd`,{className:`mt-1 font-mono text-label-18-strong tabular-nums text-heading`,children:i?$C(i.pagesErrored):`—`})]})]}),n&&(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsx)(`span`,{children:o?`Map publishing status could not load.`:`Live scan counts could not load. The scan is still running.`}),r&&(0,Q.jsx)(q,{type:`button`,variant:`secondary`,size:`sm`,onClick:r,children:`Retry progress`})]})]})}function Xw({onRetry:e}){return(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(`span`,{children:`Scan details could not load.`}),(0,Q.jsx)(q,{type:`button`,variant:`secondary`,size:`sm`,onClick:e,children:`Retry scan details`})]})}function Zw({projectName:e,runId:t,status:n,comparison:r,termination:i,canChangeSettings:a}){let o=W({...Aa({client:Y,path:{name:e,runId:t}}),refetchInterval:e=>Gw(e.state.data?.phase)?3e3:!1}),s=o.data,c=s?.error??s?.attempt?.error,l=i??s?.termination??null,u=n===hr.partial,d=r===`latest`,f=!d||o.isSuccess&&o.data.phase===hr.partial,p={completed:null,partial:d?`The latest scan was partial.`:`The earlier scan was partial.`,failed:`The latest scan failed.`,cancelled:`The latest scan was cancelled.`}[n];return(0,Q.jsxs)(`div`,{role:n===hr.failed?`alert`:`status`,className:Xt(`flex gap-3 rounded-md border px-4 py-3 text-label-14`,n===hr.failed?`border-negative bg-negative-soft text-negative`:`border-caution bg-caution-soft text-caution`),children:[n===hr.failed&&(0,Q.jsx)(O,{className:`mt-0.5 size-4 shrink-0`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`min-w-0 space-y-1 break-words`,children:[r&&u&&(0,Q.jsx)(`h3`,{className:`text-label-14-strong`,children:p}),d&&!u&&(0,Q.jsxs)(`p`,{children:[p,` Showing results from an earlier scan.`]}),c&&(0,Q.jsx)(`p`,{className:`whitespace-pre-line`,children:c}),!c&&o.isError&&(0,Q.jsx)(Xw,{onRetry:()=>void o.refetch()}),!c&&o.isSuccess&&o.data.phase===hr.failed&&(0,Q.jsx)(`p`,{children:`This scan did not record a cause.`}),!c&&!o.isPending&&n===hr.completed&&(0,Q.jsx)(`p`,{children:`This scan finished without a score.`}),u&&f&&(l||!c)&&(0,Q.jsxs)(`p`,{children:[sn(l),` `,a&&pw(l)]}),d&&u&&(0,Q.jsx)(`p`,{children:`Showing results from an earlier scan.`})]})]})}function Qw({phase:e,progress:t,onRetryDetails:n,onRunAgain:r}){let i=e===`cancelled`,a=t?.error??t?.attempt?.error;return(0,Q.jsxs)(`section`,{"aria-label":`Audit scan recovery`,role:`alert`,className:`rounded-md border border-negative bg-negative-soft px-5 py-6`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-16 text-negative`,children:i?`Scan cancelled`:`Scan failed`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:i?`The scan was cancelled before Canonry could publish a site map.`:`The scan did not complete, so there is no site map for this run.`}),a&&(0,Q.jsx)(`p`,{className:`mt-3 whitespace-pre-line break-words text-copy-14 text-negative`,children:a}),!a&&n&&(0,Q.jsx)(`div`,{className:`mt-3 text-copy-14 text-secondary`,children:(0,Q.jsx)(Xw,{onRetry:n})}),!a&&!n&&t?.phase===hr.failed&&(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:`This scan did not record a cause.`}),r&&(0,Q.jsx)(fs,{type:`button`,className:`mt-4`,onClick:r,children:`Run scan again`})]})}function $w({projectName:e,projectId:t,initialRunId:n,onReleaseInitialRun:r}){let i=(0,Z.useId)(),[a,o]=(0,Z.useState)(`map`),c=(0,Z.useRef)([]),l=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=e=>{l.current?.open&&e.target instanceof Node&&!l.current.contains(e.target)&&(l.current.open=!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[]);let[u,f]=(0,Z.useState)(()=>n??null),[p,m]=(0,Z.useState)(null),h=(0,Z.useRef)(n),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(!0),[w,T]=(0,Z.useState)(null),[E,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(`all`),[M,N]=(0,Z.useState)(`all`),[P,F]=(0,Z.useState)(null),[I,ee]=(0,Z.useState)(!1),L=K(),{isAdmin:R}=si(),z=rt(),te=(z||wn(Qt[`site-audit`]))&&!R,B=Ec(),V=!L&&!te,H=W({...Mi({client:Y,path:{name:e}}),enabled:V,staleTime:fi});(0,Z.useEffect)(()=>{let e=h.current;e!==n&&(h.current=n,f(t=>n??(t===e?null:t)),_(null))},[n]);let re=W({...ko({client:Y,path:{name:e},query:{limit:RC}}),refetchOnWindowFocus:`always`,refetchInterval:e=>e.state.data?.scans.some(e=>e.status===`queued`||e.status===`running`)?3e3:15e3}),U=re.data?.scans??[],ie=U.at(0),ae=U.find(e=>e.status===`queued`||e.status===`running`),oe=U.find(e=>e.status===`completed`||e.status===`partial`),se=B.data?.runId??null,ce=se&&se!==p&&U.some(e=>e.runId===se&&(e.status===`completed`||e.status===`partial`))?se:null,le=u??ce??re.data?.preferredRunId??oe?.runId??ae?.runId??ie?.runId??null,ue=ae?.runId===le?ae:null,de=le?U.find(e=>e.runId===le):void 0,fe=!!(n&&le===n),pe=de?.status===hr.failed||de?.status===hr.cancelled?de.status:null,me=ue?.runId??(fe||pe?le:null),he=W({...Aa({client:Y,path:{name:e,runId:me??``}}),enabled:!!me,refetchInterval:e=>Ww(e.state.data?.phase)?3e3:!1,refetchIntervalInBackground:!0});(0,Z.useEffect)(()=>{fe&&he.isError&&qw(he.error)===`NOT_FOUND`&&(f(null),_(null),r?.())},[he.error,he.isError,fe,r]);let ge=!pe&&Gw(he.data?.phase),_e=Kw(he.data?.phase)?null:ue,ve=!!(me&&he.isPending),ye=!!(fe&&!de&&he.isError),be=!!(_e||ge||ve||ye),xe=he.data?.phase===`failed`||he.data?.phase===`cancelled`?he.data.phase:pe,Se=W({...Pa({client:Y,path:{name:e},...le?{query:{runId:le}}:{}}),enabled:!be&&!xe}),Ce=Se.data,we=le??Ce?.runId??null,Te=!!(we&&Ce?.hasCrawlData&&Ce.detailsAvailable),Ee=we?{runId:we}:{},De=W({...Ha({client:Y,path:{name:e},query:{...Ee,maxNodes:UC,maxEdges:WC}}),enabled:Te&&!be}),Oe=AC.find(e=>e.id===k)?.healthState,G=Ce?.sites??[],ke=G.map(e=>e.host),Ae=G.length>1&&ke.includes(M)?M:`all`,je={client:Y,path:{name:e},query:{...Ee,...Oe?{healthState:Oe}:{},...Ae===`all`?{}:{site:Ae},urlVersions:`exclude`,limit:zC,sort:`path`}},Me=ne({...so(je),enabled:Te,initialPageParam:je,getNextPageParam:e=>e.nextCursor?{path:je.path,query:{...je.query,cursor:e.nextCursor}}:void 0}),Ne=Te&&(Ce?.deadLinks.state===`complete`||Ce?.deadLinks.state===`partial`),Pe=W({...Wa({client:Y,path:{name:e},query:{...Ee,limit:HC}}),enabled:Ne}),Fe=De.data?.nodes??[],Ie=De.data?.edges??[],Le=(0,Z.useMemo)(()=>Ie.filter(e=>e.isTemplate).length,[Ie]),Re=Ie.length-Le,ze=De.data?.templateDetection??null,Be=ze===null||!jn(ze),Ve=(0,Z.useMemo)(()=>I||Be?Ie:Ie.filter(e=>!e.isTemplate),[Ie,I,Be]),He=De.data?.layout.state===`ready`&&!De.data.layout.templateLinksExcluded,Ue=(0,Z.useMemo)(()=>Me.data?.pages.flatMap(e=>e.pages)??[],[Me.data]),We=Me.data?.pages[0]?.total??Ue.length,Ge=pc(H.data),Ke=(P??H.data?.siteAuditDomains??[]).filter(e=>Ge.owned.includes(e)),qe=(0,Z.useMemo)(()=>Ue.find(e=>e.nodeKey===g)??null,[Ue,g]),Je=!!(Te&&g&&!qe),Ye=W({...eo({client:Y,path:{name:e},query:{...Ee,...Oe?{healthState:Oe}:{},nodeKey:g??void 0,limit:1}}),enabled:Je}),Xe=qe??Ye.data?.pages[0]??null,Ze=!!(g&&Oe&&Je&&Ye.isSuccess&&Ye.data.healthStateFilter===`applied`&&Ye.data.pages.length===0);(0,Z.useEffect)(()=>{Ze&&_(null)},[Ze]);let Qe=(0,Z.useMemo)(()=>Ze?null:Fe.find(e=>e.nodeKey===g)??Xe,[Fe,Xe,g,Ze]),$e=Qe?.nodeKey??null;bc(e,{view:`site-health`,page:{...we?{runId:we}:{},...$e?{nodeKey:$e}:{}}});let et=Qe?Xe?`ready`:Ye.isError?`error`:Je&&Ye.isLoading?`loading`:`ready`:`idle`,tt=W({...Ea({client:Y,path:{name:e},query:{...Ee,nodeKey:$e??void 0,limit:VC}}),enabled:Te&&!!$e}),nt=W({...za({client:Y,path:{name:e},query:{...Ee,nodeKey:$e??void 0}}),enabled:Te&&!!$e}),it=(0,Z.useMemo)(()=>{let e=U.filter(e=>e.status!==hr.queued&&e.status!==hr.running),t=u?U.find(e=>e.runId===u):void 0;return t&&!e.some(e=>e.runId===t.runId)?[t,...e]:e},[U,u]),at=it.length>0,ot=ie?.status,st=!u&&!ce&&ie&&ie.runId!==le&&(ot===hr.failed||ot===hr.cancelled||ot===hr.partial),ct=we?de:void 0,lt=_e?_e.status:ge?he.data?.status??null:xe??Ce?.runStatus??ct?.status??null,ut=lt===`running`?`Scan running`:lt===`queued`?`Scan queued`:lt===`partial`?`Partial scan`:lt===`completed`?`Complete`:lt===`failed`?`Scan failed`:lt===`cancelled`?`Scan cancelled`:`No scan`,dt=!!we&&(lt===hr.completed||lt===hr.partial),ft=W({...wo({client:Y,path:{name:e},...we?{query:{runId:we}}:{}}),enabled:dt}),pt=dt?ow(ft.data):null,mt=pt&&ft.data?ft.data.pagesErrored:0,ht=Pe.data,gt=ht&&`found`in ht?ht:Ce?.deadLinks&&`found`in Ce.deadLinks?Ce.deadLinks:void 0,_t=Cw(ht?.state??Ce?.deadLinks?.state??`unavailable`,gt?.found,gt?.unverified),vt=iw(Ce?.requestedRootUrl??null,Ce?.rootUrl??null),yt=lb(Ce?.rootUrl??null),bt=De.data?.rootNodeKey??null,xt=W({...eo({client:Y,path:{name:e},query:{...Ee,nodeKey:bt??void 0,limit:1}}),enabled:!!(Te&&bt)}),St=(0,Z.useMemo)(()=>Fe.find(e=>e.nodeKey===bt)??xt.data?.pages[0]??null,[Fe,bt,xt.data]),Ct=ae&&ae.runId!==le?ae:null,wt=B.isPending||!!_e||!!Ct||ge||ve,Tt=a===`technical`?`map`:a,Et=e=>{f(e||null),m(se),_(null)},Dt=()=>{(!z&&!wn(Qt[`site-audit`])||R)&&(l.current&&(l.current.open=!1),f(null),_(null),n&&r?.(),B.mutate({projectName:e,projectId:t,projectLabel:H.data?.displayName||e,body:{checkDeadLinks:v,...b?{includeGeo:!0}:{},...S?{}:{includeAgentSkills:!1},...w===null?{}:{maxPages:w},...E===null?{}:{maxDepth:E},...Ge.owned.length>0?{sites:Ke}:{}}}),F(null))},Ot=(e,t)=>{let n=e=>!t||pb(e)===t,r=Fe.find(t=>(t.path===e||t.path.startsWith(`${e}/`))&&n(t.url));r&&_(r.nodeKey)},kt=e=>o(e),At=()=>{N(`all`),A(`all`),kt(`inventory`),c.current[OC.findIndex(e=>e.id===`inventory`)]?.focus()},jt=(e,t)=>{let n=null;e.key===`ArrowRight`||e.key===`ArrowDown`?n=(t+1)%OC.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?n=(t-1+OC.length)%OC.length:e.key===`Home`?n=0:e.key===`End`&&(n=OC.length-1),n!=null&&(e.preventDefault(),kt(OC[n].id),c.current[n]?.focus())};return(0,Q.jsxs)(`div`,{className:`space-y-5`,children:[(0,Q.jsxs)(`header`,{className:`flex flex-col justify-between gap-4 lg:flex-row lg:items-start`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-20 text-heading`,children:st?`Earlier scan`:`Audit scan`}),(0,Q.jsx)(X,{text:kC[a]}),(0,Q.jsx)(J,{tone:aw(lt),children:ut}),pt&&(0,Q.jsx)(`span`,{className:`text-label-14-strong tabular-nums text-heading`,children:pt}),ct&&(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:JC(ct.finishedAt??ct.startedAt)})]})}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start gap-2`,children:[at&&(0,Q.jsxs)(`div`,{className:`grid gap-1 text-label-12 text-muted`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`label`,{htmlFor:i,children:`Scan history`}),(0,Q.jsx)(X,{text:cw,placement:`bottom`})]}),(0,Q.jsxs)(`select`,{id:i,"aria-label":`View an Agent Readiness audit scan`,value:u??ce??``,onChange:e=>Et(e.target.value),className:`h-9 min-w-48 rounded-md border border-base bg-bg px-3 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600`,children:[(0,Q.jsx)(`option`,{value:``,children:sw}),it.map(e=>(0,Q.jsx)(`option`,{value:e.runId,children:lw(e)},e.runId))]})]}),!L&&!te&&(0,Q.jsxs)(`div`,{className:Xt(`flex items-end gap-2`,at&&`pt-5`),children:[(0,Q.jsxs)(`details`,{ref:l,className:`group relative`,onKeyDown:e=>{e.key===`Escape`&&e.currentTarget.open&&(e.preventDefault(),e.currentTarget.open=!1,e.currentTarget.querySelector(`summary`)?.focus())},children:[(0,Q.jsxs)(`summary`,{className:`flex h-9 cursor-pointer list-none items-center gap-2 rounded-md border border-base bg-bg px-3 text-label-14-strong text-heading outline-none hover:bg-bg-elevated focus-visible:ring-2 focus-visible:ring-mono-400 [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(D,{className:`size-4`,"aria-hidden":`true`}),`Scan settings`,(0,Q.jsx)(d,{className:`size-3.5 transition-transform group-open:rotate-180`,"aria-hidden":`true`})]}),(0,Q.jsxs)(`div`,{className:`absolute left-0 z-20 mt-2 w-72 material-menu p-4 sm:left-auto sm:right-0`,children:[Ge.main&&Ge.owned.length>0&&(0,Q.jsxs)(`fieldset`,{className:`mb-4 grid gap-2 border-b border-default pb-4`,children:[(0,Q.jsxs)(`legend`,{className:`mb-2 flex items-center gap-1.5 text-label-14-strong text-heading`,children:[`Sites`,(0,Q.jsx)(X,{text:`The main domain is always scanned. Ticks here apply to this scan; the saved choice is in Settings.`,placement:`bottom`})]}),(0,Q.jsxs)(`label`,{className:`flex items-center justify-between gap-3`,title:`The main domain is always scanned`,children:[(0,Q.jsx)(`span`,{className:`min-w-0 truncate text-label-14-mono text-primary`,children:Ge.main}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:!0,disabled:!0,"aria-label":`Scan ${Ge.main}`,className:`size-4 shrink-0 rounded border-base accent-mono-200`})]}),Ge.owned.map(e=>(0,Q.jsxs)(`label`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsx)(`span`,{className:`min-w-0 truncate text-label-14-mono text-primary`,children:e}),(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Scan ${e}`,checked:Ke.includes(e),disabled:wt,onChange:t=>F(Dc(Ge.owned,Ke,e,t.target.checked)),className:`size-4 shrink-0 rounded border-base accent-mono-200 focus-visible:ring-2 focus-visible:ring-mono-400`})]},e))]}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-label-14 text-heading`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5 text-label-14-strong`,children:[`Check dead links`,(0,Q.jsx)(X,{text:`Adds dead-link analysis to this scan. Slower on a large site.`})]}),(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Check dead links`,checked:v,disabled:wt,onChange:e=>y(e.target.checked),className:`size-4 rounded border-base accent-mono-200 focus:ring-2 focus:ring-mono-400`})]}),(0,Q.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-3 text-label-14 text-heading`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5 text-label-14-strong`,children:[`Geographic signals`,(0,Q.jsx)(X,{text:$S[`geographic-signals`],placement:`bottom`})]}),(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Geographic signals`,checked:b,disabled:wt,onChange:e=>x(e.target.checked),className:`size-4 rounded border-base accent-mono-200 focus:ring-2 focus:ring-mono-400`})]}),(0,Q.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-3 text-label-14 text-heading`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5 text-label-14-strong`,children:[`Agent integrations`,(0,Q.jsx)(X,{text:$S[`agent-skill-exposure`],placement:`bottom`})]}),(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Agent integrations`,checked:S,disabled:wt,onChange:e=>C(e.target.checked),className:`size-4 rounded border-base accent-mono-200 focus:ring-2 focus:ring-mono-400`})]}),(0,Q.jsxs)(`div`,{className:`mt-4`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5 text-label-14-strong text-heading`,children:[`Page budget`,(0,Q.jsx)(X,{text:wc,placement:`bottom`})]}),(0,Q.jsxs)(`select`,{"aria-label":`Page budget`,value:w===null?``:String(w),disabled:wt,onChange:e=>T(e.target.value===``?null:Number(e.target.value)),className:`mt-1 h-9 w-full rounded-md border border-base bg-bg px-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600`,children:[(0,Q.jsx)(`option`,{value:``,children:ac(H.data)}),[...hc(H.data)?[hc(H.data)]:[],...uw].map(e=>(0,Q.jsx)(`option`,{value:String(e.value),children:e.label},e.value))]})]}),(0,Q.jsxs)(`div`,{className:`mt-3`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5 text-label-14-strong text-heading`,children:[`Crawl depth`,(0,Q.jsx)(X,{text:`How far from the home page to follow links. A smaller scan is what fixes a scan that ran out of time.`})]}),(0,Q.jsx)(`select`,{"aria-label":`Crawl depth`,value:E===null?``:String(E),disabled:wt,onChange:e=>O(e.target.value===``?null:Number(e.target.value)),className:`mt-1 h-9 w-full rounded-md border border-base bg-bg px-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600`,children:dw.map(e=>(0,Q.jsx)(`option`,{value:e.value===null?``:String(e.value),children:e.label},String(e.value)))})]})]})]}),(0,Q.jsxs)(fs,{onClick:Dt,disabled:wt,children:[wt?(0,Q.jsx)(s,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(j,{className:`size-4`,"aria-hidden":`true`}),ae?.status===`running`?`Scan running`:ae?.status===`queued`?`Scan queued`:`Run scan`]})]})]})]}),te&&(0,Q.jsx)(Vs,{projectName:e,kind:Qt[`site-audit`],loadSchedule:!z}),Ce?.hasCrawlData&&(0,Q.jsxs)(`div`,{className:`grid grid-cols-2 divide-x divide-y divide-default material-base sm:grid-cols-4 sm:divide-y-0`,children:[(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1 text-label-12 text-muted`,children:[`Pages found`,(0,Q.jsx)(X,{text:nw(`pagesFound`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:$C(Ce.counts.pagesDiscovered)})]}),(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1 text-label-12 text-muted`,children:[`Pages checked`,(0,Q.jsx)(X,{text:nw(`pagesChecked`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:$C(Ce.counts.pagesFetched)}),mt>0&&(0,Q.jsxs)(`div`,{className:`mt-1 flex flex-wrap items-center gap-x-2 text-label-14`,children:[(0,Q.jsxs)(`span`,{className:`text-caution`,children:[$C(mt),` crawl `,mt===1?`error`:`errors`]}),Te&&a!==`inventory`&&(0,Q.jsx)(`button`,{type:`button`,onClick:At,className:`rounded-sm text-primary underline underline-offset-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:`View pages`})]})]}),(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsx)(`div`,{className:`text-label-12 text-muted`,title:AS(`eligible`),children:`Indexable`}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:$C(Ce.counts.pagesEligible)})]}),(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1 text-label-12 text-muted`,children:[`Internal links`,(0,Q.jsx)(X,{text:nw(`internalLinks`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:$C(Ce.counts.internalLinks??null)})]})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 border-b border-default`,children:[(0,Q.jsx)(`div`,{role:`tablist`,"aria-label":`Agent Readiness views`,"aria-orientation":`horizontal`,className:`flex min-w-0 gap-5`,children:OC.map((e,t)=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`site-health-${e.id}-tab`,"aria-selected":a===e.id,"aria-controls":`site-health-${e.id}-panel`,tabIndex:a===e.id?0:-1,ref:e=>{c.current[t]=e},onClick:()=>kt(e.id),onKeyDown:e=>jt(e,t),className:`min-h-11 border-b-2 px-0.5 text-button-14 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-50 ${a===e.id?`border-strong text-heading`:`border-transparent text-secondary hover:border-base hover:text-primary`}`,children:e.label},e.id))}),Ce?.hasCrawlData&&a!==`technical`&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 pb-2`,children:[(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:`Dead-link check`}),(0,Q.jsx)(J,{tone:_t.tone,children:_t.label})]})]}),!u&&ae&&!_e&&(0,Q.jsx)(`div`,{className:`rounded-md border border-caution bg-caution-soft px-4 py-3 text-label-14 text-caution`,role:`status`,children:`A newer scan is running. The latest published result remains available until it finishes.`}),vt&&(0,Q.jsxs)(`div`,{className:`material-base px-4 py-3 text-label-14 text-secondary`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Site address changed during this scan.`}),` `,`The scan started at `,(0,Q.jsx)(`span`,{className:`font-mono text-primary`,children:vt.requested}),` and continued at`,` `,(0,Q.jsx)(`span`,{className:`font-mono text-primary`,children:vt.effective}),`.`,` `,`The map and inventory use the new address.`]}),st&&(0,Q.jsx)(Zw,{projectName:e,runId:ie.runId,status:ot,canChangeSettings:V,comparison:`latest`}),Ce?.hasCrawlData&&we&&(!Ce.complete||lt===hr.partial?(0,Q.jsx)(Zw,{projectName:e,runId:we,status:`partial`,comparison:st?`earlier`:void 0,termination:Ce.termination,canChangeSettings:V}):lt===hr.completed&&ft.data?.hasData===!1?(0,Q.jsx)(Zw,{projectName:e,runId:we,status:`completed`,canChangeSettings:V}):null),xe?(0,Q.jsx)(Jw,{view:Tt,children:(0,Q.jsx)(Qw,{phase:xe,progress:he.data,onRetryDetails:he.isError?()=>void he.refetch():void 0,onRunAgain:V&&!Ct&&!B.isPending?Dt:void 0})}):be?(0,Q.jsx)(Jw,{view:Tt,children:(0,Q.jsx)(Yw,{status:he.data?.phase??(_e?.status===`running`?`running`:`queued`),progress:he.data,progressError:he.isError,onRetryProgress:()=>{he.refetch()}})}):a===`technical`?(0,Q.jsx)(`div`,{id:`site-health-technical-panel`,role:`tabpanel`,"aria-labelledby":`site-health-technical-tab`,className:`min-w-0 space-y-6`,children:(0,Q.jsx)(EC,{projectName:e,projectId:t,runId:we,integrated:!0})}):Se.isLoading?(0,Q.jsx)(Jw,{view:a,children:(0,Q.jsxs)(`div`,{className:`flex min-h-72 items-center justify-center gap-2 text-label-14 text-secondary`,role:`status`,children:[(0,Q.jsx)(s,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading Agent Readiness…`]})}):Se.error?(0,Q.jsx)(Jw,{view:a,children:(0,Q.jsxs)(`section`,{className:`rounded-md border border-negative bg-negative-soft px-5 py-6`,role:`alert`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-14 text-negative`,children:`Agent Readiness could not load`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-negative`,children:`Try loading the crawl again.`}),(0,Q.jsx)(q,{variant:`secondary`,size:`sm`,className:`mt-4`,onClick:()=>void Se.refetch(),children:`Try again`})]})}):Ce?.hasCrawlData?Ce.detailsAvailable?a===`inventory`?(0,Q.jsxs)(`div`,{id:`site-health-inventory-panel`,role:`tabpanel`,"aria-labelledby":`site-health-inventory-tab`,className:`space-y-5`,children:[Me.isLoading?(0,Q.jsxs)(`div`,{className:`flex min-h-56 items-center justify-center gap-2 text-label-14 text-secondary`,role:`status`,children:[(0,Q.jsx)(s,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading page inventory…`]}):Me.error?(0,Q.jsx)(`p`,{className:`rounded-md border border-negative bg-negative-soft px-4 py-3 text-copy-14 text-negative`,role:`alert`,children:`The page inventory could not be loaded.`}):(0,Q.jsx)(Pw,{pages:Ue,total:We,skippedUrlVersions:NC(Me.data?.pages[0]?.inventorySummary),rootHost:yt,filterUnavailable:Me.data?.pages[0]?.healthStateFilter===`unavailable-legacy-scan`,selectedNodeKey:$e,onSelect:_,hasNextPage:!!Me.hasNextPage,isFetchingNextPage:Me.isFetchingNextPage,onLoadMore:()=>void Me.fetchNextPage(),filter:k,onFilterChange:A,sites:G,siteFilter:Ae,onSiteFilterChange:N}),(0,Q.jsx)(Nw,{page:Qe,isLoading:tt.isLoading&&!!Qe,error:tt.error,inbound:tt.data?.inbound??[],outbound:tt.data?.outbound??[],inboundTruncated:tt.data?.inboundTruncated??!1,outboundTruncated:tt.data?.outboundTruncated??!1,audit:nt.data,auditLoading:nt.isLoading&&!!Qe,auditError:nt.error,onRetryAudit:()=>{nt.refetch()},rootHost:yt,reasonSource:Xe,reasonsState:et,onRetryReasons:()=>{Ye.refetch()},showTemplateLinks:I||Be,siteHosts:ke})]}):(0,Q.jsxs)(`div`,{id:`site-health-map-panel`,role:`tabpanel`,"aria-labelledby":`site-health-map-tab`,className:`space-y-5`,children:[(0,Q.jsxs)(`section`,{"aria-labelledby":`site-map-heading`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-col justify-between gap-2 sm:flex-row sm:items-end`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Q.jsx)(`h2`,{id:`site-map-heading`,className:`text-heading-16 text-heading`,children:`Site map`}),(0,Q.jsx)(X,{text:_w})]})}),De.data?.sampled&&(0,Q.jsxs)(`span`,{className:`text-label-12 text-muted`,children:[`Map limited to `,$C(De.data.nodes.length),` of `,$C(De.data.totalNodes),` pages`,` and `,$C(De.data.edges.length),` of `,$C(De.data.totalEdges),` links`]})]}),De.data?.layout.state===`ready`&&Ie.length>0&&(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-col gap-1.5 material-base px-4 py-3 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Q.jsxs)(`p`,{className:`flex items-center gap-1 text-copy-14 text-secondary`,"data-testid":`site-map-link-counts`,children:[bw({filterUnavailable:Be,showTemplateLinks:I,contentEdgeCount:Re,templateEdgeCount:Le,totalEdgeCount:Ie.length}),(0,Q.jsx)(X,{text:Sw(ze,{staleLayout:He&&!Be})})]}),(0,Q.jsxs)(`label`,{className:Xt(`flex shrink-0 items-center gap-2 text-label-14`,Be?`cursor-not-allowed text-muted`:`cursor-pointer text-heading`),title:Be?gw(ze):`Menu and footer links are drawn on top. Pages do not move, because the map was laid out from the links in your page text.`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:I&&!Be,disabled:Be,onChange:e=>ee(e.target.checked),className:`size-4 rounded border-base accent-mono-200 focus:ring-2 focus:ring-mono-400`}),`Show menu and footer links`]})]}),(0,Q.jsxs)(`div`,{id:`site-health-map-explorer`,className:`grid gap-4 lg:grid-cols-[minmax(14rem,18rem)_minmax(0,1fr)]`,children:[(0,Q.jsxs)(`aside`,{className:`material-base`,"aria-labelledby":`site-sections-heading`,children:[(0,Q.jsxs)(`div`,{className:`border-b border-default px-4 py-3`,children:[(0,Q.jsx)(`h3`,{id:`site-sections-heading`,className:`text-heading-14 text-heading`,children:`Site sections`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:G.length>1?`Sites and folders in this scan`:`Folders in this scan`})]}),(0,Q.jsx)(`div`,{className:`max-h-[468px] overflow-auto`,children:we&&G.length>1?(0,Q.jsx)(`ul`,{className:`divide-y divide-default`,children:G.map((t,n)=>(0,Q.jsx)(Lw,{site:t,children:(0,Q.jsx)(Rw,{projectName:e,runId:we,site:t.host,parentPath:`/`,onSelect:Ot,rootPage:n===0?St:null,onSelectRootPage:_})},t.host))}):we&&(0,Q.jsx)(Rw,{projectName:e,runId:we,parentPath:`/`,onSelect:Ot,rootPage:St,onSelectRootPage:_})})]}),(0,Q.jsx)(`div`,{className:`min-w-0`,children:De.isLoading?(0,Q.jsx)(zw,{}):De.error?(0,Q.jsx)(`div`,{className:`flex min-h-[420px] items-center justify-center rounded-md border border-negative bg-negative-soft px-6 text-center lg:min-h-[520px]`,role:`alert`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-negative`,children:`The interactive map could not be loaded.`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`The page inventory and findings remain available.`}),(0,Q.jsx)(q,{variant:`secondary`,size:`sm`,className:`mt-4`,onClick:()=>o(`inventory`),children:`Open page inventory`})]})}):(0,Q.jsx)(QS,{nodes:De.data?.nodes??[],edges:Ie,showTemplateLinks:I||Be,layoutState:De.data?.layout.state??`unavailable`,layoutUnavailableReason:De.data?.layout.state===`unavailable`?De.data.layout.reason:null,rootNodeKey:De.data?.rootNodeKey??null,selectedNodeKey:$e,onSelectNode:e=>_(e.nodeKey),onOpenInventory:()=>o(`inventory`),ariaLabel:`Interactive site map showing ${rw(De.data?.nodes.length??0,`page`)} and ${rw(Ve.length,`internal link`)}`})})]})]}),(0,Q.jsx)(Nw,{page:Qe,isLoading:tt.isLoading&&!!Qe,error:tt.error,inbound:tt.data?.inbound??[],outbound:tt.data?.outbound??[],inboundTruncated:tt.data?.inboundTruncated??!1,outboundTruncated:tt.data?.outboundTruncated??!1,audit:nt.data,auditLoading:nt.isLoading&&!!Qe,auditError:nt.error,onRetryAudit:()=>{nt.refetch()},rootHost:yt,reasonSource:Xe,reasonsState:et,onRetryReasons:()=>{Ye.refetch()},showTemplateLinks:I||Be,siteHosts:ke})]}):(0,Q.jsx)(Jw,{view:a,children:(0,Q.jsxs)(`section`,{className:`rounded-md border border-caution bg-caution-soft px-5 py-6`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-14 text-caution`,children:`Page details unavailable`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-caution`,children:`Summary metrics are preserved for this scan, but its page graph cannot be opened.`})]})}):(0,Q.jsx)(Jw,{view:a,children:(0,Q.jsxs)(`section`,{className:`material-base px-5 py-8 text-center`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-16 text-heading`,children:`Full-site map not available`}),(0,Q.jsx)(`p`,{className:`mx-auto mt-2 max-w-xl text-copy-14 text-secondary`,children:te?tc:Ce?.legacyAuditAvailable?`The existing score is preserved. Run a new scan to build the page and internal-link map.`:L?`An Agent Readiness audit scan has not been run for this project.`:`Run a scan to discover pages, site sections, and internal links.`}),Ce?.legacyAuditAvailable&&(0,Q.jsx)(`div`,{className:`mt-4 flex flex-wrap justify-center gap-2`,children:(0,Q.jsx)(q,{variant:`secondary`,size:`sm`,onClick:()=>o(`technical`),children:`View score`})})]})})]})}function eT({projectName:e}){let t=(0,Z.useId)(),[n,r]=(0,Z.useState)(`changes`),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(null),c=W({...No({client:Y,path:{name:e},query:{limit:30}}),enabled:n===`health`}),l=W({...Fi({client:Y,path:{name:e},query:{kind:Qt[`answer-visibility`],limit:100}}),enabled:n===`compare`}),u=(l.data??[]).filter(e=>(e.status===hr.completed||e.status===hr.partial)&&e.trigger!==ht.probe).reverse(),d=new Set(u.map(e=>e.id)).size>1,f=o??u[0]?.id??``,p=i??u.find(e=>e.id!==f)?.id??``,m=!!(p&&f&&p!==f),h=W({...Fa({client:Y,path:{name:e},query:{run1:p,run2:f}}),enabled:n===`compare`&&m}),g=c.data??[],_=h.data?.diff.filter(e=>e.changed||e.visibilityChanged)??[];return(0,Q.jsxs)(`div`,{className:`mt-6`,children:[(0,Q.jsx)(vl,{id:t,label:`Project history views`,value:n,onChange:r,className:`filter-row`,tabClassName:`filter-chip`,activeTabClassName:`filter-chip-active`,options:[[`changes`,`Changes`],[`health`,`Coverage history`],[`compare`,`Compare runs`]]}),(0,Q.jsxs)(`div`,{id:`${t}-panel`,role:`tabpanel`,"aria-labelledby":`${t}-${n}`,tabIndex:0,children:[n===`changes`?(0,Q.jsx)(Wc,{projectName:e}):null,n===`health`?(0,Q.jsxs)(`section`,{className:`mt-6`,"aria-labelledby":`coverage-history-heading`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`h2`,{id:`coverage-history-heading`,className:`text-heading-16 text-heading`,children:`Mention and citation coverage`}),(0,Q.jsx)(X,{text:`Independent answer-text mentions and source citations across completed checks.`})]}),c.isLoading?(0,Q.jsx)(`p`,{className:`supporting-copy mt-4`,role:`status`,children:`Loading coverage history…`}):null,!c.isLoading&&g.length===0?(0,Q.jsxs)(Cs,{className:`surface-card empty-card mt-4`,children:[(0,Q.jsx)(`h3`,{children:`No coverage history yet`}),(0,Q.jsx)(`p`,{children:we()?Ls:`Complete an AI Visibility check to create the first snapshot.`})]}):null,g.length>0?(0,Q.jsx)(`div`,{className:`evidence-table-wrap mt-4`,children:(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Date`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Mentioned`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Mention coverage`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Cited`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Citation coverage`})]})}),(0,Q.jsx)(`tbody`,{children:g.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`whitespace-nowrap tabular-nums text-secondary`,children:new Date(e.createdAt).toLocaleString()}),(0,Q.jsxs)(`td`,{className:`text-right tabular-nums text-secondary`,children:[e.mentionedPairs,`/`,e.totalPairs]}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-strong`,children:Ut(e.overallMentionRate)}),(0,Q.jsxs)(`td`,{className:`text-right tabular-nums text-secondary`,children:[e.citedPairs,`/`,e.totalPairs-e.citationNotMeasuredPairs]}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-strong`,children:e.overallCitedRate===null?(0,Q.jsx)(`span`,{className:`text-secondary`,children:Ar.label}):Ut(e.overallCitedRate)})]},e.id))})]})}):null]}):null,n===`compare`?(0,Q.jsxs)(`section`,{className:`mt-6`,"aria-labelledby":`compare-runs-heading`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`h2`,{id:`compare-runs-heading`,className:`text-heading-16 text-heading`,children:`Compare answer visibility runs`}),(0,Q.jsx)(X,{text:`See which tracked queries changed mention or citation state between two checks.`})]}),d&&(0,Q.jsxs)(`div`,{className:`mt-4 grid gap-3 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{className:`text-label-12 text-muted`,children:[`Earlier run`,(0,Q.jsx)(`select`,{value:p,onChange:e=>a(e.target.value),className:`mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-label-14 text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600`,children:u.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:new Date(e.createdAt).toLocaleString()},e.id))})]}),(0,Q.jsxs)(`label`,{className:`text-label-12 text-muted`,children:[`Later run`,(0,Q.jsx)(`select`,{value:f,onChange:e=>s(e.target.value),className:`mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-label-14 text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600`,children:u.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:new Date(e.createdAt).toLocaleString()},e.id))})]})]}),l.isLoading||h.isLoading?(0,Q.jsx)(`p`,{className:`supporting-copy mt-4`,role:`status`,children:`Comparing runs…`}):null,!l.isLoading&&!d?(0,Q.jsxs)(Cs,{className:`surface-card empty-card mt-4`,children:[(0,Q.jsx)(`h3`,{children:`Two completed checks are required`}),(0,Q.jsx)(`p`,{children:we()?Ls:`Run another AI Visibility check before comparing historical evidence.`})]}):null,h.data&&_.length===0?(0,Q.jsxs)(Cs,{className:`surface-card empty-card mt-4`,children:[(0,Q.jsx)(`h3`,{children:`No mention or citation changes`}),(0,Q.jsx)(`p`,{children:`The selected checks have the same states for every comparable tracked query.`})]}):null,_.length>0?(0,Q.jsx)(`div`,{className:`evidence-table-wrap mt-4`,children:(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Query`}),(0,Q.jsx)(`th`,{children:`Citation`}),(0,Q.jsx)(`th`,{children:`Mention`})]})}),(0,Q.jsx)(`tbody`,{children:_.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-strong`,children:e.query??`Archived query`}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(J,{tone:e.changed?`caution`:`neutral`,children:[e.run1State??`none`,` → `,e.run2State??`none`]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(J,{tone:e.visibilityChanged?`caution`:`neutral`,children:[e.run1MentionState??`none`,` → `,e.run2MentionState??`none`]})})]},e.queryId??e.query??`unknown`))})]})}):null]}):null]})]})}var tT={state:`not-connected`,selection:null,snapshotCount:0,evidence:`No stored evidence yet.`,lastSnapshotAt:null},nT={contract:null,assessment:null,googleAds:tT,gtm:tT,snapshots:[]};function rT(e){return e.contractSelectionRequired?`contract-selection-required`:e.assessmentState===`loading`?`assessment-loading`:e.assessmentState===`unavailable`?`assessment-unavailable`:cT(e)?`static-mismatch`:e.assessment?.status??(e.contract?`configured`:`not-configured`)}function iT(e){switch(e){case`configured`:return{label:`Configured`,detail:`The conversion is declared, but the static configuration is not yet proven consistent.`,tone:`caution`};case`static-mismatch`:return{label:`Static mismatch`,detail:`Stored configuration does not match the declared conversion. Review the failing checks before relying on it.`,tone:`negative`};case`statically-consistent`:return{label:`Statically consistent`,detail:`Stored Google Ads and Tag Manager configuration aligns with the declared conversion.`,tone:`positive`};case`runtime-unverified`:return{label:`Runtime verification needed`,detail:`The stored configuration aligns, but a real browser event has not been observed.`,tone:`caution`};case`observed`:return{label:`Observed`,detail:`Stored static evidence and a runtime observation support this conversion path.`,tone:`positive`};case`not-configured`:return{label:`Setup needed`,detail:`Connect both providers, select their resources, then declare the conversion Canonry should inspect.`,tone:`neutral`};case`contract-selection-required`:return{label:`Choose conversion`,detail:`Choose one of the declared conversions before Canonry evaluates its evidence.`,tone:`neutral`};case`assessment-loading`:return{label:`Checking configuration`,detail:`Canonry is loading the selected conversion assessment.`,tone:`neutral`};case`assessment-unavailable`:return{label:`Assessment unavailable`,detail:`The selected conversion could not be assessed. Retry before treating static evidence as current.`,tone:`negative`}}}function aT(e){switch(e.googleAds.state){case`not-connected`:return{id:`connect-google-ads`,label:`Connect Google Ads`,detail:`Canonry only queries data; connect a Google Ads user with the Read-only role.`};case`selection-required`:return{id:`select-google-ads`,label:`Select Google Ads account`,detail:`Choose the customer account Canonry should inspect.`};case`stale`:return{id:`sync-google-ads`,label:`Refresh Google Ads evidence`,detail:`Read the selected account again and save a new sanitized observation.`};default:return null}}function oT(e){switch(e.gtm.state){case`not-connected`:return{id:`connect-gtm`,label:`Connect Google Tag Manager`,detail:`Authorize read-only Tag Manager access for this project.`};case`selection-required`:return{id:`select-gtm`,label:`Select Tag Manager container`,detail:`Choose the account and container Canonry should inspect.`};case`stale`:return{id:`sync-gtm`,label:`Refresh Tag Manager evidence`,detail:`Read the selected container again and save a new sanitized observation.`};default:return null}}function sT(e){return e.googleAds.state===`not-connected`?{id:`connect-google-ads`,label:`Connect Google Ads`,detail:`Canonry only queries data; connect a Google Ads user with the Read-only role.`}:e.googleAds.state===`unavailable`||e.gtm.state===`unavailable`?{id:`retry-connection-status`,label:`Retry connection status`,detail:`Retry the stored connection reads before starting another provider action.`}:e.googleAds.state===`selection-required`?{id:`select-google-ads`,label:`Select Google Ads account`,detail:`Choose the customer account Canonry should inspect.`}:e.googleAds.state===`stale`?{id:`sync-google-ads`,label:`Refresh Google Ads evidence`,detail:`Read the selected account again and save a new sanitized observation.`}:e.gtm.state===`not-connected`?{id:`connect-gtm`,label:`Connect Google Tag Manager`,detail:`Authorize read-only Tag Manager access for this project.`}:e.gtm.state===`selection-required`?{id:`select-gtm`,label:`Select Tag Manager container`,detail:`Choose the account and container Canonry should inspect.`}:e.gtm.state===`stale`?{id:`sync-gtm`,label:`Refresh Tag Manager evidence`,detail:`Read the selected container again and save a new sanitized observation.`}:e.contractSelectionRequired?{id:`select-contract`,label:`Select conversion`,detail:`Choose the declared conversion Canonry should assess.`}:e.contract?e.assessmentState===`loading`?{id:`waiting-for-integrity`,label:`Checking configuration…`,detail:`Canonry is loading the selected conversion assessment.`}:e.assessmentState===`unavailable`?{id:`retry-integrity`,label:`Retry assessment`,detail:`Retry the selected conversion assessment before acting on its evidence.`}:e.assessment?.status===`runtime-unverified`?{id:`review-runtime-verification`,label:`Review runtime verification`,detail:`Static configuration is aligned. Verify a real browser event separately.`}:e.assessment?.status===`configured`&&lT(e)?{id:`review-findings`,label:`Review findings`,detail:`Resolve the mismatched or unknown checks before treating this conversion as ready.`}:{id:`sync-static-evidence`,label:`Refresh static evidence`,detail:`Queue fresh read-only Google Ads and Tag Manager observations.`}:{id:`declare-contract`,label:`Declare conversion`,detail:`Name the website event, Google Ads action, and Tag Manager tag that must agree.`}}function cT(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome===`fail`)}function lT(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome!==`pass`)}function uT(e){switch(e){case`connected`:return{label:`Connected`,tone:`positive`};case`stale`:return{label:`Needs refresh`,tone:`caution`};case`selection-required`:return{label:`Selection needed`,tone:`caution`};case`not-connected`:return{label:`Not connected`,tone:`neutral`};case`unavailable`:return{label:`Unavailable`,tone:`negative`}}}function dT(e,t){return e===`configured`?t===`not-configured`||t===`contract-selection-required`?`neutral`:`positive`:e===`static`?t===`assessment-unavailable`?`negative`:t===`assessment-loading`?`neutral`:t===`static-mismatch`?`negative`:t===`statically-consistent`||t===`runtime-unverified`||t===`observed`?`positive`:t===`configured`?`caution`:`neutral`:t===`observed`?`positive`:t===`runtime-unverified`?`caution`:`neutral`}function fT(e,t){return e===`configured`?t===`not-configured`?`Not declared`:t===`contract-selection-required`?`Choose conversion`:`Declared`:e===`static`?t===`assessment-unavailable`?`Unavailable`:t===`assessment-loading`?`Checking`:t===`static-mismatch`?`Mismatch`:t===`statically-consistent`||t===`runtime-unverified`||t===`observed`?`Consistent`:t===`configured`?`Needs review`:`Not checked`:t===`observed`?`Observed`:t===`runtime-unverified`?`Not observed`:`Not checked`}function pT(e){return e.length<=12?e:`…${e.slice(-10)}`}function mT(e){let t=[];return e.googleAds.requirePrimaryAction&&t.push(`primary action`),e.googleAds.requireBiddableGoal&&t.push(`biddable goal`),t.length>0?t.join(` and `):`No bidding-goal assertion`}function hT(e){let t=[];return e.runtime.requireTransactionId&&t.push(`transaction ID`),e.runtime.requireValue&&t.push(`value`),e.runtime.requireCurrency&&t.push(`currency`),t.length>0?t.join(`, `):`No additional event fields required`}var gT={"ads-connection-missing":`Google Ads connection is available`,"ads-conversion-action-missing":`Google Ads conversion action exists and is enabled`,"ads-goal-missing":`Google Ads goal includes the conversion action`,"ads-goal-not-biddable":`Google Ads goal is available for bidding`,"ads-action-not-primary":`Google Ads action is primary`,"gtm-connection-missing":`Tag Manager connection is available`,"gtm-live-graph-missing":`Tag Manager configuration is available`,"gtm-tag-missing":`Required Tag Manager tag exists`,"gtm-tag-unrecognized":`Tag Manager tag type is supported`,"gtm-tag-paused":`Tag Manager tag is active`,"gtm-trigger-missing":`Required Tag Manager trigger is linked`,"gtm-variable-missing":`Required Tag Manager variable is linked`,"gtm-event-mismatch":`Tag Manager event matches the declaration`,"gtm-hostname-mismatch":`Tag Manager host matches the production site`,"gtm-value-mapping-missing":`Conversion value mapping is present`,"gtm-transaction-id-mapping-missing":`Transaction ID mapping is present`,"gtm-currency-mapping-missing":`Currency mapping is present`,"gtm-conversion-id-mismatch":`Google conversion ID matches`,"gtm-conversion-label-mismatch":`Google conversion label matches`,"runtime-event-not-observed":`Website event was observed`,"runtime-gtm-not-observed":`Tag Manager firing was observed`,"runtime-ads-not-observed":`Google Ads conversion was observed`};function _T(e){return e.outcome===`pass`?{label:gT[e.code],tone:`positive`,outcome:`Pass`}:e.outcome===`fail`?{label:gT[e.code],tone:`negative`,outcome:`Fail`}:{label:gT[e.code],tone:`caution`,outcome:`Unknown`}}function vT(e){return e.runtime.productionHosts.length>0?e.runtime.productionHosts.join(`, `):`the declared production site`}function yT(e){let t=[];return e.runtime.requireTransactionId&&t.push(`transaction ID`),e.runtime.requireValue&&t.push(`conversion value`),e.runtime.requireCurrency&&t.push(`currency`),t.length>0?t.join(`, `):`no additional event fields`}function bT(e){return e.provider===`google-ads`?`Google Ads`:`Tag Manager`}function xT({label:e,connection:t,changeSelectionLabel:n,onChangeSelection:r,actionPending:i}){let a=uT(t.state),o=t.snapshotState===`loading`?`Loading stored snapshots`:t.snapshotState===`unavailable`?`Stored snapshots unavailable`:t.snapshotCount===0?`No stored snapshots`:null;return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:a.tone,children:a.label})}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:t.selection??`No selection`}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`p`,{className:`text-secondary`,children:t.evidence}),o?(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:o}):(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[t.snapshotCount,` stored `,t.snapshotCount===1?`snapshot`:`snapshots`,t.lastSnapshotAt?`, latest ${Jr(t.lastSnapshotAt)}`:``]}),t.snapshotError?(0,Q.jsx)(`p`,{role:`alert`,className:`mt-1 text-copy-14 text-negative`,children:t.snapshotError}):null]}),(0,Q.jsx)(`td`,{children:n&&r?(0,Q.jsx)(fs,{type:`button`,variant:`outline`,size:`sm`,disabled:i,onClick:r,children:n}):(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Use the next step above`})})]})}var ST=`A conversion names the website event, the Google Ads conversion action, and the Tag Manager tag that must agree. It needs both connections selected because it references resources from each.`,CT=`Available once Google Ads and Tag Manager are connected.`;function wT({workspace:e,onPrimaryAction:t,onChangeGoogleAdsSelection:n,onChangeGtmSelection:r,actionPending:i,actionError:a}){let o=e.googleAds.state===`connected`,s=e.gtm.state===`connected`,c=e.googleAds.state===`unavailable`,l=e.gtm.state===`unavailable`,u=c||l||e.gtm.state===`unavailable`,d={id:`retry-connection-status`,label:`Retry connection status`,detail:`Retry the stored connection reads before starting another provider action.`},f=[{title:`Google Ads`,state:e.googleAds.state,ready:o,summary:e.googleAds.selection,changeLabel:`Change Google Ads account`,onChange:n,action:c?d:aT(e)},{title:`Tag Manager`,state:e.gtm.state,ready:s,summary:e.gtm.selection,changeLabel:`Change Tag Manager container`,onChange:r,action:l?d:oT(e)}],p=o&&s&&!u?sT(e):null;return(0,Q.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`conversion-integrity-title`,children:[(0,Q.jsx)(`div`,{className:`section-head mb-4`,children:(0,Q.jsx)(`div`,{children:(0,Q.jsxs)(`div`,{className:`mt-1 flex items-center gap-1.5`,children:[(0,Q.jsx)(`h2`,{id:`conversion-integrity-title`,className:`text-heading-20 text-heading`,children:`Conversion Integrity`}),(0,Q.jsx)(X,{text:`Canonry reads your Google configuration and never changes or publishes it. Connect Google Ads and Tag Manager, then choose one website conversion to check across both.`})]})})}),(0,Q.jsxs)(`div`,{className:`max-w-3xl`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 border-y border-default py-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-14 text-heading`,children:`Conversion to check`}),(0,Q.jsx)(X,{text:ST})]}),p&&t?(0,Q.jsx)(fs,{type:`button`,disabled:i,onClick:()=>t(p.id),children:i?`Working…`:p.label}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:CT})]}),(0,Q.jsx)(`ul`,{className:`flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3`,children:f.map(e=>{let n=e.ready?{label:`Ready`,tone:`positive`}:uT(e.state),r=e.action;return(0,Q.jsxs)(`li`,{className:`flex min-w-0 flex-wrap items-center gap-2 text-label-14`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e.title}),(0,Q.jsx)(J,{tone:n.tone,children:n.label}),e.summary?(0,Q.jsx)(`span`,{className:`min-w-0 truncate text-secondary`,children:e.summary}):null,r&&t?r.id===`retry-connection-status`?(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:i,onClick:()=>t(r.id),children:i?`Working…`:r.label}):(0,Q.jsx)(fs,{type:`button`,variant:`outline`,size:`sm`,disabled:i,onClick:()=>t(r.id),children:i?`Working…`:r.label}):null,e.summary&&e.onChange?(0,Q.jsx)(fs,{type:`button`,variant:`ghost`,size:`sm`,"aria-label":e.changeLabel,disabled:i,onClick:e.onChange,children:`Change`}):null]},e.title)})}),a?(0,Q.jsx)(`p`,{role:`alert`,className:`mt-3 text-copy-14 text-negative`,children:a}):null]})]})}function TT({workspace:e=nT,onPrimaryAction:t,actionPending:n=!1,actionError:r=null,contracts:i=[],selectedContractId:a=null,onSelectContract:o,contractError:s=null,onRetryContracts:c,onRetryEvidence:l,onChangeGoogleAdsSelection:u,onChangeGtmSelection:d,onAddContract:f}){let p=rT(e),m=iT(p),h=sT(e),g=e.assessment?.findings??[],_=g.filter(e=>e.outcome!==`pass`),v=g.filter(e=>e.outcome===`pass`),y=_.some(e=>e.outcome===`fail`)?`negative`:`caution`;return i.length===0&&e.contract===null&&!e.contractSelectionRequired&&s===null?(0,Q.jsx)(wT,{workspace:e,onPrimaryAction:t,onChangeGoogleAdsSelection:u,onChangeGtmSelection:d,actionPending:n,actionError:r}):(0,Q.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`conversion-integrity-title`,children:[(0,Q.jsx)(`div`,{className:`section-head mb-5`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h2`,{id:`conversion-integrity-title`,className:`text-heading-20 text-heading`,children:`Conversion Integrity`}),(0,Q.jsx)(X,{text:`Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify. Static configuration and observed browser events are checked separately.`})]})}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(J,{tone:m.tone,children:m.label}),e.assessment?.evaluatedAt?(0,Q.jsxs)(`span`,{className:`text-label-12 text-muted`,children:[`Assessed `,Jr(e.assessment.evaluatedAt)]}):null]}),(0,Q.jsx)(`p`,{className:`supporting-copy mt-2 max-w-2xl`,children:m.detail}),e.assessmentEvidenceSnapshots?.length?(0,Q.jsxs)(`details`,{className:`inline-disclosure mt-3 max-w-2xl`,children:[(0,Q.jsx)(`summary`,{children:`Evidence used for this assessment`}),(0,Q.jsx)(`ul`,{className:`mt-3 space-y-2 text-label-14 text-secondary`,children:e.assessmentEvidenceSnapshots.map(e=>(0,Q.jsxs)(`li`,{className:`break-words`,children:[bT(e),` `,e.kind,`, captured `,Jr(e.capturedAt),(0,Q.jsxs)(`span`,{className:`ml-1 text-label-12-mono text-muted`,children:[`(`,e.id,`)`]})]},e.id))})]}):null]}),(0,Q.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2 lg:max-w-xs`,children:[t?h.id===`review-findings`||h.id===`review-runtime-verification`||h.id===`retry-connection-status`||h.id===`select-contract`||h.id===`retry-integrity`||h.id===`waiting-for-integrity`?(0,Q.jsx)(q,{type:`button`,disabled:n||h.id===`waiting-for-integrity`,onClick:()=>t(h.id),children:n?`Working…`:h.label}):(0,Q.jsx)(fs,{type:`button`,disabled:n,onClick:()=>t(h.id),children:n?`Working…`:h.label}):h.id===`review-findings`?(0,Q.jsx)(q,{asChild:!0,type:`button`,children:(0,Q.jsx)(`a`,{href:`#conversion-integrity-findings`,children:`Review findings`})}):p===`runtime-unverified`?(0,Q.jsx)(q,{asChild:!0,type:`button`,children:(0,Q.jsx)(`a`,{href:`#conversion-integrity-runtime-guidance`,onClick:e=>{let t=e.currentTarget.ownerDocument.getElementById(`conversion-integrity-runtime-guidance`);t instanceof HTMLDetailsElement&&(t.open=!0)},children:`Review runtime verification`})}):null,(0,Q.jsx)(X,{text:h.detail}),r?(0,Q.jsx)(`p`,{role:`alert`,className:`basis-full text-copy-14 text-negative`,children:r}):null]})]}),(0,Q.jsxs)(`section`,{className:`page-section-divider`,"aria-labelledby":`conversion-integrity-contract-title`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{className:`min-w-0`,children:(0,Q.jsx)(`h3`,{id:`conversion-integrity-contract-title`,className:`min-w-0 break-words text-heading-16 text-heading`,children:e.contract?.name??(e.contractSelectionRequired?`Choose a conversion`:`No conversion declared`)})}),i.length>0&&f?(0,Q.jsx)(fs,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:f,children:`Add conversion`}):null]}),i.length>1?(0,Q.jsxs)(`label`,{htmlFor:`conversion-integrity-contract-select`,className:`mb-5 block max-w-xl text-label-14-strong text-secondary`,children:[`Conversion to inspect`,(0,Q.jsxs)(`select`,{id:`conversion-integrity-contract-select`,className:`mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-label-14 text-heading outline-none transition-colors focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30`,value:a??``,onChange:e=>o?.(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a declared conversion`}),i.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}):null,e.contract?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`dl`,{className:`grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-12-strong normal-case text-muted`,children:`Website event`}),(0,Q.jsx)(`dd`,{className:`mt-1 text-label-14-strong text-heading`,children:e.contract.eventName})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-12-strong normal-case text-muted`,children:`Google Ads goal`}),(0,Q.jsx)(`dd`,{className:`mt-1 text-label-14 text-secondary`,children:mT(e.contract)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-12-strong normal-case text-muted`,children:`Tag Manager`}),(0,Q.jsxs)(`dd`,{className:`mt-1 text-label-14 text-secondary`,children:[e.contract.gtm.triggerIds.length,` `,e.contract.gtm.triggerIds.length===1?`trigger`:`triggers`,` and `,e.contract.gtm.variableIds.length,` `,e.contract.gtm.variableIds.length===1?`variable`:`variables`,` required`]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-label-12-strong normal-case text-muted`,children:`Runtime event fields`}),(0,Q.jsx)(`dd`,{className:`mt-1 text-label-14 text-secondary`,children:hT(e.contract)})]})]}),(0,Q.jsxs)(`details`,{className:`inline-disclosure mt-5`,children:[(0,Q.jsx)(`summary`,{children:`Show declared identifiers`}),(0,Q.jsxs)(`dl`,{className:`mt-3 grid gap-x-6 gap-y-3 text-label-14 sm:grid-cols-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Google Ads customer`}),(0,Q.jsx)(`dd`,{className:`mt-0.5 font-mono text-secondary`,children:pT(e.contract.googleAds.customerId)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Google Ads conversion action`}),(0,Q.jsx)(`dd`,{className:`mt-0.5 font-mono text-secondary`,children:pT(e.contract.googleAds.conversionActionId)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Tag Manager container`}),(0,Q.jsx)(`dd`,{className:`mt-0.5 font-mono text-secondary`,children:pT(e.contract.gtm.containerId)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Tag Manager tag`}),(0,Q.jsx)(`dd`,{className:`mt-0.5 font-mono text-secondary`,children:pT(e.contract.gtm.tagId)})]})]})]})]}):(0,Q.jsx)(`p`,{className:`supporting-copy max-w-2xl`,children:e.contractSelectionRequired?`Choose a declared conversion before Canonry evaluates the configuration.`:`A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration.`}),s?(0,Q.jsxs)(`div`,{role:`alert`,className:`mt-4 flex flex-wrap items-center gap-3 text-label-14 text-negative`,children:[(0,Q.jsx)(`span`,{children:s}),c?(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:c,children:`Retry contracts`}):null]}):null,e.assessmentError?(0,Q.jsx)(`p`,{role:`alert`,className:`mt-4 text-copy-14 text-negative`,children:e.assessmentError}):null]}),_.length>0?(0,Q.jsxs)(`section`,{id:`conversion-integrity-findings`,tabIndex:-1,className:`page-section-divider`,"aria-labelledby":`conversion-integrity-findings-title`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`h3`,{id:`conversion-integrity-findings-title`,className:`text-heading-16 text-heading`,children:`Checks to review`}),(0,Q.jsxs)(J,{tone:y,children:[_.length,` `,_.length===1?`check`:`checks`]})]}),(0,Q.jsx)(`div`,{className:`evidence-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Conversion checks that need review`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Check`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Result`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Details`})]})}),(0,Q.jsx)(`tbody`,{children:_.map(e=>{let t=_T(e);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:t.label}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:t.tone,children:t.outcome})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`details`,{children:[(0,Q.jsxs)(`summary`,{className:`cursor-pointer text-label-13 text-secondary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2`,children:[`Diagnostic details`,(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` for `,t.label]})]}),(0,Q.jsxs)(`p`,{className:`mt-2 break-words text-copy-14 text-secondary`,children:[`Related item: `,e.subject]}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13-mono text-muted`,children:[`Diagnostic: `,e.code]}),e.evidenceIds.length>0?(0,Q.jsxs)(`p`,{className:`mt-1 break-words text-copy-13-mono text-muted`,children:[`Evidence: `,e.evidenceIds.join(`, `)]}):null]})})]},`${e.code}:${e.subject}`)})})]})})]}):null,(0,Q.jsxs)(`details`,{className:`inline-disclosure mt-6`,open:e.googleAds.state!==`connected`||e.gtm.state!==`connected`||!!(e.googleAds.snapshotState||e.gtm.snapshotState||e.googleAds.snapshotError||e.gtm.snapshotError),children:[(0,Q.jsx)(`summary`,{children:`Assessment details`}),(0,Q.jsxs)(`div`,{className:`mt-4`,children:[(0,Q.jsxs)(`section`,{"aria-labelledby":`conversion-integrity-progression-title`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{id:`conversion-integrity-progression-title`,className:`text-heading-16 text-heading`,children:`Evidence progression`}),(0,Q.jsx)(X,{text:`Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence.`})]})}),(0,Q.jsx)(`ol`,{className:`divide-y divide-default`,children:[{key:`configured`,title:`Declared`,detail:`The event and provider identifiers are recorded in one project contract.`},{key:`static`,title:`Static configuration`,detail:`Sanitized Google Ads and Tag Manager snapshots are compared with that contract.`},{key:`runtime`,title:`Runtime observation`,detail:`A real browser event, tag firing, and recorded conversion are verified separately.`}].map(e=>{let t=dT(e.key,p);return(0,Q.jsxs)(`li`,{className:`grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`size-2 rounded-full ${t===`positive`?`bg-positive-fill`:t===`caution`?`bg-caution-fill`:t===`negative`?`bg-negative-fill`:`bg-neutral-fill`}`}),(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e.title})]}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:e.detail}),(0,Q.jsx)(J,{tone:t,children:fT(e.key,p)})]},e.key)})})]}),(0,Q.jsxs)(`section`,{className:`page-section-divider`,"aria-labelledby":`conversion-integrity-connections-title`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{id:`conversion-integrity-connections-title`,className:`text-heading-16 text-heading`,children:`Google Ads and Tag Manager`})})}),(0,Q.jsx)(`div`,{className:`evidence-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Google Ads and Tag Manager connection and stored evidence state`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Source`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Connection`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Selection`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Stored evidence`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Actions`})]})}),(0,Q.jsxs)(`tbody`,{children:[xT({label:`Google Ads`,connection:e.googleAds,...e.googleAds.state===`connected`||e.googleAds.state===`stale`?{changeSelectionLabel:`Change Google Ads account`,onChangeSelection:u}:{},actionPending:n}),xT({label:`Google Tag Manager`,connection:e.gtm,...e.gtm.state===`connected`||e.gtm.state===`stale`?{changeSelectionLabel:`Change Tag Manager container`,onChangeSelection:d}:{},actionPending:n})]})]})}),(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-caution`,children:`Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion.`}),(e.googleAds.snapshotError||e.gtm.snapshotError)&&l?(0,Q.jsx)(q,{type:`button`,variant:`outline`,className:`mt-3`,onClick:l,children:`Retry evidence`}):null]}),e.snapshots.length>0?(0,Q.jsxs)(`section`,{className:`page-section-divider`,"aria-labelledby":`conversion-integrity-snapshots-title`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{id:`conversion-integrity-snapshots-title`,className:`text-heading-16 text-heading`,children:`Latest sanitized snapshots`})})}),(0,Q.jsx)(`div`,{className:`evidence-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Latest stored Google marketing snapshots`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Source`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Observation`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Captured`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Identifier`})]})}),(0,Q.jsx)(`tbody`,{children:e.snapshots.slice(0,5).map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.provider===`google-ads`?`Google Ads`:`Google Tag Manager`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.kind}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:Jr(e.capturedAt)}),(0,Q.jsx)(`td`,{className:`text-label-12-mono text-muted`,children:pT(e.id)})]},e.id))})]})})]}):null,v.length>0?(0,Q.jsxs)(`details`,{className:`inline-disclosure mt-8`,children:[(0,Q.jsxs)(`summary`,{children:[v.length,` `,v.length===1?`passing check`:`passing checks`,` from the latest assessment`]}),(0,Q.jsx)(`div`,{className:`findings-table-wrap mt-3`,children:(0,Q.jsxs)(`table`,{className:`findings-table`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Conversion integrity findings`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Check`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Result`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Subject`})]})}),(0,Q.jsx)(`tbody`,{children:v.map(e=>{let t=_T(e);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`td`,{className:`text-secondary`,children:[(0,Q.jsx)(`p`,{children:t.label}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13-mono text-muted`,children:[`Diagnostic: `,e.code]}),e.evidenceIds.length>0?(0,Q.jsxs)(`p`,{className:`mt-1 break-words text-copy-13-mono text-muted`,children:[`Evidence: `,e.evidenceIds.join(`, `)]}):null]}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:t.tone,children:t.outcome})}),(0,Q.jsx)(`td`,{className:`break-words text-secondary`,children:e.subject})]},`${e.code}:${e.subject}`)})})]})})]}):null]})]}),p===`runtime-unverified`?(0,Q.jsxs)(`details`,{id:`conversion-integrity-runtime-guidance`,className:`inline-disclosure mt-3`,children:[(0,Q.jsx)(`summary`,{id:`conversion-integrity-runtime-title`,children:`Runtime verification checklist`}),(0,Q.jsxs)(`ol`,{className:`mt-4 max-w-2xl list-decimal space-y-2 pl-5 text-label-14 text-secondary marker:text-muted`,children:[(0,Q.jsxs)(`li`,{children:[`Use a controlled browser session on `,vT(e.contract),` and complete the conversion that emits `,(0,Q.jsx)(`span`,{className:`font-mono text-heading`,children:e.contract.eventName}),`.`]}),(0,Q.jsxs)(`li`,{children:[`In Tag Manager preview or debugging, confirm tag `,(0,Q.jsx)(`span`,{className:`font-mono text-heading`,children:pT(e.contract.gtm.tagId)}),` fires with `,yT(e.contract),`.`]}),(0,Q.jsxs)(`li`,{children:[`Confirm Google Ads records the matching conversion action `,(0,Q.jsx)(`span`,{className:`font-mono text-heading`,children:pT(e.contract.googleAds.conversionActionId)}),`. Do not change the account or publish a Tag Manager version just to verify it.`]})]})]}):null]})}var ET=3e4,DT={name:``,eventName:``,conversionActionId:``,conversionId:``,conversionLabel:``,campaignIds:``,tagId:``,triggerIds:``,variableIds:``,productionHosts:``,requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},OT=`mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-label-14 text-heading outline-none transition-colors placeholder-mono-400 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30`,kT=`text-label-14-strong text-secondary`;function AT(e,t,n,r){return n?{snapshotCount:e,snapshotState:`unavailable`,snapshotError:ws(r)}:t?{snapshotCount:e,snapshotState:`loading`}:{snapshotCount:e}}function jT(e){return[...new Set(e.split(/[\n,]/).map(e=>e.trim()).filter(Boolean))]}function MT(e,t,n){if(n)return{state:`unavailable`,selection:null,...t,evidence:`Stored Google Ads connection status could not be loaded.`,lastSnapshotAt:null};if(!e||e.status===`not-connected`)return{state:`not-connected`,selection:null,...t,evidence:`No Google Ads OAuth connection is stored for this project.`,lastSnapshotAt:null};if(e.status===`selection-required`){let n=e.connection.selection.customerId;return n?{state:`stale`,selection:`Selected customer ${n}`,...t,evidence:`A customer is selected, but Canonry needs a fresh conversion-goal observation.`,lastSnapshotAt:e.connection.lastInventorySnapshotAt}:{state:`selection-required`,selection:null,...t,evidence:`OAuth access is connected, but Canonry needs a customer account selection.`,lastSnapshotAt:e.connection.lastInventorySnapshotAt}}let r=e.selectedCustomer;return{state:e.status,selection:r.descriptiveName??`Selected customer ${r.customerId}`,...t,evidence:e.status===`stale`?`The selected customer needs a fresh conversion-goal observation.`:`Selected customer and conversion-goal evidence are stored.`,lastSnapshotAt:e.connection.lastInventorySnapshotAt}}function NT(e,t,n){let r=[`Container ${e}`,`account ${t}`];return n&&r.push(`workspace ${n}`),r.join(` · `)}function PT(e,t,n){if(n)return{state:`unavailable`,selection:null,...t,evidence:`Stored Tag Manager connection status could not be loaded.`,lastSnapshotAt:null};if(!e||e.status===`not-connected`)return{state:`not-connected`,selection:null,...t,evidence:`No Tag Manager OAuth connection is stored for this project.`,lastSnapshotAt:null};let r=e.selection;return e.status===`selection-required`||!r.accountId||!r.containerId?{state:`selection-required`,selection:null,...t,evidence:`OAuth access is connected, but Canonry needs an account and container selection.`,lastSnapshotAt:e.connection.lastSnapshotAt}:{state:e.status,selection:NT(r.containerId,r.accountId,r.workspaceId),...t,evidence:e.status===`stale`?`The selected container needs a fresh static configuration observation.`:`Selected container configuration evidence is stored.`,lastSnapshotAt:e.connection.lastSnapshotAt}}function FT(e,t,n){return{name:e.name.trim(),eventName:e.eventName.trim(),googleAds:{customerId:t,conversionActionId:e.conversionActionId.trim(),...e.conversionId.trim()?{conversionId:e.conversionId.trim()}:{},...e.conversionLabel.trim()?{conversionLabel:e.conversionLabel.trim()}:{},campaignIds:jT(e.campaignIds),requireBiddableGoal:e.requireBiddableGoal,requirePrimaryAction:e.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:e.tagId.trim(),triggerIds:jT(e.triggerIds),variableIds:jT(e.variableIds)},runtime:{verificationRequired:e.verificationRequired,requireTransactionId:e.requireTransactionId,requireValue:e.requireValue,requireCurrency:e.requireCurrency,productionHosts:jT(e.productionHosts)}}}function IT(e,t){let n=window.open(e,`_blank`,`width=600,height=700`);if(!n){window.location.assign(e);return}let r=window.setInterval(()=>{n.closed&&(window.clearInterval(r),t())},1e3)}function LT(e,t,n){if(!t)return null;let r=t.totalAccessible===1?e:`${e}s`;return t.truncated?`Incomplete result: showing ${n} of ${t.totalAccessible} accessible ${r}. Use the CLI or API if the resource is not shown.`:`${t.totalAccessible} accessible ${r} found.`}function RT(e,t,n){return e?`no longer accessible`:n?`access not verified`:t?`not in the current result`:`checking access`}function zT({id:e,label:t,value:n,onChange:r,children:i,disabled:a=!1}){return(0,Q.jsxs)(`label`,{htmlFor:e,className:kT,children:[t,(0,Q.jsx)(`select`,{id:e,className:OT,value:n,onChange:e=>r(e.target.value),disabled:a,children:i})]})}function BT({id:e,checked:t,onChange:n,children:r}){return(0,Q.jsxs)(`label`,{htmlFor:e,className:`flex items-start gap-2 text-label-14 text-secondary`,children:[(0,Q.jsx)(`input`,{id:e,type:`checkbox`,checked:t,onChange:e=>n(e.target.checked),className:`mt-0.5 size-4 rounded border-base bg-bg accent-mono-100`}),(0,Q.jsx)(`span`,{children:r})]})}function VT({providerLabel:e,disabled:t,onDisconnect:n}){let[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),d=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{let e=d.current;d.current=r,r?u.current?.focus():e&&l.current?.querySelector(`button`)?.focus()},[r]);function f(){c(null),i(!0)}function p(){c(null),i(!1)}async function m(){o(!0),c(null);try{await n()}catch(e){c(ws(e)),o(!1)}}return(0,Q.jsx)(`div`,{ref:l,className:`mt-5 border-t border-subtle pt-4`,children:r?(0,Q.jsxs)(`div`,{role:`group`,"aria-label":`Confirm disconnect ${e}`,className:`max-w-2xl`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:`Remove Canonry's stored access and selection?`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Saved evidence and conversion contracts remain. New checks stop until you reconnect.`}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,Q.jsx)(q,{ref:u,type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,disabled:a,onClick:p,children:`Keep connected`}),(0,Q.jsx)(fs,{type:`button`,variant:`destructive`,size:`sm`,className:`pointer-coarse:min-h-11`,disabled:t||a,onClick:()=>void m(),children:a?`Disconnecting…`:`Disconnect ${e}`})]}),s?(0,Q.jsx)(`p`,{role:`alert`,className:`mt-2 text-copy-14 text-negative`,children:s}):null]}):(0,Q.jsxs)(fs,{type:`button`,variant:`ghost`,size:`sm`,className:`pointer-coarse:min-h-11 text-negative hover:text-negative`,disabled:t,onClick:f,children:[`Disconnect `,e]})})}function HT({id:e,label:t,options:n,synced:r,loading:i,failed:a,onRetry:o,emptyHint:s,value:c,onChange:l}){let u=n.some(e=>e.id===c),[d,f]=(0,Z.useState)(!1),p=d||c!==``&&!u&&n.length>0,m=(0,Q.jsx)(`label`,{htmlFor:e,className:kT,children:t});return i?(0,Q.jsxs)(`div`,{children:[m,(0,Q.jsx)(`select`,{id:e,className:OT,disabled:!0,children:(0,Q.jsx)(`option`,{children:`Loading…`})})]}):a?(0,Q.jsxs)(`div`,{children:[m,(0,Q.jsx)(`input`,{id:e,required:!0,className:OT,value:c,onChange:e=>l(e.target.value)}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-negative`,children:[`Could not load the list.`,` `,(0,Q.jsx)(`button`,{type:`button`,className:`text-link underline`,onClick:o,children:`Retry`})]})]}):!r||n.length===0?(0,Q.jsxs)(`div`,{children:[m,(0,Q.jsx)(`input`,{id:e,required:!0,className:OT,value:c,onChange:e=>l(e.target.value)}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:r?`Synced, but nothing to choose from yet.`:s})]}):(0,Q.jsxs)(`div`,{children:[m,p?(0,Q.jsx)(`input`,{id:e,required:!0,className:OT,value:c,onChange:e=>l(e.target.value)}):(0,Q.jsxs)(`select`,{id:e,required:!0,className:OT,value:c,onChange:e=>l(e.target.value),children:[(0,Q.jsxs)(`option`,{value:``,children:[`Select `,t.toLowerCase()]}),n.map(e=>(0,Q.jsxs)(`option`,{value:e.id,children:[e.name,e.detail?` (${e.detail})`:``,e.active?``:` — inactive`]},e.id))]}),(0,Q.jsx)(`button`,{type:`button`,className:`mt-1 text-button-14 text-link`,onClick:()=>{f(!p),l(``)},children:p?`Choose from synced list`:`Enter an ID manually`})]})}function UT({projectId:e,projectName:t}){let n=si(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(``),[x,S]=(0,Z.useState)(``),[C,w]=(0,Z.useState)(``),[T,E]=(0,Z.useState)(``),[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(DT),[j,M]=(0,Z.useState)(null),N=(0,Z.useRef)(null),P=W({...ka({client:Y,path:{name:t}}),staleTime:ET}),F=W({...Eo({client:Y,path:{name:t}}),staleTime:ET}),I=W({...Po({client:Y,path:{name:t}}),staleTime:ET}),ee=W({...xi({client:Y,path:{name:t}}),staleTime:ET}),L=ee.data,R=W({...qa({client:Y,path:{name:t},query:{limit:5}}),staleTime:ET}),z=W({...Da({client:Y,path:{name:t},query:{limit:5}}),staleTime:ET}),te=I.data??[],ne=(j?te.find(e=>e.id===j)??null:null)??(te.length===1?te[0]??null:null),B=te.length>1&&!ne,V=W({...sa({client:Y,path:{name:t,contractId:ne?.id??``}}),enabled:!!ne,staleTime:ET}),H=W({...io({client:Y,path:{name:t}}),enabled:d===`google-ads`&&P.data?.connected===!0,staleTime:0}),re=W({...Ua({client:Y,path:{name:t}}),enabled:d===`gtm`&&F.data?.connected===!0,staleTime:0}),U=W({...Ga({client:Y,path:{name:t,accountId:x}}),enabled:d===`gtm`&&!!x,staleTime:0}),ae=W({...to({client:Y,path:{name:t,accountId:x,containerId:C}}),enabled:d===`gtm`&&!!x&&!!C,staleTime:0}),oe=ie(Zi({client:Y})),se=ie(ra({client:Y})),ce=ie(Pi({client:Y})),le=ie(Ki({client:Y})),ue=ie($i({client:Y})),de=ie(ji({client:Y})),fe=ie(no({client:Y})),pe=ie(mo({client:Y})),me=ie(Qa({client:Y}));(0,Z.useEffect)(()=>{if(d!==`google-ads`||p||!P.isSuccess)return;let e=P.data.connection?.selection;v(e?.customerId??``),b(e?.loginCustomerId??``),m(!0)},[p,P.data,P.isSuccess,d]),(0,Z.useEffect)(()=>{if(d!==`gtm`||h||!F.isSuccess)return;let e=F.data.selection;S(e?.accountId??``),w(e?.containerId??``),E(e?.workspaceId??``),g(!0)},[h,F.data,F.isSuccess,d]),(0,Z.useEffect)(()=>{j&&I.data&&(I.data.some(e=>e.id===j)||M(null))},[I.data,j]);let he=(0,Z.useMemo)(()=>{let e=R.data?.snapshots??[],t=z.data?.snapshots??[],n=[...e.map(e=>({id:e.id,provider:`google-ads`,kind:e.kind,capturedAt:e.capturedAt})),...t.map(e=>({id:e.id,provider:`gtm`,kind:e.kind,capturedAt:e.capturedAt}))].sort((e,t)=>t.capturedAt.localeCompare(e.capturedAt)).slice(0,5),r=[],i=V.data?.googleAdsSnapshot,a=V.data?.gtmSnapshot;return i&&r.push({id:i.id,provider:`google-ads`,kind:i.kind,capturedAt:i.capturedAt}),a&&r.push({id:a.id,provider:`gtm`,kind:a.kind,capturedAt:a.capturedAt}),{contract:V.data?.assessment.contract??ne,assessment:V.data?.assessment??null,contractSelectionRequired:B,assessmentState:ne?V.isError?`unavailable`:V.isLoading?`loading`:void 0:void 0,assessmentError:V.isError?ws(V.error):null,googleAds:MT(P.data,AT(R.data?.total??0,R.isLoading,R.isError,R.error),P.isError),gtm:PT(F.data,AT(z.data?.total??0,z.isLoading,z.isError,z.error),F.isError),snapshots:n,assessmentEvidenceSnapshots:r}},[ne,B,R.data,R.error,R.isError,R.isLoading,P.data,P.isError,z.data,z.error,z.isError,z.isLoading,F.data,F.isError,V.data,V.error,V.isError,V.isLoading]),ge=(0,Z.useSyncExternalStore)(Qs,js,js),_e=Object.values(ge.runs).some(t=>t.projectId===e&&(t.kind===Qt[`google-ads-sync`]||t.kind===Qt[`gtm-sync`])),ve=oe.isPending||se.isPending||ce.isPending||le.isPending||ue.isPending||de.isPending||fe.isPending||pe.isPending||me.isPending||_e;async function ye(){await Promise.all([P.refetch(),F.refetch(),I.refetch(),R.refetch(),z.refetch(),ee.refetch(),ne?V.refetch():Promise.resolve()])}async function be(e){await ye();for(let t=0;t<10&&!e();t+=1)await new Promise(e=>setTimeout(e,1500)),await ye()}function xe(){let e=document.activeElement;N.current=e instanceof HTMLElement?e:null}function Se(e){typeof window<`u`&&typeof window.requestAnimationFrame==`function`?window.requestAnimationFrame(e):globalThis.setTimeout(e,0)}function Ce(e){e&&(!e.matches(`a[href], button, input, select, textarea, summary, [contenteditable="true"]`)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=-1),e.focus({preventScroll:!0}))}function we(e,t=e){let n=document.getElementById(e);n instanceof HTMLDetailsElement&&(n.open=!0);let r=n?.scrollIntoView;typeof r==`function`&&r.call(n,{behavior:$s()?`auto`:`smooth`,block:`start`}),Ce(document.getElementById(t)??n)}function Te(e,t){xe(),Se(()=>we(e,t))}function Ee(){let e=N.current;N.current=null,e&&Se(()=>{e.isConnected&&e.focus({preventScroll:!0})})}function De(){i(null),c(!1),Ee()}function Oe(){i(null),f(null),Ee()}function G(){i(null),O(!1),Ee()}function ke(){i(null),f(null),c(!0),Te(`google-ads-connect-panel`,`google-ads-connect-title`)}function Ae(){i(null),v(``),b(``),m(!1),f(`google-ads`),c(!1),Te(`google-ads-selection-panel`,`google-ads-selection-title`)}function je(){i(null),S(``),w(``),E(``),g(!1),f(`gtm`),c(!1),Te(`gtm-selection-panel`,`gtm-selection-title`)}function Me(){i(null),O(!0),Te(`conversion-integrity-contract-form`,`conversion-integrity-contract-form-title`)}function Ne(e,n){Fs({id:e.id,projectId:e.projectId,kind:e.kind,projectLabel:t,sourceAction:n}),li({title:n===`google-ads-sync`?`Google Ads sync queued`:`Tag Manager sync queued`,detail:`${t} will refresh when the sync completes.`,tone:`neutral`,dedupeKey:`google-marketing-sync:${e.id}`,dedupeMode:`replace`})}async function Pe(){jc(n),i(null);try{let e=await oe.mutateAsync({path:{name:t},body:{provider:`google-ads`,...l.trim()?{developerToken:l.trim()}:{}}});u(``),c(!1),o(`Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes.`),IT(e.authorizationUrl,()=>{ye(),o(null),Ee()})}catch(e){i(ws(e))}}async function Fe(){jc(n),i(null);try{let e=await se.mutateAsync({path:{name:t},body:{provider:`gtm`}});o(`Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes.`),IT(e.authorizationUrl,()=>{ye(),o(null),Ee()})}catch(e){i(ws(e))}}async function Ie(){if(jc(n),!_)i(`Select a Google Ads customer before saving.`);else{i(null);try{await ce.mutateAsync({path:{name:t},body:{customerId:_,...y.trim()?{loginCustomerId:y.trim()}:{}}}),f(null),Ee(),await be(()=>P.data?.selectedCustomer!=null)}catch(e){i(ws(e))}}}async function Le(){if(jc(n),!x||!C)i(`Select a Tag Manager account and container before saving.`);else{i(null);try{await le.mutateAsync({path:{name:t},body:{accountId:x,containerId:C,...T?{workspaceId:T}:{}}}),f(null),Ee(),await be(()=>F.data?.status===`connected`)}catch(e){i(ws(e))}}}async function Re(){jc(n),i(null),await fe.mutateAsync({path:{name:t}}),f(null),c(!1),v(``),b(``),m(!1),o(null),await ye(),li({title:`Google Ads disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`google-ads-disconnected:${e}`,dedupeMode:`replace`}),N.current=null,Se(()=>Ce(document.getElementById(`conversion-integrity-title`)))}async function ze(){jc(n),i(null),await pe.mutateAsync({path:{name:t}}),f(null),S(``),w(``),E(``),g(!1),o(null),await ye(),li({title:`Tag Manager disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`gtm-disconnected:${e}`,dedupeMode:`replace`}),N.current=null,Se(()=>Ce(document.getElementById(`conversion-integrity-title`)))}async function Be(){jc(n),i(null);try{Ne(await ue.mutateAsync({path:{name:t}}),`google-ads-sync`)}catch(e){i(ws(e))}}async function Ve(){jc(n),i(null);try{Ne(await de.mutateAsync({path:{name:t}}),`gtm-sync`)}catch(e){i(ws(e))}}async function He(){jc(n),i(null);try{let e=await Promise.allSettled([ue.mutateAsync({path:{name:t}}),de.mutateAsync({path:{name:t}})]),[n,r]=e;n.status===`fulfilled`&&Ne(n.value,`google-ads-sync`),r.status===`fulfilled`&&Ne(r.value,`gtm-sync`);let i=e.find(e=>e.status===`rejected`);if(i?.status===`rejected`)throw i.reason}catch(e){i(ws(e))}}async function Ue(){jc(n);let e=P.data?.connection?.selection.customerId,r=F.data?.selection;if(!e||!r?.accountId||!r.containerId)i(`Select Google Ads and Tag Manager resources before declaring a conversion.`);else{i(null);try{let n=await me.mutateAsync({path:{name:t},body:FT(k,e,{accountId:r.accountId,containerId:r.containerId})});A(DT),O(!1),Ee(),(await I.refetch()).data?.some(e=>e.id===n.id)&&M(n.id)}catch(e){i(ws(e))}}}function We(e){switch(e){case`connect-google-ads`:ke();return;case`connect-gtm`:xe(),Fe();return;case`select-google-ads`:Ae();return;case`select-gtm`:je();return;case`sync-google-ads`:Be();return;case`sync-gtm`:Ve();return;case`sync-static-evidence`:He();return;case`declare-contract`:Me();return;case`review-findings`:Te(`conversion-integrity-findings`,`conversion-integrity-findings`);return;case`review-runtime-verification`:Te(`conversion-integrity-runtime-guidance`,`conversion-integrity-runtime-title`);return;case`retry-connection-status`:ye();return;case`select-contract`:Te(`conversion-integrity-contract-select`,`conversion-integrity-contract-select`);return;case`retry-integrity`:V.refetch();return;case`waiting-for-integrity`:return}}let Ge=H.data?.customers??[],Ke=re.data?.accounts??[],qe=U.data?.containers??[],Je=ae.data?.workspaces??[],Ye=!!_&&!Ge.some(e=>e.customerId===_),Xe=!!x&&!Ke.some(e=>e.id===x),Ze=!!C&&!qe.some(e=>e.id===C),Qe=!!T&&!Je.some(e=>e.id===T),$e=Ye&&H.isSuccess&&H.data.truncated===!1,et=Xe&&re.isSuccess&&re.data.truncated===!1,tt=Ze&&U.isSuccess&&U.data.truncated===!1,nt=Qe&&ae.isSuccess&&ae.data.truncated===!1,rt=et||tt||nt,it=et?`The saved Tag Manager account is no longer accessible. Choose an available account before saving.`:tt?`The saved Tag Manager container is no longer accessible. Choose an available container before saving.`:nt?`The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.`:null,at=RT($e,H.data,H.isError),ot=RT(et,re.data,re.isError),st=RT(tt,U.data,U.isError),ct=RT(nt,ae.data,ae.isError),lt=H.isError?ws(H.error):null,ut=re.isError?ws(re.error):U.isError?ws(U.error):ae.isError?ws(ae.error):null,dt=d===`google-ads`?lt:d===`gtm`?ut:null,ft=LT(`customer`,H.data,Ge.length),pt=LT(`account`,re.data,Ke.length),mt=LT(`container`,U.data,qe.length),ht=LT(`draft workspace`,ae.data,Je.length),gt=re.isError||U.isError||ae.isError&&!!T,_t=s||d!==null||D;function vt(){H.refetch()}function yt(){re.isError?re.refetch():U.isError?U.refetch():ae.isError&&ae.refetch()}return P.isLoading||F.isLoading||I.isLoading?(0,Q.jsxs)(`section`,{className:`page-section`,"aria-busy":`true`,"aria-labelledby":`conversion-integrity-title`,children:[(0,Q.jsx)(`p`,{className:`eyebrow`,children:`Google marketing`}),(0,Q.jsx)(`h2`,{id:`conversion-integrity-title`,className:`mt-1 text-heading-20 text-heading`,children:`Conversion Integrity`}),(0,Q.jsx)(`div`,{"aria-hidden":`true`,className:`mt-5 grid gap-4 sm:grid-cols-2`,children:[0,1].map(e=>(0,Q.jsxs)(`div`,{className:`page-skeleton-card`,children:[(0,Q.jsx)(`div`,{className:`skeleton-text w-28`}),(0,Q.jsx)(`div`,{className:`skeleton-text-sm w-full`}),(0,Q.jsx)(`div`,{className:`skeleton-text-sm w-3/4`})]},e))}),(0,Q.jsx)(`p`,{role:`status`,className:`sr-only`,children:`Loading conversion setup…`})]}):I.isError&&!I.data?(0,Q.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`conversion-integrity-title`,children:[(0,Q.jsx)(`p`,{className:`eyebrow`,children:`Google marketing`}),(0,Q.jsx)(`h2`,{id:`conversion-integrity-title`,className:`mt-1 text-heading-20 text-heading`,children:`Conversion Integrity`}),(0,Q.jsxs)(`p`,{role:`alert`,className:`mt-3 text-copy-14 text-negative`,children:[`Could not load conversion contracts: `,ws(I.error)]}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>void I.refetch(),children:`Retry contracts`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(TT,{workspace:he,onPrimaryAction:We,actionPending:ve,actionError:_t?null:r,contracts:te,selectedContractId:ne?.id??null,onSelectContract:e=>M(e||null),contractError:I.isError?ws(I.error):null,onRetryContracts:()=>void I.refetch(),onRetryEvidence:()=>{Promise.all([R.refetch(),z.refetch()])},onChangeGoogleAdsSelection:Ae,onChangeGtmSelection:je,onAddContract:()=>We(`declare-contract`)}),a?(0,Q.jsx)(`p`,{role:`status`,className:`page-section text-copy-14 text-secondary`,children:a}):null,s?(0,Q.jsxs)(`section`,{id:`google-ads-connect-panel`,className:`page-section-divider`,"aria-labelledby":`google-ads-connect-title`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Google Ads`}),(0,Q.jsx)(`h3`,{id:`google-ads-connect-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Connect read-only access`})]})}),r?(0,Q.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:r}):null,(0,Q.jsxs)(`form`,{className:`max-w-xl`,onSubmit:ci(async e=>{e.preventDefault(),await Pe()}),children:[(0,Q.jsxs)(`label`,{htmlFor:`google-ads-developer-token`,className:kT,children:[`Developer token`,(0,Q.jsx)(`input`,{id:`google-ads-developer-token`,type:`password`,autoComplete:`off`,value:l,onChange:e=>u(e.target.value),className:OT,placeholder:`Required only when this project has no saved token`})]}),(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Canonry stores this securely. It never appears in saved evidence.`}),(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,Q.jsx)(fs,{type:`submit`,disabled:oe.isPending,children:oe.isPending?`Starting…`:`Continue to Google`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:De,children:`Cancel`})]})]})]}):null,d===`google-ads`?(0,Q.jsxs)(`section`,{id:`google-ads-selection-panel`,className:`page-section-divider`,"aria-labelledby":`google-ads-selection-title`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Google Ads`}),(0,Q.jsx)(`h3`,{id:`google-ads-selection-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Select customer context`})]})}),dt?(0,Q.jsxs)(`div`,{role:`alert`,className:`mb-4 flex flex-wrap items-center gap-3 text-label-14 text-negative`,children:[(0,Q.jsx)(`span`,{children:dt}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:vt,children:`Retry customer list`})]}):null,r?(0,Q.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:r}):null,$e?(0,Q.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:`The saved customer is no longer accessible. Choose another customer before saving.`}):null,(0,Q.jsxs)(`div`,{className:`grid max-w-2xl gap-4 sm:grid-cols-2`,children:[(0,Q.jsxs)(zT,{id:`google-ads-customer`,label:`Customer account`,value:_,onChange:e=>{m(!0),v(e);let t=Ge.find(t=>t.customerId===e);b(t?.parentCustomerId??``)},disabled:H.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:H.isLoading?`Loading accessible customers…`:`Select a customer`}),Ye?(0,Q.jsxs)(`option`,{value:_,disabled:$e,children:[`Saved customer `,_,` (`,at,`)`]}):null,Ge.map(e=>(0,Q.jsx)(`option`,{value:e.customerId,children:e.descriptiveName??`Customer ${e.customerId}`},e.customerId))]}),(0,Q.jsxs)(`label`,{htmlFor:`google-ads-login-customer`,className:kT,children:[`Manager account ID (optional)`,(0,Q.jsx)(`input`,{id:`google-ads-login-customer`,className:OT,value:y,onChange:e=>{m(!0),b(e.target.value)},placeholder:`Use only when a manager context is required`})]})]}),ft?(0,Q.jsx)(`p`,{role:`status`,className:`mt-3 text-copy-14 ${H.data?.truncated?`text-caution`:`text-secondary`}`,children:ft}):null,(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,Q.jsx)(fs,{type:`button`,disabled:ce.isPending||H.isLoading||H.isError||$e||!_,onClick:ci(Ie),children:ce.isPending?`Saving…`:`Save customer selection`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:Oe,children:`Cancel`})]}),P.data?.connected?(0,Q.jsx)(VT,{providerLabel:`Google Ads`,disabled:ve,onDisconnect:Re}):null]}):null,d===`gtm`?(0,Q.jsxs)(`section`,{id:`gtm-selection-panel`,className:`page-section-divider`,"aria-labelledby":`gtm-selection-title`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Google Tag Manager`}),(0,Q.jsx)(`h3`,{id:`gtm-selection-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Select container context`})]})}),dt?(0,Q.jsxs)(`div`,{role:`alert`,className:`mb-4 flex flex-wrap items-center gap-3 text-label-14 text-negative`,children:[(0,Q.jsx)(`span`,{children:dt}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:yt,children:re.isError?`Retry account list`:U.isError?`Retry container list`:`Retry workspace list`})]}):null,r?(0,Q.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:r}):null,it?(0,Q.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:it}):null,(0,Q.jsxs)(`div`,{className:`grid max-w-3xl gap-4 sm:grid-cols-3`,children:[(0,Q.jsxs)(zT,{id:`gtm-account`,label:`Account`,value:x,onChange:e=>{g(!0),e!==x&&(w(``),E(``)),S(e)},disabled:re.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:re.isLoading?`Loading accounts…`:`Select an account`}),Xe?(0,Q.jsxs)(`option`,{value:x,disabled:et,children:[`Saved account `,x,` (`,ot,`)`]}):null,Ke.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Q.jsxs)(zT,{id:`gtm-container`,label:`Container`,value:C,onChange:e=>{g(!0),e!==C&&E(``),w(e)},disabled:!x||U.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:U.isLoading?`Loading containers…`:`Select a container`}),Ze?(0,Q.jsxs)(`option`,{value:C,disabled:tt,children:[`Saved container `,C,` (`,st,`)`]}):null,qe.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Q.jsxs)(zT,{id:`gtm-workspace`,label:`Draft workspace (optional)`,value:T,onChange:e=>{g(!0),E(e)},disabled:!C||ae.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:ae.isLoading?`Loading workspaces…`:`No draft workspace`}),Qe?(0,Q.jsxs)(`option`,{value:T,disabled:nt,children:[`Saved draft workspace `,T,` (`,ct,`)`]}):null,Je.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,Q.jsxs)(`div`,{className:`mt-3 grid max-w-3xl gap-2 text-label-14 sm:grid-cols-3`,children:[pt?(0,Q.jsx)(`p`,{role:`status`,className:re.data?.truncated?`text-caution`:`text-secondary`,children:pt}):null,mt?(0,Q.jsx)(`p`,{role:`status`,className:U.data?.truncated?`text-caution`:`text-secondary`,children:mt}):null,ht?(0,Q.jsx)(`p`,{role:`status`,className:ae.data?.truncated?`text-caution`:`text-secondary`,children:ht}):null]}),(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,Q.jsx)(fs,{type:`button`,disabled:le.isPending||re.isLoading||U.isLoading||ae.isLoading&&!!T||gt||rt||!x||!C,onClick:ci(Le),children:le.isPending?`Saving…`:`Save container selection`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:Oe,children:`Cancel`})]}),F.data?.connected?(0,Q.jsx)(VT,{providerLabel:`Tag Manager`,disabled:ve,onDisconnect:ze}):null]}):null,D?(0,Q.jsxs)(`section`,{id:`conversion-integrity-contract-form`,className:`page-section-divider`,"aria-labelledby":`conversion-integrity-contract-form-title`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Declared conversion`}),(0,Q.jsx)(`h3`,{id:`conversion-integrity-contract-form-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Declare the expected path`})]})}),r?(0,Q.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:r}):null,(0,Q.jsxs)(`form`,{onSubmit:ci(async e=>{e.preventDefault(),await Ue()}),children:[(0,Q.jsxs)(`div`,{className:`grid max-w-3xl gap-4 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{htmlFor:`contract-name`,className:kT,children:[`Conversion name`,(0,Q.jsx)(`input`,{id:`contract-name`,required:!0,maxLength:120,className:OT,value:k.name,onChange:e=>A(t=>({...t,name:e.target.value})),placeholder:`Booking completed`})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-event-name`,className:kT,children:[`Website event`,(0,Q.jsx)(`input`,{id:`contract-event-name`,required:!0,className:OT,value:k.eventName,onChange:e=>A(t=>({...t,eventName:e.target.value})),placeholder:`booking_complete`})]}),(0,Q.jsx)(HT,{id:`contract-conversion-action`,label:`Google Ads conversion action`,options:L?.googleAds.conversionActions??[],synced:L?.googleAds.syncedAt!=null,loading:ee.isLoading,failed:ee.isError,onRetry:()=>void ee.refetch(),emptyHint:`Run a Google Ads sync to list conversion actions.`,value:k.conversionActionId,onChange:e=>A(t=>({...t,conversionActionId:e}))}),(0,Q.jsx)(HT,{id:`contract-gtm-tag`,label:`Tag Manager tag`,options:L?.gtm.tags??[],synced:L?.gtm.syncedAt!=null,loading:ee.isLoading,failed:ee.isError,onRetry:()=>void ee.refetch(),emptyHint:`Run a Tag Manager sync to list tags.`,value:k.tagId,onChange:e=>A(t=>({...t,tagId:e}))})]}),(0,Q.jsxs)(`details`,{className:`inline-disclosure mt-5 max-w-3xl`,children:[(0,Q.jsx)(`summary`,{children:`Additional matching rules`}),(0,Q.jsxs)(`div`,{className:`mt-4 grid gap-4 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{htmlFor:`contract-conversion-id`,className:kT,children:[`Google conversion ID (optional)`,(0,Q.jsx)(`input`,{id:`contract-conversion-id`,className:OT,value:k.conversionId,onChange:e=>A(t=>({...t,conversionId:e.target.value}))})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-conversion-label`,className:kT,children:[`Google conversion label (optional)`,(0,Q.jsx)(`input`,{id:`contract-conversion-label`,className:OT,value:k.conversionLabel,onChange:e=>A(t=>({...t,conversionLabel:e.target.value}))})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-trigger-ids`,className:kT,children:[`Trigger IDs`,(0,Q.jsx)(`input`,{id:`contract-trigger-ids`,className:OT,value:k.triggerIds,onChange:e=>A(t=>({...t,triggerIds:e.target.value})),placeholder:`Comma-separated, optional`})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-variable-ids`,className:kT,children:[`Variable IDs`,(0,Q.jsx)(`input`,{id:`contract-variable-ids`,className:OT,value:k.variableIds,onChange:e=>A(t=>({...t,variableIds:e.target.value})),placeholder:`Comma-separated, optional`})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-campaign-ids`,className:kT,children:[`Campaign IDs`,(0,Q.jsx)(`input`,{id:`contract-campaign-ids`,className:OT,value:k.campaignIds,onChange:e=>A(t=>({...t,campaignIds:e.target.value})),placeholder:`Optional campaign-specific goal checks`})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-production-hosts`,className:kT,children:[`Production hosts`,(0,Q.jsx)(`input`,{id:`contract-production-hosts`,className:OT,value:k.productionHosts,onChange:e=>A(t=>({...t,productionHosts:e.target.value})),placeholder:`example.com`})]})]}),(0,Q.jsxs)(`fieldset`,{className:`mt-5 border-t border-subtle pt-4`,children:[(0,Q.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`Required evidence`}),(0,Q.jsxs)(`div`,{className:`mt-3 grid gap-3 sm:grid-cols-2`,children:[(0,Q.jsx)(BT,{id:`contract-primary-action`,checked:k.requirePrimaryAction,onChange:e=>A(t=>({...t,requirePrimaryAction:e})),children:`Google Ads action is primary`}),(0,Q.jsx)(BT,{id:`contract-biddable-goal`,checked:k.requireBiddableGoal,onChange:e=>A(t=>({...t,requireBiddableGoal:e})),children:`Google Ads goal is biddable`}),(0,Q.jsx)(BT,{id:`contract-runtime-verification`,checked:k.verificationRequired,onChange:e=>A(t=>({...t,verificationRequired:e})),children:`Runtime proof is required`}),(0,Q.jsx)(BT,{id:`contract-transaction-id`,checked:k.requireTransactionId,onChange:e=>A(t=>({...t,requireTransactionId:e})),children:`Transaction ID is required`}),(0,Q.jsx)(BT,{id:`contract-value`,checked:k.requireValue,onChange:e=>A(t=>({...t,requireValue:e})),children:`Conversion value is required`}),(0,Q.jsx)(BT,{id:`contract-currency`,checked:k.requireCurrency,onChange:e=>A(t=>({...t,requireCurrency:e})),children:`Currency is required`})]})]})]}),(0,Q.jsx)(`p`,{className:`mt-4 max-w-2xl text-copy-14 text-secondary`,children:`This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version.`}),(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,Q.jsx)(fs,{type:`submit`,disabled:me.isPending,children:me.isPending?`Saving…`:`Save conversion contract`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:G,children:`Cancel`})]})]})]}):null]})}var WT=6e4,GT=[`7d`,`14d`,`30d`],KT=`not available`,qT=`Figures come from the stored Google Ads snapshot; this view never calls Google. The window ends on the newest CLOSED day, because the capture day is only partly recorded and would read as a drop. A calendar day the provider returned no row for is zero delivery, so it is charted as zero. Rates with a zero denominator read "not available", never 0%.`,JT=`No Google Ads snapshot stored yet`,YT=`Connect a Google Ads account in Conversion Integrity below, choose the customer, then run a Google Ads sync. Spend, clicks, impressions, and conversions appear here once the first snapshot is stored.`,XT=`No closed days yet`,ZT=`The stored snapshot covers no completed day yet. Figures appear after a full day closes in the account time zone; the day a snapshot is captured is partial and is left out on purpose. If this persists, check the latest Google Ads sync in Activity.`,QT={"insufficient-history":`Period change is hidden: the stored snapshot does not cover a prior period of equal length yet.`},$T=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),eE=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),tE=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function nE(e,t){return e===null||!Number.isFinite(e)?KT:t===null?tE.format(e/1e6):ll(e,t)}function rE(e){return e===null||!Number.isFinite(e)?KT:Ut(e)}function iE(e,t){return e===null||!Number.isFinite(e)?`${KT} vs prior ${t}d`:e===0?`no change vs prior ${t}d`:`${e>0?`↑`:`↓`} ${Ut(Math.abs(e))} vs prior ${t}d`}function aE(e){return e===`enabled`?`positive`:e===`paused`?`caution`:`neutral`}function oE(e){return e===`enabled`?`Enabled`:e===`paused`?`Paused`:e===`removed`?`Removed`:`Unknown`}function sE(e,t){return t===`none`||e===null||!Number.isFinite(e)||e===0?`text-muted`:(t===`up-good`?e>0:e<0)?`text-positive`:`text-negative`}function cE({projectName:e}){let[t,n]=(0,Z.useState)(`14d`),[r,i]=(0,Z.useState)(()=>new Set([`costMicros`,`conversions`])),a=W({...go({client:Y,path:{name:e},query:{window:t}}),staleTime:WT}),o=a.data,s=(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h2`,{id:`google-ads-performance-title`,className:`text-heading-20 text-heading`,children:`Google Ads performance`}),(0,Q.jsx)(X,{text:qT})]}),o?.source?(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[Yr(o.startDate),` to `,Yr(o.endDate),` · `,o.days,` closed `,o.days===1?`day`:`days`]}):null]}),(0,Q.jsx)(Tu,{windows:GT,value:t,onChange:n,label:`Google Ads time period`})]});if(a.isLoading)return(0,Q.jsxs)(`section`,{className:`page-section`,"aria-busy":`true`,"aria-labelledby":`google-ads-performance-title`,children:[s,(0,Q.jsx)(`div`,{"aria-hidden":`true`,className:`mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4`,children:[0,1,2,3].map(e=>(0,Q.jsxs)(`div`,{className:`page-skeleton-card`,children:[(0,Q.jsx)(`div`,{className:`skeleton-text w-20`}),(0,Q.jsx)(`div`,{className:`skeleton-text-sm w-28`})]},e))}),(0,Q.jsx)(`p`,{role:`status`,className:`sr-only`,children:`Loading Google Ads performance…`})]});if(a.isError||!o)return(0,Q.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`google-ads-performance-title`,children:[s,(0,Q.jsxs)(`p`,{role:`alert`,className:`mt-4 text-copy-14 text-negative`,children:[`Could not load Google Ads performance: `,ws(a.error)]}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>void a.refetch(),children:`Retry performance`})]});let{totals:c,daily:l,campaigns:u,comparison:d,comparisonUnavailableReason:f,source:p}=o;if(!p){let e=f===`insufficient-history`;return(0,Q.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`google-ads-performance-title`,children:[s,(0,Q.jsxs)(`div`,{className:`mt-4 max-w-2xl material-base p-5`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:e?XT:JT}),(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:e?ZT:YT})]})]})}let m=p.currencyCode,h=p.campaignsInInventory>0&&p.campaignsQueried<p.campaignsInInventory?{queried:p.campaignsQueried,inInventory:p.campaignsInInventory}:null,g=c.costMicros>0&&c.conversions===0,_=[{key:`spend`,comparable:!0,label:`Spend`,value:nE(c.costMicros,m),change:d?.change.costMicros??null,direction:`none`,seriesKey:`costMicros`},{key:`conversions`,comparable:!0,label:`Conversions`,value:eE.format(c.conversions),change:d?.change.conversions??null,direction:`up-good`,seriesKey:`conversions`},{key:`cost-per-conversion`,label:`Cost / conv.`,value:g?`no conversions`:nE(c.costPerConversionMicros,m),change:null,comparable:!1,direction:`down-good`,seriesKey:null},{key:`conversion-rate`,comparable:!0,label:`Conv. rate`,value:rE(c.conversionRate),change:d?.change.conversionRate??null,direction:`up-good`,seriesKey:null}],v=[{key:`clicks`,label:`Clicks`,value:$T.format(c.clicks),seriesKey:`clicks`},{key:`impressions`,label:`Impressions`,value:$T.format(c.impressions),seriesKey:`impressions`},{key:`ctr`,label:`CTR`,value:rE(c.ctr),seriesKey:`ctr`},{key:`cpc`,label:`CPC`,value:nE(c.cpcMicros,m),seriesKey:null}],y={costMicros:{label:`Spend`,color:zr[1],axisId:`spend`,formatValue:e=>nE(e,m)},conversions:{label:`Conversions`,color:zr[0],axisId:`conversions`,formatValue:e=>eE.format(e)},clicks:{label:`Clicks`,color:zr[2],axisId:`clicks`,formatValue:e=>$T.format(e)},impressions:{label:`Impressions`,color:zr[3],axisId:`impressions`,formatValue:e=>$T.format(e)},ctr:{label:`CTR`,color:zr[4],axisId:`ctr`,formatValue:e=>rE(e)}},b=[...r].map(e=>({dataKey:e,...y[e]}));return(0,Q.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`google-ads-performance-title`,children:[s,h===null?null:(0,Q.jsxs)(`p`,{role:`status`,className:`mt-3 text-copy-14 text-caution`,children:[`Totals cover `,$T.format(h.queried),` of`,` `,$T.format(h.inInventory),` campaigns, so they are a subset of the account.`]}),p.truncated?(0,Q.jsx)(`p`,{role:`status`,className:`mt-3 text-copy-14 text-caution`,children:`The provider returned a bounded result, so some rows are missing from the figures below.`}):null,!d&&f===`insufficient-history`?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:QT[`insufficient-history`]}):null,(0,Q.jsx)(`div`,{className:`mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4`,children:_.map(e=>{let n=e.seriesKey!==null&&r.has(e.seriesKey),a=n&&r.size===1,o=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5 text-label-12 text-secondary`,children:[e.seriesKey?(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`size-1.5 shrink-0 rounded-full`,style:{backgroundColor:n?y[e.seriesKey].color:`var(--color-mono-600)`}}):null,e.label]}),(0,Q.jsx)(`span`,{className:`mt-0.5 block text-label-18 tabular-nums text-strong`,children:e.value}),d&&e.comparable?(0,Q.jsx)(`span`,{className:`block text-label-12 tabular-nums ${sE(e.change,e.direction)}`,children:iE(e.change,d.days)}):(0,Q.jsx)(`span`,{className:`block text-label-12 text-muted`,children:e.comparable?`no prior ${t} period stored`:`\xA0`})]});return e.seriesKey===null?(0,Q.jsx)(`div`,{className:`material-base px-3 py-2`,children:o},e.key):(0,Q.jsx)(`button`,{type:`button`,"aria-pressed":n,disabled:a,onClick:()=>i(t=>{let n=new Set(t);return n.has(e.seriesKey)?n.delete(e.seriesKey):n.add(e.seriesKey),n.size===0?t:n}),className:`rounded-md border px-3 py-2 text-left transition-colors ${n?`border-strong bg-surface-active`:`border-subtle bg-surface-subtle hover:bg-surface-hover`} ${a?`cursor-default`:``}`,children:o},e.key)})}),(0,Q.jsx)(`dl`,{className:`mt-2 flex flex-wrap gap-x-6 gap-y-1 rounded-md border border-subtle bg-surface-subtle px-3 py-2`,children:v.map(e=>{let t=e.seriesKey!==null&&r.has(e.seriesKey),n=t&&r.size===1,a=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`dt`,{className:`flex items-center gap-1.5 text-label-12 text-secondary`,children:[e.seriesKey?(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`size-1.5 shrink-0 rounded-full`,style:{backgroundColor:t?y[e.seriesKey].color:`var(--color-mono-600)`}}):null,e.label]}),(0,Q.jsx)(`dd`,{className:`text-label-14 tabular-nums text-strong`,children:e.value})]});return e.seriesKey===null?(0,Q.jsx)(`div`,{className:`flex items-baseline gap-1.5`,children:a},e.key):(0,Q.jsx)(`button`,{type:`button`,"aria-pressed":t,disabled:n,onClick:()=>i(t=>{let n=new Set(t);return n.has(e.seriesKey)?n.delete(e.seriesKey):n.add(e.seriesKey),n.size===0?t:n}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${n?`cursor-default`:`hover:bg-surface-hover`}`,children:a},e.key)})}),(0,Q.jsxs)(`div`,{className:`mt-4`,children:[(0,Q.jsx)(Vr,{data:l,xKey:`date`,series:b,xTickFormatter:Hr,labelFormatter:Yr}),(0,Q.jsx)(`ul`,{className:`sr-only`,children:l.map(e=>(0,Q.jsxs)(`li`,{children:[Yr(e.date),`:`,` `,b.map(t=>{let n=e[t.dataKey];return`${t.label} ${n===null?KT:y[t.dataKey].formatValue(n)}`}).join(`, `),e.origin===`filled`?`, no delivery reported`:``]},e.date))})]}),(0,Q.jsxs)(`div`,{className:`page-section-divider`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Campaign performance`})}),(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Google Ads campaign performance for the selected window`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Campaign`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Status`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Impressions`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Clicks`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Spend`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Conversions`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`CTR`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Cost / conv.`})]})}),(0,Q.jsx)(`tbody`,{children:u.length===0?(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:8,className:`text-secondary`,children:`No campaign delivered in this window.`})}):u.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-xs truncate text-strong`,title:e.name??e.campaignId,children:e.name??(0,Q.jsx)(`span`,{className:`font-mono text-secondary`,children:e.campaignId})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:aE(e.status),children:oE(e.status)})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:$T.format(e.totals.impressions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:$T.format(e.totals.clicks)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-strong`,children:nE(e.totals.costMicros,m)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:eE.format(e.totals.conversions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:rE(e.totals.ctr)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums`,children:e.totals.costMicros>0&&e.totals.conversions===0?(0,Q.jsx)(J,{tone:`caution`,children:`no conversions`}):(0,Q.jsx)(`span`,{className:`text-secondary`,children:nE(e.totals.costPerConversionMicros,m)})})]},e.campaignId))})]})}),(0,Q.jsxs)(`details`,{className:`inline-disclosure mt-3`,children:[(0,Q.jsx)(`summary`,{children:`Performance data details`}),(0,Q.jsxs)(`dl`,{className:`mt-3 grid gap-x-6 gap-y-3 text-label-14 sm:grid-cols-2 lg:grid-cols-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Snapshot captured`}),(0,Q.jsx)(`dd`,{className:`mt-1 text-secondary`,children:Ur(Gr(p.capturedAt))})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Google Ads customer`}),(0,Q.jsx)(`dd`,{className:`mt-1 text-secondary`,children:p.customerId})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Latest closed day`}),(0,Q.jsx)(`dd`,{className:`mt-1 text-secondary`,children:Yr(p.asOfDate)})]}),p.openDate?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Open day excluded`}),(0,Q.jsx)(`dd`,{className:`mt-1 text-secondary`,children:Yr(p.openDate)})]}):null,p.timeZone?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Account time zone`}),(0,Q.jsxs)(`dd`,{className:`mt-1 text-secondary`,children:[`Days close in `,p.timeZone]})]}):null]})]})]})]})}var lE={proposed:{label:`New`,tone:`caution`},confirmed:{label:`Included`,tone:`positive`},excluded:{label:`Excluded`,tone:`neutral`}};function uE(e){return e.trim().toLocaleLowerCase()}function dE(e,t){return!t||`${e.name} ${(e.urls??[e.url]).join(` `)}`.toLocaleLowerCase().includes(t)}function fE({property:e}){let t=e.urls??[e.url];return t.length<=1?(0,Q.jsx)(`span`,{children:t[0]??`No URL`}):(0,Q.jsxs)(`details`,{children:[(0,Q.jsxs)(`summary`,{className:`cursor-pointer text-label-12-strong text-primary`,children:[t.length,` URLs`]}),(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1`,children:t.map(e=>(0,Q.jsx)(`li`,{className:`break-all text-label-12-mono text-secondary`,children:e},e))})]})}function pE({canEdit:e,draft:t,onDraftChange:n,onReviewSitemap:r,reviewState:i,onAddProperty:a,propertyCount:o,onContinue:s,isBusy:c}){let[l,u]=(0,Z.useState)(!1),d=!e||c||i===`reviewing`,f=d||!t.sitemapUrl.trim()||!t.examplePropertyUrl.trim()&&!t.propertyPathPattern.trim();function p(e,r){n({...t,[e]:r})}return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-import-heading`,"aria-busy":i===`reviewing`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h2`,{id:`advanced-measurement-import-heading`,className:`text-heading-20 text-heading`,children:`Add Properties`})}),e?null:(0,Q.jsxs)(`div`,{className:`mt-4 flex items-center gap-2 text-label-14 text-secondary`,children:[(0,Q.jsx)(J,{tone:`neutral`,children:`Viewer access`}),(0,Q.jsx)(`span`,{children:`You can inspect this setup.`})]}),e&&a?(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-2`,role:`group`,"aria-label":`Add Properties method`,children:[(0,Q.jsx)(q,{type:`button`,disabled:d,variant:l?`outline`:`default`,onClick:()=>u(!1),children:`Import sitemap`}),(0,Q.jsx)(q,{type:`button`,disabled:d,variant:l?`default`:`outline`,onClick:()=>u(!0),children:`Add manually`})]}):null,l&&a?(0,Q.jsxs)(`div`,{className:`mt-5 space-y-5`,children:[(0,Q.jsx)(gE,{onSave:a,onCancel:()=>u(!1)}),o>0?(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-t border-default pt-4`,children:[(0,Q.jsxs)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:[o,` `,o===1?`Property`:`Properties`,` added`]}),(0,Q.jsxs)(q,{type:`button`,disabled:d,onClick:s,children:[`Continue with `,o,` `,o===1?`Property`:`Properties`]})]}):null]}):(0,Q.jsxs)(`form`,{className:`mt-5 space-y-4`,onSubmit:e=>{e.preventDefault(),!f&&r(t)},children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`advanced-measurement-sitemap-url`,className:`text-label-14-strong text-heading`,children:`Sitemap URL`}),(0,Q.jsx)(`input`,{id:`advanced-measurement-sitemap-url`,type:`url`,value:t.sitemapUrl,disabled:d,onChange:e=>p(`sitemapUrl`,e.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-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`advanced-measurement-example-property-url`,className:`text-label-14-strong text-heading`,children:`Example Property page`}),(0,Q.jsx)(`input`,{id:`advanced-measurement-example-property-url`,type:`url`,required:!t.propertyPathPattern.trim(),value:t.examplePropertyUrl,disabled:d,onChange:e=>p(`examplePropertyUrl`,e.target.value),placeholder:`https://example.com/products/example`,className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:`This shows Canonry the Property URL pattern. Or enter the pattern under More import options.`})]}),(0,Q.jsxs)(`details`,{className:`material-base p-3`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-label-14-strong text-heading`,children:`More import options`}),(0,Q.jsxs)(`div`,{className:`mt-4 space-y-4`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`advanced-measurement-preferred-host`,className:`text-label-14-strong text-heading`,children:`Use URLs from this domain`}),(0,Q.jsx)(`input`,{id:`advanced-measurement-preferred-host`,value:t.preferredHost,disabled:d,onChange:e=>p(`preferredHost`,e.target.value),placeholder:`example.com`,className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`advanced-measurement-property-path-pattern`,className:`text-label-14-strong text-heading`,children:`Property URL pattern`}),(0,Q.jsx)(`input`,{id:`advanced-measurement-property-path-pattern`,value:t.propertyPathPattern,disabled:d,onChange:e=>p(`propertyPathPattern`,e.target.value),placeholder:`/products/*`,className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,Q.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`advanced-measurement-additional-host`,className:`text-label-14-strong text-heading`,children:`Additional URL domain`}),(0,Q.jsx)(`input`,{id:`advanced-measurement-additional-host`,value:t.additionalHost,disabled:d,onChange:e=>p(`additionalHost`,e.target.value),placeholder:`properties.example.com`,className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`advanced-measurement-additional-path-pattern`,className:`text-label-14-strong text-heading`,children:`Additional URL pattern`}),(0,Q.jsx)(`input`,{id:`advanced-measurement-additional-path-pattern`,value:t.additionalPathPattern,disabled:d,onChange:e=>p(`additionalPathPattern`,e.target.value),placeholder:`/*`,className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary md:col-span-2`,children:`Use both fields when each Property also has a matching page on another domain.`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`advanced-measurement-excluded-paths`,className:`text-label-14-strong text-heading`,children:`Ignore these URL paths`}),(0,Q.jsx)(`textarea`,{id:`advanced-measurement-excluded-paths`,value:t.excludedPaths,disabled:d,onChange:e=>p(`excludedPaths`,e.target.value),placeholder:`/products/archive`,rows:3,className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-copy-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:`One path per line. Use * at the beginning or end to match similar pages.`})]})]})]}),(0,Q.jsx)(q,{type:`submit`,disabled:f,children:i===`reviewing`?`Reviewing sitemap…`:`Review sitemap`})]})]})}function mE({canEdit:e,properties:t,propertiesState:n,propertiesSearch:r,onPropertiesSearchChange:i,selectedPropertyIds:a,onSelectedPropertyIdsChange:o,onContinue:s,isContinuing:c=!1,onRetryProperties:l,onReturnToImport:u,maxVisibleProperties:d,onShowAllProperties:f}){let p=uE(r),m=t.filter(e=>dE(e,p)),h=Math.max(1,d??m.length),g=m.slice(0,h),_=new Set(a),v=t.filter(e=>_.has(e.id)).map(e=>e.id),y=g.length<m.length;function b(e){let n=new Set(e);o(t.filter(e=>n.has(e.id)).map(e=>e.id))}function x(t,n){if(!e||c)return;let r=new Set(v);n?r.add(t):r.delete(t),b(r)}function S(){e&&!c&&b([...v,...g.map(e=>e.id)])}function C(){e&&!c&&o([])}function w(){e&&!c&&v.length!==0&&s(v)}return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-properties-heading`,"aria-busy":n===`loading`||c,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{id:`advanced-measurement-properties-heading`,className:`text-heading-20 text-heading`,children:`Properties`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Choose the Properties to include, then continue.`})]}),e?null:(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:`Viewing only. Property changes are unavailable.`}),n===`loading`?(0,Q.jsxs)(`div`,{className:`mt-5 material-base p-4`,children:[(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading Properties…`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`If this does not finish, refresh the list.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:l,children:`Refresh Properties`})]}):null,n===`error`?(0,Q.jsxs)(`div`,{className:`mt-5 material-base p-4`,children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:`Could not load Properties. Retry to request the current list.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:l,children:`Retry`})]}):null,n===`ready`&&t.length===0?(0,Q.jsxs)(`div`,{className:`mt-5 material-base p-4`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No Properties were found.`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Check the sitemap and review it again.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,disabled:!e,onClick:u,children:`Review sitemap`})]}):null,n===`ready`&&t.length>0?(0,Q.jsxs)(`div`,{className:`mt-5`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3`,children:[(0,Q.jsxs)(`label`,{className:`block min-w-48 flex-1`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Search Properties`}),(0,Q.jsx)(`input`,{type:`search`,value:r,disabled:c,onChange:e=>i(e.target.value),className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400`})]}),e?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:c,onClick:S,children:`Select all shown`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,disabled:c||v.length===0,onClick:C,children:`Clear selection`})]}):null]}),m.length===0?(0,Q.jsxs)(`div`,{className:`mt-4 material-base p-4`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No Properties match this search.`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Clear the search or review the sitemap again.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,disabled:!e,onClick:u,children:`Review sitemap`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center justify-between gap-2 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`p`,{children:[`Showing `,g.length,` of `,m.length,` Properties`]}),(0,Q.jsxs)(`p`,{children:[v.length,` of `,t.length,` selected`]})]}),(0,Q.jsx)(`div`,{className:`mt-2 overflow-x-auto rounded-md border border-default`,children:(0,Q.jsxs)(`table`,{className:`w-full min-w-150 text-left text-label-14`,"aria-label":`Properties to review`,children:[(0,Q.jsx)(`thead`,{className:`bg-surface-subtle text-label-12-strong normal-case text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`px-3 py-2`,children:`Property`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-3 py-2`,children:`URL`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-3 py-2`,children:`State`}),e?(0,Q.jsx)(`th`,{scope:`col`,className:`px-3 py-2 text-right`,children:`Include`}):null]})}),(0,Q.jsx)(`tbody`,{children:g.map(t=>{let n=lE[t.state];return(0,Q.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-3 py-3 text-label-14-strong text-heading`,children:t.name}),(0,Q.jsx)(`td`,{className:`max-w-96 px-3 py-3 text-label-12-mono text-secondary`,children:(0,Q.jsx)(fE,{property:t})}),(0,Q.jsx)(`td`,{className:`px-3 py-3`,children:(0,Q.jsx)(J,{tone:n.tone,children:n.label})}),e?(0,Q.jsx)(`td`,{className:`p-0 text-right`,children:(0,Q.jsx)(`label`,{className:`ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center`,children:(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${t.name}`,checked:v.includes(t.id),disabled:c,onChange:e=>x(t.id,e.target.checked),className:`size-6 accent-accent`})})}):null]},t.id)})})]})}),y&&f?(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,disabled:c,onClick:f,children:`Show all Properties`}):null]}),e?(0,Q.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3`,children:[(0,Q.jsx)(q,{type:`button`,variant:`ghost`,disabled:c,onClick:u,children:`Add Properties`}),(0,Q.jsx)(q,{type:`button`,disabled:c||v.length===0,onClick:w,children:c?`Saving Properties…`:`Continue with ${v.length} ${v.length===1?`Property`:`Properties`}`})]}):null]}):null]})}function hE(e){return e.activeStep===`import`?(0,Q.jsx)(pE,{canEdit:e.canEdit,draft:e.importDraft,onDraftChange:e.onImportDraftChange,onReviewSitemap:e.onReviewSitemap,reviewState:e.reviewState,onAddProperty:e.onAddProperty,propertyCount:e.properties.filter(e=>e.state===`confirmed`).length,onContinue:()=>e.onContinue(e.selectedPropertyIds),isBusy:e.isContinuing??!1}):(0,Q.jsx)(mE,{...e})}function gE({property:e,onSave:t,onCancel:n}){let r=(0,Z.useId)(),i=(0,Z.useRef)(null),a=(0,Z.useRef)(!1),[o,s]=(0,Z.useState)(e?.name??``),[c,l]=(0,Z.useState)(e?.aliases.join(`
7
- `)??``),[u,d]=(0,Z.useState)(e?.identityAliases.join(`
8
- `)??``),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(!1),g=`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-copy-14 text-primary focus:border-strong focus:outline-none focus:ring-2 focus:ring-mono-400`;(0,Z.useEffect)(()=>{i.current?.focus()},[]),(0,Z.useEffect)(()=>{!m&&a.current&&(a.current=!1,i.current?.focus())},[m,o]);async function _(){h(!0);try{await t({name:o.trim(),aliases:e?c.split(`
9
- `).map(e=>e.trim()).filter(Boolean):[o.trim()],identityAliases:u.split(`
10
- `).map(e=>e.trim()).filter(Boolean),urls:e?[...e.urls]:[f.trim()]})&&!e&&(s(``),p(``),d(``),a.current=!0)}finally{h(!1)}}return(0,Q.jsxs)(`form`,{className:`max-w-2xl space-y-4`,onSubmit:e=>{e.preventDefault(),_()},"aria-busy":m,children:[(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,htmlFor:`${r}-name`,children:[`Property name`,(0,Q.jsx)(`input`,{ref:i,id:`${r}-name`,required:!0,value:o,disabled:m,onChange:e=>s(e.target.value),className:g})]}),e?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,htmlFor:`${r}-names`,children:[`Names that count as a mention`,(0,Q.jsx)(`textarea`,{id:`${r}-names`,value:c,disabled:m,onChange:e=>l(e.target.value),className:g,rows:3,"aria-describedby":`${r}-names-help`})]}),(0,Q.jsx)(`p`,{id:`${r}-names-help`,className:`text-copy-13 text-secondary`,children:`One name per line. Use names for this specific Property; a shared brand name also matches other Properties.`}),(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{className:`min-h-11 cursor-pointer text-label-14-strong text-heading`,children:`Qualified names (optional)`}),(0,Q.jsxs)(`label`,{className:`block text-copy-13 text-secondary`,htmlFor:`${r}-qualified`,children:[`Longer names that distinguish this Property when a plain name is shared.`,(0,Q.jsx)(`textarea`,{id:`${r}-qualified`,value:u,disabled:m,onChange:e=>d(e.target.value),className:g,rows:3})]})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,htmlFor:`${r}-url`,children:[`Property page URL`,(0,Q.jsx)(`input`,{id:`${r}-url`,type:`url`,pattern:`https?://.*`,title:`Enter a full http or https page URL`,required:!0,value:f,disabled:m,onChange:e=>p(e.target.value),className:g,placeholder:`https://example.com/products/example`})]}),(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`The name matches mentions; the page URL matches citations. You can review both before publishing.`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsx)(q,{type:`submit`,disabled:m||!o.trim(),children:m?`Saving…`:e?`Save Property`:`Add Property`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,disabled:m,onClick:n,children:`Cancel`})]})]})}function _E({properties:e,onSave:t,onEditingChange:n}){let[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(20);function s(e){i(e),n?.(e!==null)}return(0,Q.jsxs)(`section`,{"aria-label":`Property matching`,className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:`Property matching`}),(0,Q.jsx)(X,{text:`Check the names and URLs used to measure each Property. Display names alone do not change matching.`})]}),(0,Q.jsx)(`ul`,{className:`divide-y divide-subtle border-y border-default`,children:e.slice(0,a).map(e=>(0,Q.jsx)(`li`,{className:`py-3`,children:r===e.id&&t?(0,Q.jsx)(gE,{property:e,onCancel:()=>s(null),onSave:async n=>{let r=await t(e.id,n);return r&&s(null),r}}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Q.jsx)(`h5`,{className:`text-label-14-strong text-heading`,children:e.name}),t?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:r!==null,"aria-label":`Edit matching for ${e.name}`,onClick:()=>s(e.id),children:`Edit names`}):null]}),(0,Q.jsxs)(`dl`,{className:`grid gap-x-4 gap-y-1 text-copy-13 sm:grid-cols-[auto_minmax(0,1fr)]`,children:[(0,Q.jsx)(`dt`,{className:`text-secondary`,children:`Mention names`}),(0,Q.jsx)(`dd`,{className:`break-words text-primary`,children:e.aliases.length>0?e.aliases.join(`, `):`No names configured`}),e.identityAliases.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dt`,{className:`text-secondary`,children:`Qualified names`}),(0,Q.jsx)(`dd`,{className:`break-words text-primary`,children:e.identityAliases.join(`, `)})]}):null,(0,Q.jsx)(`dt`,{className:`text-secondary`,children:`Citation URLs`}),(0,Q.jsx)(`dd`,{className:`break-all text-primary`,children:e.urls.length>0?e.urls.join(`, `):`No citation URLs configured`})]})]})},e.id))}),e.length>a?(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>o(e=>e+20),children:`Show more Properties`}):null]})}var vE=20,yE=50,bE=50,xE=50;function SE(e){return e===`viewer`}function CE(e){return e?.status===`unavailable`}function wE(e,t,n){return n?e.includes(t)?[...e]:[...e,t]:e.filter(e=>e!==t)}function TE(e,t){let n=new Map(t.map(e=>[e.id,e.label])),r=e.map(e=>n.get(e)).filter(e=>!!e);return r.length===0?`Not applied`:r.length>3?`${r.length} Properties`:r.join(`, `)}function EE(e,t,n){if(e.kind===`none`)return[];if(e.kind===`all`)return t.map(e=>e.id);if(e.kind===`specific`)return t.filter(t=>e.propertyIds.includes(t.id)).map(e=>e.id);let r=new Set(e.groupIds),i=new Set(n.filter(e=>r.has(e.id)).flatMap(e=>e.propertyIds));return t.filter(e=>i.has(e.id)).map(e=>e.id)}function DE(e,t,n){if(e.kind===`all`)return`every Property (${n})`;if(e.kind===`specific`)return n===1?`1 Property`:`${n} Properties`;let r=e.groupIds.map(e=>t.find(t=>t.id===e)?.name).filter(e=>!!e);return r.length===0?`selected groups`:r.join(` + `)}function OE(e,t){let n=new Set(t.map(e=>e.id)),r=e.propertyIds.filter(e=>n.has(e)).length;return`${e.name} · ${r===1?`1 Property`:`${r} Properties`}`}function kE(e){return e===`matched`?`positive`:e===`duplicate`?`neutral`:e===`ambiguous`||e===`proposed`||e===`excluded`?`caution`:`negative`}function AE(e){return e===`matched`?`Matched`:e===`duplicate`?`Duplicate`:e===`ambiguous`?`Ambiguous`:e===`proposed`?`Property needs review`:e===`excluded`?`Property excluded`:e===`invalid`?`Invalid row`:`Not matched`}function jE(e){return e.status===`duplicate`&&e.duplicateOfRow?`Duplicates row ${e.duplicateOfRow}.`:e.status===`matched`?null:e.reason===`group-label-ambiguous`?`More than one group matches “${e.group}”. Rename duplicate groups, then preview again.`:e.status===`ambiguous`?`More than one Property matches this row. Add an exact URL to choose one.`:e.status===`unmatched`?`No included Property matches this row.`:e.reason===`group-key-conflict`?`The group name “${e.group}” conflicts with an existing setup identity. Rename the group, then preview again.`:e.status===`invalid`?`Check the Property, group, and optional URL fields.`:e.status===`proposed`?`Review this proposed Property before importing it.`:e.status===`excluded`?`Include this Property before importing it.`:e.reason??null}function ME(e){return e.state===`missing`||e.source===`unavailable-tracked-query`||!e.source}function NE(e){return ME(e)?`Unavailable tracked query`:e.text?.trim()||`Unavailable tracked query`}function PE({properties:e,selectedPropertyIds:t,onSelectedPropertyIdsChange:n,legend:r,showBulkActions:i=!0}){let[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(!1),l=a.trim().toLocaleLowerCase(),u=l?e.filter(e=>e.label.toLocaleLowerCase().includes(l)):e,d=s?u:u.slice(0,bE),f=d.length<u.length;function p(){let r=new Set([...t,...d.map(e=>e.id)]);n(e.filter(e=>r.has(e.id)).map(e=>e.id))}return(0,Q.jsxs)(`fieldset`,{children:[(0,Q.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:r}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-end justify-between gap-3`,children:[(0,Q.jsxs)(`label`,{className:`block min-w-48 flex-1`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Search Properties`}),(0,Q.jsx)(`input`,{type:`search`,value:a,onChange:e=>o(e.currentTarget.value),className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400`})]}),i?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:d.length===0,onClick:p,children:`Select all shown`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:t.length===0,onClick:()=>n([]),children:`Clear selection`})]}):null]}),u.length===0?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:`No Properties match this search.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:[`Showing `,d.length,` of `,u.length,` Properties`]}),(0,Q.jsx)(`div`,{className:`mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default`,children:d.map(e=>{let r=t.includes(e.id);return(0,Q.jsxs)(`label`,{className:`flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-label-14 text-primary`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(`input`,{"aria-label":`Select ${e.label}`,checked:r,type:`checkbox`,onChange:r=>n(wE(t,e.id,r.currentTarget.checked))}),(0,Q.jsx)(`span`,{children:e.label})]}),e.urlCount===void 0?null:(0,Q.jsxs)(`span`,{className:`tabular-nums text-secondary`,children:[e.urlCount,` URLs`]})]},e.id)})}),f?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`mt-3 pointer-coarse:min-h-11`,onClick:()=>c(!0),children:`Show all Properties`}):null]})]})}function FE(){return(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 text-label-14 text-secondary`,children:[(0,Q.jsx)(J,{tone:`neutral`,children:`Viewer access`}),(0,Q.jsx)(`span`,{children:`You can inspect this setup.`})]})}function IE({message:e}){return(0,Q.jsxs)(`div`,{role:`status`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4 text-label-14 text-caution`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(J,{tone:`caution`,children:`Unavailable`}),(0,Q.jsx)(`h4`,{className:`text-heading-14`,children:`Measurement setup unavailable`})]}),(0,Q.jsx)(`p`,{className:`mt-2 max-w-2xl text-secondary`,children:e})]})}function LE({value:e}){let[t,n]=(0,Z.useState)(0),[r,i]=(0,Z.useState)(0),[a,o]=(0,Z.useState)(null),s=e.preview,c=s?.counts.needsAttention??0,l=s?.rows.filter(e=>e.status===`matched`)??[],u=s?.rows??[],d=u.filter(e=>e.status!==`matched`),f=Math.max(1,Math.ceil(u.length/yE)),p=Math.min(t,f-1),h=u.slice(p*yE,(p+1)*yE),g=Math.max(1,Math.ceil(d.length/yE)),_=Math.min(r,g-1),v=d.slice(_*yE,(_+1)*yE),y=e.csv.trim().length>0&&!e.isReviewing&&!e.isApplying,b=l.length>0&&!e.isApplying,x=s!==null&&a===s.previewChecksum,S=d.length>0&&_===g-1;(0,Z.useEffect)(()=>{n(0),i(0),o(null)},[s?.previewChecksum]);async function C(t){if(t)try{e.onCsvChange(await t.text())}catch{}}return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-group-import-title`,className:`border-y border-default py-4`,children:[(0,Q.jsxs)(`div`,{className:`max-w-2xl`,children:[(0,Q.jsx)(`h4`,{id:`advanced-measurement-group-import-title`,className:`text-heading-14 text-heading`,children:`Import groups from CSV`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Import group membership once instead of selecting the same Properties repeatedly.`})]}),(0,Q.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,Q.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`CSV file`}),(0,Q.jsx)(`input`,{"aria-label":`Group membership CSV file`,type:`file`,accept:`.csv,text/csv`,disabled:e.isReviewing||e.isApplying,onChange:e=>{C(e.currentTarget.files?.[0])},className:`mt-1 block min-h-11 w-full text-label-14 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-label-14-strong file:text-primary`})]}),(0,Q.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Or paste CSV`}),(0,Q.jsx)(`textarea`,{"aria-label":`Group membership CSV`,rows:5,value:e.csv,disabled:e.isReviewing||e.isApplying,onChange:t=>e.onCsvChange(t.currentTarget.value),placeholder:`property,group,url
11
- 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-copy-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:!y,onClick:()=>{e.onReview()},children:e.isReviewing?`Reviewing CSV…`:`Review CSV`}),(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Use columns named property and group. URL is optional.`})]}),e.error?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:e.error}):null,e.notice?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:e.notice}):null]}),s?(0,Q.jsxs)(`div`,{className:`mt-4 border-t border-default pt-4`,"aria-live":`polite`,children:[(0,Q.jsx)(`h5`,{className:`text-heading-14 text-heading`,children:`Review group membership`}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[s.counts.matchedRows,` matched · `,s.counts.groupsReady,` group`,s.counts.groupsReady===1?``:`s`,` ready`,c>0?` · ${c} need${c===1?`s`:``} attention`:``]}),s.groupChanges.length>0?(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Groups and memberships ready to apply`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Group`}),(0,Q.jsx)(`th`,{children:`Change`}),(0,Q.jsx)(`th`,{children:`Properties`}),(0,Q.jsx)(`th`,{children:`New memberships`})]})}),(0,Q.jsx)(`tbody`,{children:s.groupChanges.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.label}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.action===`create`?`Create group`:`Add to existing group`}),(0,Q.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.targetKeys.length}),(0,Q.jsxs)(`td`,{className:`tabular-nums text-secondary`,children:[e.addedTargetKeys.length,e.unchangedTargetKeys.length>0?` · ${e.unchangedTargetKeys.length} already members`:``]})]},e.groupKey))})]})}):null,s.rows.length>0?(0,Q.jsxs)(`details`,{className:`group/csv-rows mt-3 border-y border-default py-3`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(m,{className:`size-3.5 shrink-0 transition-transform group-open/csv-rows:rotate-90`,"aria-hidden":`true`}),`Review CSV rows (`,s.counts.dataRows,`)`]}),(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`CSV group membership review`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Row`}),(0,Q.jsx)(`th`,{children:`Property`}),(0,Q.jsx)(`th`,{children:`Group`}),(0,Q.jsx)(`th`,{children:`Status`})]})}),(0,Q.jsx)(`tbody`,{children:h.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.dataRow}),(0,Q.jsx)(`td`,{className:`text-heading`,children:e.property}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.group}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(J,{tone:kE(e.status),children:AE(e.status)}),jE(e)?(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:jE(e)}):null]})]},e.dataRow))})]})}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Page `,p+1,` of `,f,` · `,s.rows.length,` rows`]}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:p===0,onClick:()=>n(e=>Math.max(0,e-1)),children:`Previous 50 rows`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:p===f-1,onClick:()=>n(e=>Math.min(f-1,e+1)),children:`Next 50 rows`})]})]}):null,c>0?(0,Q.jsxs)(`details`,{className:`group/csv-fixes mt-3 border-y border-caution-800/30 py-3`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(m,{className:`size-3.5 shrink-0 transition-transform group-open/csv-fixes:rotate-90`,"aria-hidden":`true`}),`Fix `,c,` row`,c===1?``:`s`,` before applying`]}),(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added.`}),(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`CSV rows that need attention`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Row`}),(0,Q.jsx)(`th`,{children:`Property`}),(0,Q.jsx)(`th`,{children:`Group`}),(0,Q.jsx)(`th`,{children:`Issue`})]})}),(0,Q.jsx)(`tbody`,{children:v.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.dataRow}),(0,Q.jsx)(`td`,{className:`text-heading`,children:e.property}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.group}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(J,{tone:kE(e.status),children:AE(e.status)}),jE(e)?(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:jE(e)}):null]})]},e.dataRow))})]})}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Exception page `,_+1,` of `,g]}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:_===0,onClick:()=>i(e=>Math.max(0,e-1)),children:`Previous 50 exceptions`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:_===g-1,onClick:()=>i(e=>Math.min(g-1,e+1)),children:`Review next 50 exceptions`})]}),(0,Q.jsxs)(`label`,{className:`mt-3 flex min-h-11 max-w-xl items-center gap-3 text-label-14 text-heading`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:x,disabled:e.isApplying||!S,onChange:e=>o(e.currentTarget.checked?s.previewChecksum:null),className:`size-4 rounded border-default`}),`I reviewed the exceptions and understand that `,c,` row`,c===1?``:`s`,` will be skipped.`]}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`mt-3 pointer-coarse:min-h-11`,disabled:!b||!x,onClick:()=>{e.onApply(l.map(e=>e.dataRow))},children:e.isApplying?`Applying groups…`:`Apply ${l.length} matched row${l.length===1?``:`s`}`})]}):(0,Q.jsx)(q,{type:`button`,className:`mt-3 pointer-coarse:min-h-11`,disabled:!b,onClick:()=>{e.onApply(l.map(e=>e.dataRow))},children:e.isApplying?`Creating groups…`:`Create ${s.counts.groupsReady} group${s.counts.groupsReady===1?``:`s`} with ${l.length} membership${l.length===1?``:`s`}`})]}):null]})}var RE=`—`;function zE({access:e,availability:t,properties:n,queries:r,selectedQueryIds:i,isApplying:a=!1,isBusy:o=!1,canContinue:s=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:l,onClearQueryAssignments:u,onRemoveQuery:d,onCreateQueries:f,onCreateAndPairQuestions:p,isCreatingQueries:h=!1,createQueriesError:g=null,onManageProjectQueries:_,groups:v,audience:y,onAudienceChange:b,executionOptions:x=[],executionOptionId:S=``,onExecutionOptionChange:C,markets:w=[],marketAssignments:T=[],onSaveMarket:E,marketId:D=``,onMarketChange:O,marketExecutionOptionId:k=``,onMarketExecutionOptionChange:A,onRouteMarket:j,isRoutingMarket:M=!1,isPreviewingMarketRouting:N=!1,marketRoutingImpact:P=null,marketRoutingError:F=null,onRetryMarketRouting:I,marketRoutingNotice:ee=null,assignmentImpact:L=null,isPreviewingAssignmentImpact:R=!1,assignmentImpactError:z=null,onRetryAssignmentImpact:te,assignmentNotice:ne=null,onReplaceAssignments:B,isReplacingAssignments:V=!1,onBack:H,onContinue:re}){let[U,ie]=(0,Z.useState)(``),[W,ae]=(0,Z.useState)(!1),[oe,se]=(0,Z.useState)(!1),[ce,le]=(0,Z.useState)(``),[ue,de]=(0,Z.useState)(``),[fe,pe]=(0,Z.useState)(!1),[me,he]=(0,Z.useState)(null);if(CE(t))return(0,Q.jsx)(`section`,{"aria-label":`Queries`,children:(0,Q.jsx)(IE,{message:t.message})});let ge=SE(e),_e=y,ve=b,ye=EE(_e,n,v),be=ye.length,xe=be>0&&i.length>0&&!a&&!o&&!R&&L!==null&&z===null,Se=u??d,Ce=U.trim().toLocaleLowerCase(),we=Ce?r.filter(e=>NE(e).toLocaleLowerCase().includes(Ce)):r,Te=we.filter(e=>(e.propertyIds?.length??0)===0),Ee=oe?Te:we,De=W?Ee:Ee.slice(0,xE),Oe=De.filter(e=>!ME(e)),G=[...new Set(ce.split(`
12
- `).map(e=>e.trim()).filter(Boolean))],ke=[...ue.matchAll(/\{([a-z][\w-]*)\}/gi)].map(e=>e[1]),Ae=n.filter(e=>ye.includes(e.id)),je=ke.length===0||ue.trim()===``?[]:Ae.map(e=>({propertyId:e.id,text:ke.reduce((t,n)=>t.replaceAll(`{${n}}`,e.label),ue.trim())})),Me=[...new Set(je.map(e=>e.text))];function Ne(){let e=new Set([...i,...Oe.map(e=>e.id)]);c(r.filter(t=>e.has(t.id)).map(e=>e.id))}return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-queries-title`,className:`space-y-5`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{id:`advanced-measurement-queries-title`,children:`Queries`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Choose queries, then assign them to Properties.`})]})}),ge?(0,Q.jsx)(FE,{}):null,ge?null:(0,Q.jsxs)(`fieldset`,{className:`border-y border-default py-4`,children:[(0,Q.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`Apply to`}),(0,Q.jsxs)(`div`,{className:`mt-3 grid max-w-2xl gap-3 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Properties or group`}),(0,Q.jsxs)(`select`,{"aria-label":`Apply to`,value:_e.kind===`none`?``:_e.kind===`all`?`all`:_e.kind===`specific`?`specific`:`group:${_e.groupIds[0]??``}`,onChange:e=>{let t=e.currentTarget.value;t===`all`?ve({kind:`all`}):t===`specific`?ve({kind:`specific`,propertyIds:[]}):t.startsWith(`group:`)&&ve({kind:`groups`,groupIds:[t.slice(6)]})},className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400`,children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Choose where to apply`}),(0,Q.jsxs)(`option`,{value:`all`,children:[`Every Property (`,n.length,`)`]}),v.length>0?(0,Q.jsx)(`optgroup`,{label:`Groups`,children:v.map(e=>{let t=EE({kind:`groups`,groupIds:[e.id]},n,v).length;return(0,Q.jsx)(`option`,{value:`group:${e.id}`,disabled:t===0,children:OE(e,n)},e.id)})}):null,(0,Q.jsx)(`option`,{value:`specific`,children:`Specific Properties…`})]})]}),x.length>0&&C?(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Answer engine`}),(0,Q.jsxs)(`select`,{"aria-label":`Answer engine for these assignments`,value:S,onChange:e=>C(e.currentTarget.value),className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400`,children:[(0,Q.jsx)(`option`,{value:``,children:`Keep existing or use portfolio defaults`}),x.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}):null]}),x.length>0?(0,Q.jsx)(`p`,{className:`mt-2 max-w-2xl text-copy-14 text-secondary`,children:`The selected engine applies to these Property assignments.`}):null,_e.kind===`groups`?(0,Q.jsxs)(`div`,{className:`mt-3 max-w-2xl space-y-3`,children:[(0,Q.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:_e.groupIds.map(e=>{let t=v.find(t=>t.id===e);return t?(0,Q.jsxs)(`span`,{className:`inline-flex min-h-11 items-center gap-1 rounded-md border border-default bg-surface px-2 text-label-14 text-primary`,children:[OE(t,n),(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Remove ${t.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:()=>{let e=_e.groupIds.filter(e=>e!==t.id);ve(e.length>0?{kind:`groups`,groupIds:e}:{kind:`none`})},children:`×`})]},t.id):null})}),v.some(e=>!_e.groupIds.includes(e.id)&&EE({kind:`groups`,groupIds:[e.id]},n,v).length>0)?(0,Q.jsxs)(`label`,{className:`block max-w-sm`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Add another group`}),(0,Q.jsxs)(`select`,{"aria-label":`Add another group`,value:``,onChange:e=>{e.currentTarget.value&&ve({kind:`groups`,groupIds:[..._e.groupIds,e.currentTarget.value]})},className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400`,children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a group`}),v.filter(e=>!_e.groupIds.includes(e.id)).map(e=>{let t=EE({kind:`groups`,groupIds:[e.id]},n,v).length;return(0,Q.jsx)(`option`,{value:e.id,disabled:t===0,children:OE(e,n)},e.id)})]})]}):null,be===0?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-caution`,children:`This group has no included Properties. Add Properties to the group, then try again.`}):null]}):null,_e.kind===`specific`?(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(PE,{legend:`Specific Properties`,properties:n,selectedPropertyIds:_e.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:e=>{ve({kind:`specific`,propertyIds:e})}})}):null,_e.kind===`groups`?(0,Q.jsx)(`p`,{className:`mt-3 max-w-2xl text-copy-13 text-secondary`,children:`Assignments use the group’s current Properties. Later membership changes do not change existing assignments.`}):null]}),!ge&&(E||w.length>0)?(0,Q.jsxs)(`details`,{className:`border-b border-default py-3`,children:[(0,Q.jsxs)(`summary`,{className:`min-h-11 cursor-pointer text-label-14-strong text-heading`,children:[`Markets`,w.length>0?` (${w.length})`:` (optional)`]}),E?(0,Q.jsx)(BE,{markets:w,assignments:T,groups:v,onSave:E,disabled:o,onEditingChange:pe}):null,w.length===0||x.length===0||!O||!A||!j?null:(0,Q.jsxs)(`fieldset`,{className:`border-b border-default pb-4`,children:[(0,Q.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`Market routing`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Choose the answer engine for one saved market. Its existing answer-engine locations stay unchanged.`}),(0,Q.jsxs)(`div`,{className:`mt-3 grid max-w-2xl gap-3 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Market`}),(0,Q.jsxs)(`select`,{"aria-label":`Market to route`,value:D,onChange:e=>O(e.currentTarget.value),className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400`,children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a market`}),w.map(e=>(0,Q.jsxs)(`option`,{value:e.id,children:[e.label,` · `,e.measurementCount,` saved measurement`,e.measurementCount===1?``:`s`]},e.id))]})]}),(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Answer engine`}),(0,Q.jsxs)(`select`,{"aria-label":`Answer engine for this market`,value:k,onChange:e=>A(e.currentTarget.value),className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400`,children:[(0,Q.jsx)(`option`,{value:``,children:`Choose an answer engine`}),x.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]})]}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(q,{type:`button`,size:`sm`,className:`pointer-coarse:min-h-11`,disabled:!D||!k||o||M||N||P===null||P.changedMeasurements===0||F!==null,onClick:()=>{j()},children:M?`Saving market routing…`:`Save market routing`}),ee?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:ee}):null]}),(0,Q.jsxs)(`div`,{className:`mt-2 min-h-5`,children:[N?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Calculating market impact…`}):null,P?(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[P.changedMeasurements,` of `,P.matchedMeasurements,` saved measurement`,P.matchedMeasurements===1?``:`s`,` will change`,` · `,P.addedProviderCalls,` new provider request`,P.addedProviderCalls===1?``:`s`,` · `,P.fullRunProviderCalls,` per full run`]}):F?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:F}),I?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:I,children:`Retry impact`}):null]}):null]})]})]}):null,ge||!f?null:(0,Q.jsxs)(`details`,{open:r.length===0,className:`group/add-queries border-y border-default py-4`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(m,{className:`size-3.5 shrink-0 transition-transform group-open/add-queries:rotate-90`,"aria-hidden":`true`}),`Add queries`]}),(0,Q.jsxs)(`div`,{className:`pt-3`,children:[(0,Q.jsx)(`h4`,{className:`m-0 text-heading-14 text-heading`,children:r.length===0?`Add the queries you want to track`:`Add more queries`}),(0,Q.jsx)(`p`,{className:`mt-1 mb-2 text-copy-14 text-secondary`,children:`One per line. Add them to the project, then apply them to Properties.`}),(0,Q.jsx)(`textarea`,{"aria-label":`New queries, one per line`,className:`w-full rounded border border-strong bg-transparent px-3 py-2 text-copy-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,rows:4,value:ce,onChange:e=>le(e.currentTarget.value),placeholder:`best tools for team collaboration
13
- how to compare project management software`}),g?(0,Q.jsx)(`p`,{role:`alert`,className:`mt-2 text-copy-14 text-negative`,children:g}):null,(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:G.length===0||h||o,onClick:()=>{Promise.resolve(f(G)).then(()=>le(``),()=>{})},children:h?`Adding…`:`Add ${G.length||``} ${G.length===1?`query`:`queries`}`.replace(` `,` `)}),_?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:o,onClick:_,children:`Manage project queries`}):null]}),(0,Q.jsxs)(`details`,{className:`mt-4 border-t border-default pt-4`,children:[(0,Q.jsx)(`summary`,{className:`min-h-11 cursor-pointer text-label-14-strong text-heading`,children:`Write one query for every Property`}),(0,Q.jsxs)(`p`,{className:`mt-1 mb-2 text-copy-14 text-secondary`,children:[`Put `,(0,Q.jsx)(`code`,{className:`rounded bg-bg-elevated px-1`,children:`{property}`}),` where the Property name belongs. You get one query per selected Property.`]}),(0,Q.jsx)(`input`,{"aria-label":`Query pattern`,className:`min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,value:ue,onChange:e=>de(e.target.value),placeholder:`How does {property} compare with alternatives?`}),ue.trim()===``?null:ke.length===0?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-14 text-caution`,children:[`Add `,`{property}`,` to the pattern, or use the box above for a single query.`]}):Ae.length===0?(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-caution`,children:`Select at least one Property to write queries for.`}):(0,Q.jsxs)(`div`,{className:`mt-2 material-base p-3`,children:[(0,Q.jsxs)(`p`,{className:`m-0 text-copy-14 text-secondary`,children:[Me.length,` `,Me.length===1?`query`:`queries`,`, one per selected Property:`]}),(0,Q.jsx)(`ul`,{className:`mt-1 mb-0 list-none space-y-0.5 p-0`,children:Me.slice(0,3).map(e=>(0,Q.jsx)(`li`,{className:`text-label-14 text-strong`,children:e},e))}),Me.length>3?(0,Q.jsxs)(`p`,{className:`mt-1 mb-0 text-copy-14 text-secondary`,children:[`and `,Me.length-3,` more`]}):null]}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`mt-2 pointer-coarse:min-h-11`,disabled:je.length===0||h||o||!p,onClick:()=>{p&&Promise.resolve(p(je)).then(()=>de(``),()=>{})},children:h?`Adding…`:`Add ${je.length||``} ${je.length===1?`query`:`queries`}`.replace(` `,` `)}),je.length>0?(0,Q.jsxs)(`p`,{className:`mt-2 mb-0 text-copy-14 text-secondary`,children:[`Each query is measured on the one Property it names, so this adds`,` `,je.length,` assignment`,je.length===1?``:`s`,`.`]}):null]})]})]}),ge?null:(0,Q.jsx)(`div`,{className:`space-y-3 border-y border-default py-4`,children:r.length===0?null:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:Oe.length===0,onClick:Ne,children:`Select all shown queries`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:i.length===0,onClick:()=>c([]),children:`Clear query selection`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,className:`pointer-coarse:min-h-11`,disabled:!xe,onClick:()=>{l({queryIds:i,propertyIds:ye,..._e.kind===`groups`?{groupIds:_e.groupIds}:{}})},children:a?`Assigning queries…`:`Assign ${i.length||``} ${i.length===1?`query`:`queries`}${_e.kind===`none`?``:` to ${DE(_e,v,be)}`}`.replace(` `,` `)}),(0,Q.jsxs)(`div`,{className:`min-h-[2.75rem]`,children:[R?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Calculating assignment impact…`}):null,L?(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[i.length,` `,i.length===1?`query`:`queries`,` → `,L.assignmentCount,` Property assignment`,L.assignmentCount===1?``:`s`,` · `,L.addedAssignments,` new, `,L.alreadyPresentAssignments,` already assigned`,` · `,L.fullRunProviderCalls,` provider request`,L.fullRunProviderCalls===1?``:`s`,` per full run`,` · `,L.addedProviderCalls,` new`,_e.kind===`groups`?` · ${L.resolvedPropertyCount} unique ${L.resolvedPropertyCount===1?`Property`:`Properties`}${L.overlapCount>0?`, ${L.overlapCount} in overlapping groups`:``}`:``,`. Existing assignments stay in place.`]}):z?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:z}),te?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:te,children:`Retry impact`}):null,H?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:H,children:`Back to Groups`}):null]}):_e.kind===`none`?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Choose where to apply first.`}):(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[i.length,` `,i.length===1?`query`:`queries`,` × `,be,` Properties = `,i.length*be,` assignments`]})]}),ne?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:ne}):null]})}),r.length>0?(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Search queries`}),(0,Q.jsx)(`input`,{type:`search`,value:U,onChange:e=>{ie(e.currentTarget.value),ae(!1)},className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400`,placeholder:`Query text`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsxs)(`p`,{className:`m-0 text-copy-14 text-secondary`,children:[`Showing `,De.length,` of `,Ee.length,` queries,`,` `,we.length-Te.length,` of `,we.length,` applied`]}),ge||Te.length===0?null:(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>{se(e=>!e),ae(!1)},children:oe?`Show all queries`:`Show the ${Te.length} not applied`})]})]}):null,De.length>0?(0,Q.jsx)(`div`,{className:`relative overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[ge?null:(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Select query`})}),(0,Q.jsx)(`th`,{children:`Query`}),(0,Q.jsx)(`th`,{children:`Properties`}),ge?null:(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Clear query assignments`})})]})}),(0,Q.jsx)(`tbody`,{children:De.map(e=>{let t=ME(e),r=NE(e),a=i.includes(e.id),s=(e.propertyIds?.length??0)>0;return(0,Q.jsxs)(`tr`,{children:[ge?null:t?(0,Q.jsx)(`td`,{"aria-hidden":`true`}):(0,Q.jsx)(`td`,{className:`p-0`,children:(0,Q.jsx)(`label`,{className:`flex min-h-11 min-w-11 cursor-pointer items-center justify-center`,children:(0,Q.jsx)(`input`,{"aria-label":`Select query ${r}`,checked:a,type:`checkbox`,onChange:t=>c(wE(i,e.id,t.currentTarget.checked)),className:`size-6 accent-accent`})})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:r})}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:TE(e.propertyIds??[],n)}),ge?null:(0,Q.jsx)(`td`,{className:`text-right`,children:s?(0,Q.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-1`,children:[B?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:o||V,onClick:()=>he({queryId:e.id,propertyIds:[...e.propertyIds??[]]}),"aria-label":`Replace query assignments for ${r}`,children:`Replace assignments`}):null,(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:o,onClick:()=>{Se(e.id)},"aria-label":`Clear query assignments for ${r}`,children:`Clear assignments`})]}):null})]},e.id)})})]})}):r.length>0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No queries match this search.`}):null,ge||!me?null:(()=>{let e=r.find(e=>e.id===me.queryId),t=e?NE(e):`this query`,i=me.propertyIds.filter(e=>n.some(t=>t.id===e));return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-replace-assignments-title`,className:`border-y border-default py-4`,children:[(0,Q.jsx)(`h4`,{id:`advanced-measurement-replace-assignments-title`,className:`text-heading-14 text-heading`,children:`Replace assigned Properties`}),(0,Q.jsxs)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:[`This replaces every Property assigned to “`,t,`”.`]}),(0,Q.jsx)(`div`,{className:`mt-3`,children:(0,Q.jsx)(PE,{legend:`Properties for this query`,properties:n,selectedPropertyIds:i,onSelectedPropertyIdsChange:e=>he(t=>t&&{...t,propertyIds:[...e]})})}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:V||o,onClick:()=>he(null),children:`Keep current assignments`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:i.length===0||V||o||!B,onClick:()=>{B&&Promise.resolve(B({queryId:me.queryId,propertyIds:i}))},children:V?`Replacing assignments…`:`Replace with ${i.length} ${i.length===1?`Property`:`Properties`}`})]})]})})(),De.length<Ee.length?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:()=>ae(!0),children:`Show all queries`}):null,ge?null:(0,Q.jsxs)(Q.Fragment,{children:[s?null:(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`Apply at least one query to a Property before continuing.`}),fe?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Save or cancel the market before continuing.`}):null,(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 ${H?`justify-between`:`justify-end`}`,children:[H?(0,Q.jsx)(q,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:o,onClick:H,children:`Back`}):null,(0,Q.jsx)(q,{type:`button`,variant:xe?`outline`:`default`,className:`pointer-coarse:min-h-11`,disabled:!s||o||fe,onClick:re,children:`Continue`})]})]})]})}function BE({markets:e,assignments:t,groups:n,onSave:r,disabled:i,onEditingChange:a}){let[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(!1),h=e.find(e=>e.id===o?.id),g=n.find(e=>e.id===h?.groupId),_=t.filter(e=>!h?.groupId||e.groupIds.includes(h.groupId)).filter(e=>`${e.property} ${e.query} ${e.context} ${e.queryClass}`.toLocaleLowerCase().includes(c.trim().toLocaleLowerCase())),v=o?.assignmentIds??[];(0,Z.useEffect)(()=>{a(o!==null)},[o,a]),(0,Z.useEffect)(()=>{o!==null&&!m.current&&f.current?.focus(),o===null&&m.current&&p.current?.focus(),m.current=o!==null},[o]);async function y(){if(o){d(!0);try{await r(o)&&s(null)}finally{d(!1)}}}return(0,Q.jsxs)(`div`,{className:`space-y-4 pb-5`,children:[(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`A market reports on the specific Property, query, engine, and location assignments you select.`}),e.length>0?(0,Q.jsx)(`ul`,{className:`divide-y divide-subtle`,children:e.map(e=>(0,Q.jsxs)(`li`,{className:`flex items-center justify-between gap-3 py-2`,children:[(0,Q.jsxs)(`span`,{className:`text-label-14 text-primary`,children:[e.label,` `,(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`· `,e.measurementCount,` assignments`]})]}),e.assignmentIds?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,disabled:i||o!==null,"aria-label":`Edit ${e.label} market`,onClick:()=>{s({id:e.id,name:e.label,assignmentIds:e.assignmentIds}),l(``)},children:`Edit`}):null]},e.id))}):null,t.length===0?(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Publish your initial setup, then return here to choose its saved assignments for a market.`}):o?(0,Q.jsxs)(`form`,{className:`space-y-3`,onSubmit:e=>{e.preventDefault(),y()},children:[(0,Q.jsxs)(`label`,{className:`block max-w-xl text-label-14-strong text-heading`,children:[`Market name`,(0,Q.jsx)(`input`,{ref:f,required:!0,value:o.name,disabled:i||u,onChange:e=>s({...o,name:e.target.value}),className:`mt-1 block min-h-11 w-full rounded border border-default bg-surface px-3 text-label-14 text-primary`})]}),g?(0,Q.jsxs)(`p`,{className:`text-copy-13 text-secondary`,children:[`Linked group: `,g.name]}):null,(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,children:[`Find assignments`,(0,Q.jsx)(`input`,{type:`search`,value:c,onChange:e=>l(e.target.value),className:`mt-1 block min-h-11 w-full rounded border border-default bg-surface px-3 text-label-14 text-primary`})]}),(0,Q.jsxs)(`fieldset`,{disabled:i||u,children:[(0,Q.jsxs)(`legend`,{className:`text-copy-13 text-secondary`,children:[v.length,` assignments selected`]}),(0,Q.jsxs)(`div`,{className:`mt-2 max-h-80 overflow-y-auto divide-y divide-subtle border-y border-default`,children:[_.map(e=>(0,Q.jsxs)(`label`,{className:`flex min-h-11 cursor-pointer items-start gap-3 py-3 text-label-14 text-primary`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:v.includes(e.id),onChange:t=>s({...o,assignmentIds:wE(v,e.id,t.target.checked)}),className:`mt-1 size-4 shrink-0 accent-accent`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`span`,{className:`block text-label-14-strong`,children:[e.property,` · `,e.query]}),(0,Q.jsxs)(`span`,{className:`text-copy-13 text-secondary`,children:[e.context,` · `,e.queryClass]})]})]},e.id)),_.length===0?(0,Q.jsx)(`p`,{className:`py-3 text-copy-13 text-secondary`,children:`No matching assignments.`}):null]})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsx)(q,{type:`submit`,disabled:i||u||!o.name.trim()||v.length===0,children:u?`Saving market…`:`Save market`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,disabled:u,onClick:()=>s(null),children:`Cancel`})]})]}):(0,Q.jsx)(q,{ref:p,type:`button`,size:`sm`,variant:`outline`,disabled:i,onClick:()=>{s({name:``,assignmentIds:[]}),l(``)},children:`Add market`})]})}function VE({access:e,availability:t,properties:n,groups:r,groupDraft:i,isSaving:a=!1,onGroupDraftChange:o,onSaveGroup:s,onEditGroup:c,onRemoveGroup:l,onClearGroupDraft:u,membershipImport:d,onBack:f,onContinue:p}){if(CE(t))return(0,Q.jsx)(`section`,{"aria-label":`Groups`,children:(0,Q.jsx)(IE,{message:t.message})});let h=SE(e),g=i.name.trim().length>0&&i.propertyIds.length>0&&!a,_=n.filter(e=>i.propertyIds.includes(e.id)).length,v=i.name.trim().length>0||i.propertyIds.length>0||i.competitorDomains.trim().length>0,y=!h&&(c!==void 0||l!==void 0);function b(){u?u():o({name:``,propertyIds:[],competitorDomains:``})}return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-groups-title`,className:`space-y-5`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{id:`advanced-measurement-groups-title`,children:`Groups`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Use groups to organize Properties, apply queries in bulk, and compare competitors.`})]})}),h?(0,Q.jsx)(FE,{}):null,h?null:(0,Q.jsxs)(`div`,{className:`space-y-4 border-y border-default py-4`,children:[(0,Q.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Group name`}),(0,Q.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-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,value:i.name,onChange:e=>o({...i,name:e.currentTarget.value}),placeholder:`e.g. Core products`})]}),(0,Q.jsxs)(`details`,{open:n.length<=10,className:`group/group-properties`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(m,{className:`size-3.5 shrink-0 transition-transform group-open/group-properties:rotate-90`,"aria-hidden":`true`}),_,` of `,n.length,` Properties selected`]}),(0,Q.jsx)(`div`,{className:`pt-3`,children:(0,Q.jsx)(PE,{legend:`Properties in this group`,properties:n,selectedPropertyIds:i.propertyIds,onSelectedPropertyIdsChange:e=>o({...i,propertyIds:e})})})]}),(0,Q.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Competitor domains (optional)`}),(0,Q.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-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,value:i.competitorDomains,onChange:e=>o({...i,competitorDomains:e.currentTarget.value}),placeholder:`one.example, two.example`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:!g,onClick:()=>{s(i)},children:a?`Saving group…`:`Save group`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:!v,onClick:b,children:`Clear form`})]}),v?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`Save this group or clear the form before continuing.`}):null]}),r.length>0?(0,Q.jsx)(`div`,{className:`overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Group`}),(0,Q.jsx)(`th`,{children:`Properties`}),(0,Q.jsx)(`th`,{children:`Competitors`}),y?(0,Q.jsx)(`th`,{children:`Actions`}):null]})}),(0,Q.jsx)(`tbody`,{children:r.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.name}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:TE(e.propertyIds,n)}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.competitors.length>0?e.competitors.join(`, `):`None`}),y?(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsxs)(`div`,{className:`flex justify-end gap-1`,children:[c?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-label":`Edit ${e.name}`,onClick:()=>c(e),children:`Edit`}):null,l?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-label":`Remove ${e.name}`,onClick:()=>{l(e.id)},children:`Remove`}):null]})}):null]},e.id))})]})}):null,h||!d?null:(0,Q.jsxs)(`details`,{className:`border-t border-default pt-3`,children:[(0,Q.jsx)(`summary`,{className:`min-h-11 cursor-pointer text-label-14-strong text-heading`,children:`Import groups from CSV`}),(0,Q.jsx)(LE,{value:d})]}),h?null:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 ${f?`justify-between`:`justify-end`}`,children:[f?(0,Q.jsx)(q,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:f,children:`Back`}):null,(0,Q.jsx)(q,{type:`button`,className:`pointer-coarse:min-h-11`,disabled:v,onClick:p,children:r.length===0&&!v?`Continue without groups`:`Continue`})]})]})}function HE({access:e,availability:t,counts:n,flaggedExceptions:r,properties:i,onSaveProperty:a,sitemapReview:o,onBack:s,onReviewChanges:c,isReviewing:l=!1,canReviewChanges:u=!0,reviewedChanges:d,reviewChangesError:f,canPublish:p,sweepActive:h=!1,isPublishing:g=!1,onPublish:_}){let[v,y]=(0,Z.useState)(vE),[b,x]=(0,Z.useState)(vE),[S,C]=(0,Z.useState)(vE),[w,T]=(0,Z.useState)(!1);if(CE(t))return(0,Q.jsx)(`section`,{"aria-label":`Review and publish`,children:(0,Q.jsx)(IE,{message:t.message})});let E=SE(e),D=o?.items??[],O=o?.coverageItems??[],k=D.slice(0,v),A=O.slice(0,b),j=r.slice(0,S),M=c!==void 0,N=d!=null;return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-review-title`,className:`space-y-5`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{id:`advanced-measurement-review-title`,children:`Review & publish`})})}),E?(0,Q.jsx)(FE,{}):null,i&&i.length>0?(0,Q.jsx)(_E,{properties:i,onSave:E?void 0:a,onEditingChange:T}):null,o?(0,Q.jsx)(`section`,{"aria-labelledby":`advanced-measurement-sitemap-review-title`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4`,children:(0,Q.jsxs)(`div`,{className:`max-w-2xl space-y-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{id:`advanced-measurement-sitemap-review-title`,className:`text-heading-14 text-heading`,children:`Sitemap changes need review`}),o.exceptionCount>0?(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[o.exceptionCount,` sitemap `,o.exceptionCount===1?`entry needs`:`entries need`,` review.`]}):null,o.coverageReviewCount>0?(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[o.coverageReviewCount,` `,o.coverageReviewCount===1?`Property has`:`Properties have`,` URL coverage changes.`]}):null]}),o.exceptionCount>0?(0,Q.jsxs)(`details`,{className:`group/sitemap-urls border-y border-caution-800/30 py-3`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(m,{className:`size-3.5 shrink-0 transition-transform group-open/sitemap-urls:rotate-90`,"aria-hidden":`true`}),`URLs not added to Properties (`,o.exceptionCount,`)`]}),D.length>0?(0,Q.jsx)(`ul`,{className:`mt-3 space-y-3 text-label-14`,children:k.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-primary`,children:e.url}),(0,Q.jsx)(`p`,{className:`mt-1 text-secondary`,children:e.reason})]},`${e.url}-${e.reason}`))}):(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Review the affected sitemap URLs before confirming.`}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing `,k.length,` of `,D.length]}),k.length<D.length?(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>y(e=>e+yE),children:`Show next 50 URLs`}):null]})]}):null,E?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`An editor must finish this review before publishing.`}):(0,Q.jsxs)(Q.Fragment,{children:[o.coverageReviewCount>0?(0,Q.jsxs)(`fieldset`,{className:`space-y-3`,children:[(0,Q.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`For changed Property URLs`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`This choice applies to all `,o.coverageReviewCount,` changed `,o.coverageReviewCount===1?`Property`:`Properties`,`.`]}),(0,Q.jsxs)(`details`,{className:`group/url-changes border-y border-caution-800/30 py-3`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(m,{className:`size-3.5 shrink-0 transition-transform group-open/url-changes:rotate-90`,"aria-hidden":`true`}),`Review Property URL changes (`,o.coverageReviewCount,`)`]}),A.length>0?(0,Q.jsxs)(`div`,{className:`mt-3 space-y-4`,children:[A.map(e=>(0,Q.jsxs)(`section`,{"aria-label":`${e.property} URL changes`,children:[(0,Q.jsx)(`h5`,{className:`text-heading-14 text-primary`,children:e.property}),(0,Q.jsxs)(`div`,{className:`mt-2 grid gap-3 text-label-14 md:grid-cols-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:`Saved URLs`}),(0,Q.jsx)(`ul`,{className:`mt-1 space-y-1`,children:e.savedUrls.map(e=>(0,Q.jsx)(`li`,{className:`break-all text-secondary`,children:e},e))})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:`Current sitemap URLs`}),e.currentSitemapUrls.length>0?(0,Q.jsx)(`ul`,{className:`mt-1 space-y-1`,children:e.currentSitemapUrls.map(e=>(0,Q.jsx)(`li`,{className:`break-all text-secondary`,children:e},e))}):(0,Q.jsx)(`p`,{className:`mt-1 text-secondary`,children:`No matching URL was found.`})]})]})]},e.property)),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing `,A.length,` of `,O.length]}),A.length<O.length?(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>x(e=>e+yE),children:`Show next 50 URL changes`}):null]})]}):(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Review the affected Properties before confirming.`})]}),(0,Q.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-label-14 text-primary`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`advanced-measurement-coverage-resolution`,checked:o.coverageResolution===`keep-existing`,onChange:()=>o.onCoverageResolutionChange(`keep-existing`)}),`Keep existing Property URLs`]}),(0,Q.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-label-14 text-primary`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`advanced-measurement-coverage-resolution`,checked:o.coverageResolution===`replace-with-imported`,onChange:()=>o.onCoverageResolutionChange(`replace-with-imported`)}),`Use current sitemap URLs`]})]}):null,(0,Q.jsx)(q,{type:`button`,className:`pointer-coarse:min-h-11`,onClick:()=>{o.onResolve()},children:`Confirm sitemap changes`})]})]})}):null,(0,Q.jsx)(`div`,{className:`overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[720px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Properties`}),(0,Q.jsx)(`th`,{children:`Queries`}),(0,Q.jsx)(`th`,{children:`Groups`}),(0,Q.jsx)(`th`,{children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[`Assignments`,n.assignments!==void 0&&n.assignments>n.queries?(0,Q.jsx)(X,{text:`An assignment pairs one query with one Property. Applying a query to a group creates one assignment per Property. ${n.queries} ${n.queries===1?`query produces`:`queries produce`} ${n.assignments} assignments here.`}):null]})}),(0,Q.jsx)(`th`,{children:`Provider requests / run`})]})}),(0,Q.jsx)(`tbody`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.properties}),(0,Q.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.queries}),(0,Q.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.groups}),(0,Q.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.assignments??`—`}),(0,Q.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.providerCalls??RE})]})})]})}),n.providerCalls===void 0?(0,Q.jsx)(`p`,{className:`supporting-copy`,children:`Review changes to see how many provider requests one run will make.`}):null,d?(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-reviewed-changes-title`,className:`border-y border-default py-4`,"aria-live":`polite`,children:[(0,Q.jsx)(`h4`,{id:`advanced-measurement-reviewed-changes-title`,className:`text-heading-14 text-heading`,children:d.title}),d.items.length>0?(0,Q.jsx)(`ul`,{className:`mt-3 list-disc space-y-2 pl-5 text-label-14 text-secondary`,children:d.items.map((e,t)=>(0,Q.jsx)(`li`,{children:e},`${e}-${t}`))}):null]}):null,r.length>0?(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-flagged-exceptions-title`,className:`space-y-3`,children:[(0,Q.jsx)(`h4`,{id:`advanced-measurement-flagged-exceptions-title`,className:`text-heading-14 text-heading`,children:`Flagged exceptions`}),r.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No flagged exceptions.`}):(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsx)(`div`,{className:`divide-y divide-default border-y border-default`,children:j.map(e=>(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3 py-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:e.title}),e.detail?(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:e.detail}):null]}),(0,Q.jsx)(J,{tone:e.tone??`caution`,children:`Needs attention`})]},e.id))}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing `,j.length,` of `,r.length]}),j.length<r.length?(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>C(e=>e+yE),children:`Show next 50 exceptions`}):null]})]})]}):null,E?null:(0,Q.jsxs)(Q.Fragment,{children:[M&&f?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:f}):null,h?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`A check is queued or running. Publish after it finishes.`}):null,w?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Save or cancel the Property edit before reviewing or publishing.`}):null,(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 ${s?`justify-between`:`justify-end`}`,children:[s?(0,Q.jsx)(q,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:s,children:`Back`}):null,c!==void 0&&!N?(0,Q.jsx)(q,{type:`button`,className:`pointer-coarse:min-h-11`,disabled:w||l||!u,onClick:()=>{c()},children:l?`Reviewing changes…`:`Review changes`}):(0,Q.jsx)(q,{type:`button`,className:`pointer-coarse:min-h-11`,disabled:w||!p||g,onClick:()=>{_()},children:g?`Publishing setup…`:`Publish setup`})]})]})]})}var UE=[{id:`import`,label:`Import`},{id:`properties`,label:`Properties`},{id:`groups`,label:`Groups`},{id:`queries`,label:`Queries`},{id:`review`,label:`Review and publish`}];function WE({currentStep:e,hasDraft:t,canEdit:n,onDiscard:r,onStepChange:i,children:a}){let o=(0,Z.useRef)(null),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(!1),[d,f]=(0,Z.useState)(!1);return(0,Z.useEffect)(()=>{t||f(!1)},[t]),(0,Z.useEffect)(()=>{let e=u.current;u.current=d,d?c.current?.focus():e&&l.current?.focus()},[d]),(0,Z.useEffect)(()=>{let t=o.current;if(o.current=e,t===null||t===e)return;let n=s.current?.querySelector(`h1, h2, h3, [role="heading"]`);n&&(n.tabIndex=-1,n.focus())},[e]),(0,Q.jsxs)(`div`,{className:`space-y-6`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between`,children:[(0,Q.jsx)(`div`,{className:`min-w-0 w-full sm:flex-1`,children:(0,Q.jsx)(`h2`,{children:`Advanced measurement setup`})}),t?(0,Q.jsxs)(`div`,{className:`flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end`,children:[(0,Q.jsx)(J,{tone:`neutral`,children:`Draft`}),n&&r?d?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,role:`group`,"aria-label":`Confirm discard`,children:[(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Discard all unpublished changes?`}),(0,Q.jsx)(q,{ref:c,type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>f(!1),children:`Keep editing`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:r,children:`Discard unpublished changes`})]}):(0,Q.jsx)(q,{ref:l,type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>f(!0),children:`Discard changes`}):null]}):null]}),(0,Q.jsx)(`div`,{role:`group`,"aria-label":`Advanced measurement setup progress`,className:`overflow-x-auto border-b border-default`,children:(0,Q.jsx)(`ol`,{className:`flex min-w-max gap-6`,children:UE.map(t=>(0,Q.jsx)(`li`,{children:i?(0,Q.jsx)(`button`,{type:`button`,"aria-current":e===t.id?`step`:void 0,onClick:()=>i(t.id),className:`block min-h-11 border-b-2 bg-transparent px-1 py-3 text-left text-button-14 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${e===t.id?`border-strong text-heading`:`border-transparent text-secondary hover:text-heading`}`,children:t.label}):(0,Q.jsx)(`span`,{"aria-current":e===t.id?`step`:void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-label-14-strong ${e===t.id?`border-strong text-heading`:`border-transparent text-secondary`}`,children:t.label})},t.id))})}),(0,Q.jsx)(`div`,{ref:s,children:a})]})}function GE(e){let t=e.canEdit?`editor`:`viewer`;return e.currentStep===`import`||e.currentStep===`properties`?(0,Q.jsx)(hE,{...e.importProperties,activeStep:e.currentStep,canEdit:e.canEdit}):e.currentStep===`queries`?(0,Q.jsx)(zE,{...e.queries,access:t,onManageProjectQueries:e.onManageProjectQueries}):e.currentStep===`groups`?(0,Q.jsx)(VE,{...e.groups,access:t}):`review`in e?(0,Q.jsx)(HE,{...e.review,access:t}):null}function KE(e){return(0,Q.jsx)(WE,{currentStep:e.currentStep,hasDraft:e.hasDraft,canEdit:e.canEdit,onDiscard:e.onDiscard,onStepChange:e.onStepChange,children:GE(e)})}var qE={sitemapUrl:``,examplePropertyUrl:``,preferredHost:``,propertyPathPattern:``,additionalHost:``,additionalPathPattern:``,excludedPaths:``},JE={name:``,propertyIds:[],competitorDomains:``},YE=50,XE=[],ZE={};function QE(e){let t=e.trim();if(!t)return null;try{return new URL(t.includes(`://`)?t:`https://${t}`).hostname.toLocaleLowerCase()}catch{return null}}function $E(e){let t=e.trim();if(!t)throw Error(`Add a sitemap URL.`);let n;try{n=new URL(t.includes(`://`)?t:`https://${t}`)}catch{throw Error(`Sitemap URL must be a valid web address.`)}return(n.pathname===``||n.pathname===`/`)&&(n.pathname=`/sitemap.xml`),n.toString()}function eD(e){let t=e.propertyPathPattern.trim();if(t){let e=(t.startsWith(`/`)?t:`/${t}`).split(`/`).slice(1);if(e.filter(e=>e===`*`||e===`{slug}`).length!==1||e.some(e=>e.includes(`*`)&&e!==`*`))throw Error(`Property URL pattern must contain exactly one * or {slug} segment.`);return`/${e.map(e=>e===`*`?`{slug}`:e).join(`/`)}`}let n=e.examplePropertyUrl.trim();if(!n)throw Error(`Add one example Property page so Canonry can identify the matching URLs.`);try{let e=new URL(n).pathname.split(`/`).filter(Boolean);if(e.length===0)throw Error();return e[e.length-1]=`{slug}`,`/${e.join(`/`)}`}catch{throw Error(`Example Property page must be a valid web address.`)}}function tD(e){let t=[],n=new Set;for(let r of e.split(/[\n,]+/)){let e=r.trim().replace(/\/+$/,``);if(!e)continue;let i=e.split(`/`).filter(Boolean).at(-1)??e,a=i.startsWith(`*`),o=i.endsWith(`*`),s=i.slice(+!!a,o?-1:void 0).trim();if(!s)throw Error(`Ignored URL patterns must include text besides *.`);let c=a&&o?`contains`:a?`suffix`:o?`prefix`:`exact`,l=`${c}:${s}`;n.has(l)||(n.add(l),t.push({kind:c,value:s}))}return t}function nD(e){let t=$E(e.sitemapUrl),n=e.examplePropertyUrl.trim()?QE(e.examplePropertyUrl):null,r=QE(e.preferredHost)??n??QE(t);if(!r)throw Error(`Add a valid sitemap or Property page URL.`);let i=QE(e.additionalHost),a=e.additionalHost.trim().length>0;if(a!==e.additionalPathPattern.trim().length>0||a&&!i)throw Error(`Add both an additional domain and its Property URL pattern.`);let o=tD(e.excludedPaths);return{sitemapUrl:t,rule:{primary:{host:r,pathTemplate:eD(e)},...i?{aliases:[{host:i,pathTemplate:eD({...e,examplePropertyUrl:``,propertyPathPattern:e.additionalPathPattern})}]}:{},...o.length>0?{excludedSlugPatterns:o}:{}}}}function rD(e){return!e||e.authoring.targets.length===0?`import`:e.authoring.targets.some(e=>e.status===`proposed`)?`properties`:e.authoring.assignments.length===0?`groups`:e.baseActiveRevision===null?`review`:`properties`}function iD(e,t){return!e||e.authoring.targets.length===0?`import`:!e.authoring.targets.some(e=>e.status!==`excluded`)||e.authoring.targets.some(e=>e.status===`proposed`)?`properties`:e.authoring.assignments.length===0&&t===`review`?`groups`:t}function aD(e){return[...new Set([...e.discoveredUrl?[e.discoveredUrl]:[],...e.urlMatchers])]}function oD(e){return e===`included`?`confirmed`:e===`excluded`?`excluded`:`proposed`}function sD(e){return e?.authoring.targets.filter(e=>e.status===`included`).map(e=>e.stableKey)??[]}function cD(e,t){return`${t}-${e.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,`-`).replace(/^-+|-+$/g,``)||`item`}`.slice(0,128)}function lD(e){return QE(e)}function uD(e,t){if(t[0]!==`targets`)return;let n=t[1];if(typeof n==`number`)return e?.targets[n];if(typeof n==`string`)return e?.targets.find(e=>e.stableKey===n)}function dD(e,t){if(t[0]!==`groups`)return;let n=t[1];if(typeof n==`number`)return e?.groups[n];if(typeof n==`string`)return e?.groups.find(e=>e.stableKey===n)}function fD(e,t){return t[0]===`assignments`&&typeof t[1]==`number`?e?.assignments[t[1]]:void 0}function pD(e,t){return e?.targets.find(e=>e.stableKey===t)?.label??`a Property`}function mD(e,t){let n=uD(e.authoring,t.path);if(!n)return;let r=t.path[2],i=t.path[3];if(r===`urlMatchers`&&typeof i==`number`){let e=n.urlMatchers[i];return e?`${n.label} — ${e}`:n.label}if(r===`aliases`&&typeof i==`number`){let e=n.aliases[i];return e?`${n.label} — ${e}`:n.label}return n.label}function hD(e,t){let n=dD(e.authoring,t.path);if(!n)return;let r=t.path[2],i=t.path[3];if(r===`competitors`&&typeof i==`number`){let e=n.competitors.at(i)?.domain;return e?`${n.label} — ${e}`:n.label}if(r===`targetKeys`&&typeof i==`number`){let t=pD(e.authoring,n.targetKeys[i]);return`${n.label} — ${t}`}return n.label}function gD(e,t){let n=fD(e.authoring,t.path);if(!n)return;let r=e.queries.find(e=>e.id===n.queryId)?.query??`an unavailable query`;return`${pD(e.authoring,n.targetKey)} — ${r}`}function _D(e,t){return t.path[0]===`identities`?`Project domain`:mD(e,t)??hD(e,t)??gD(e,t)}function vD(e,t,n){let r=fD(e.authoring,t.path);if(!r)return;let i={...e.authoring?.defaultContext,...r.contextOverride},a=t.path.at(-1);if(n===`models`&&typeof a==`string`)return i.models?.[a];if(n===`locations`&&typeof a==`number`)return i.locations?.[a]}function yD(e,t){let n=_D(t,e);switch(e.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,vD(t,e,`models`)].filter(Boolean).join(` — `)||void 0};case`invalid-location`:return{title:`Fix a location`,detail:`Choose a location configured for this project, or remove it from the query.`,tone:`negative`,affected:[n,vD(t,e,`locations`)].filter(Boolean).join(` — `)||void 0};case`target-without-aliases`:return{title:`Add Property aliases`,detail:`Add a name or alias to measure mentions.`,tone:`caution`,affected:n};case`duplicate-group-key`:return{title:`Resolve duplicate groups`,detail:`Two groups use the same setup identifier. Rename one group, then review again.`,tone:`negative`,affected:n};case`group-unknown-target`:return{title:`Fix group Properties`,detail:`This group contains a Property that is no longer in setup. Remove it or add the Property back.`,tone:`negative`,affected:n};case`group-excluded-target`:return{title:`Include or remove a grouped Property`,detail:`This group contains an excluded Property. Include it or remove it from the group.`,tone:`negative`,affected:n};case`competitor-invalid-domain`:return{title:`Fix a competitor domain`,detail:`Enter a valid competitor domain.`,tone:`negative`,affected:n};case`competitor-matches-project`:return{title:`Remove a project domain`,detail:`A competitor cannot use the project domain.`,tone:`negative`,affected:n};case`competitor-duplicate`:return{title:`Remove a duplicate competitor`,detail:`List each competitor domain only once in a group.`,tone:`negative`,affected:n};case`duplicate-assignment`:return{title:`Remove a duplicate query`,detail:`Assign each query to a Property only once.`,tone:`negative`,affected:n};case`assignment-unknown-target`:return{title:`Fix a query assignment`,detail:`This query is assigned to a Property that is no longer in setup. Remove the assignment or add the Property back.`,tone:`negative`,affected:n};case`assignment-excluded-target`:return{title:`Include or unassign a Property`,detail:`This query is assigned to an excluded Property. Include it or remove the assignment.`,tone:`negative`,affected:n};case`assignment-unknown-query`:return{title:`Remove an unavailable query`,detail:`This assignment refers to a tracked query that is no longer available. Remove it or add the query back to the project.`,tone:`negative`,affected:n};case`assignment-unclassified`:return{title:`Classify a query`,detail:`Choose Branded or Non-brand for this query before publishing.`,tone:`negative`,affected:n};case`query-limit-exceeded`:return{title:`Reduce queries`,detail:`This setup exceeds the distinct-query publishing limit. Remove some query assignments, then review again.`,tone:`negative`};case`target-without-assignments`:return{title:`Assign queries`,detail:`Assign at least one query to measure a Property.`,tone:`caution`,affected:n};case`invalid-compiled-plan`:return{title:`Fix setup details`,detail:`A setup value could not be validated. Review the affected item, then review again.`,tone:`negative`,affected:n};case`compiled-plan-too-large`:return{title:`Reduce setup size`,detail:`This setup is too large to publish. Remove Properties, queries, or groups, then review again.`,tone:`negative`};case`active-revision-schema-v1`:return{title:`Historical results will be kept`,detail:`Existing results remain visible after you publish this setup.`,tone:`neutral`}}return{title:e.severity===`fail`?`An unexpected setup issue blocks publishing`:`An unexpected setup issue needs review`,detail:e.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:e.severity===`fail`?`negative`:`caution`,affected:n}}function bD(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function xD(e){let t=[...new Set(e)];return t.length===0?``:t.length===1?` Affected: ${t[0]}.`:t.length<=3?` Affected: ${t.join(`, `)}.`:` Affected: ${t.slice(0,3).join(`, `)}, and ${t.length-3} more.`}function SD(e,t,n,r){return`${(()=>{switch(e){case`execution-context-no-provider`:return`${t} ${bD(n,`query assignment`)} need${n===1?`s`:``} a provider.`;case`target-without-aliases`:return`${t} ${bD(n,`Property`,`Properties`)} need${n===1?`s`:``} aliases.`;case`target-without-assignments`:return`${t} ${bD(n,`Property`,`Properties`)} need${n===1?`s`:``} queries.`;default:return n>1?`${t} ${bD(n,`item`)} need review.`:t}})()}${xD(r)}`}function CD(e,t){let n=new Map;for(let r of e){let e=yD(r,t),i=[r.ruleId,r.severity,e.title,e.detail].join(`\0`),a=n.get(i)??{ruleId:r.ruleId,severity:r.severity,meaning:e,paths:new Set,affected:new Set};a.paths.add(JSON.stringify(r.path)),e.affected&&a.affected.add(e.affected),n.set(i,a)}return[...n.values()].map((e,t)=>({id:`${e.ruleId}-${e.severity}-${t}`,title:e.meaning.title,detail:SD(e.ruleId,e.meaning.detail,e.paths.size,e.affected),tone:e.meaning.tone}))}function wD(e){if(!e)return;let t=e.discoveredUrl??e.urlMatchers[0];return t?`${e.label} — ${t}`:e.label}function TD(e,t,n){let r=uD(n,e.path),i=dD(n,e.path),a=e.path[2]===`rebind`&&typeof e.path[3]==`string`?e.path[3]:void 0,o=a?n?.targets.find(e=>e.stableKey===a):void 0,s=r?.label??i?.label,c=xD(s?[s]:[]),l={id:`${e.code}-${t}`,tone:`caution`};switch(e.code){case`merge-targets-noop`:return{...l,title:`Choose another Property to merge`,detail:`Select at least one other Property before merging.${c}`};case`excluded-target-has-assignments`:return{...l,title:`Review excluded Property queries`,detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${c}`};case`group-unknown-target`:return{...l,title:`Fix group Properties`,detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${c}`};case`measurement.discovery.proposed_new_target`:{let e=wD(r)??`the proposed Property`;return{...l,title:`Review a new Property`,detail:`Review ${e}. It did not match an existing Property.`}}case`measurement.discovery.proposed_rebind`:{let e=wD(r)??`the proposed Property`,t=o?.label??`an existing Property`;return{...l,title:`Review a moved Property`,detail:`Review ${e}. It may be the same Property as ${t}.`}}case`measurement.discovery.rebind_ambiguous`:{let e=wD(r)??`the proposed Property`,t=o?.label??`an existing Property`;return{...l,title:`Choose an existing Property`,detail:`Review ${e}. It may match ${t}; choose the correct Property.`}}default:return{...l,title:`Unexpected setup warning`,detail:`Review the latest setup change before publishing. If this warning remains, contact support.`}}}function ED(e,t=!1){let n=[],r=e.targets.added.length+e.targets.removed.length+e.targets.changed.length,i=e.groups.added.length+e.groups.removed.length+e.groups.changed.length,a=e.assignments.added+e.assignments.removed+e.assignments.reclassified;return r>0&&n.push(`${r} Property ${r===1?`change`:`changes`}`),a>0&&n.push(`${a} query assignment ${a===1?`change`:`changes`}`),i>0&&n.push(`${i} group ${i===1?`change`:`changes`}`),t&&n.unshift(`Existing results remain visible after you publish this setup.`),{title:t?`Historical results will be kept`:e.activeRevision===null?`New setup ready`:`Changes ready`,items:n.length>0?n:[`No changes from the published setup.`]}}function DD(e){return[...new Set(e)]}function OD(e){return DD(e).sort()}function kD(e,t,n,r){return e.kind===`groups`?{groupKeys:OD(e.groupIds),queryIds:OD(n),...r?{contextOverride:r}:{}}:{targetKeys:OD(e.kind===`all`?t:e.kind===`specific`?e.propertyIds:[]),queryIds:OD(n),...r?{contextOverride:r}:{}}}function AD(e,t){return t===void 0?e:JSON.stringify([e,t])}function jD(e){return{assignmentCount:e.assignments.requested,addedAssignments:e.assignments.added,alreadyPresentAssignments:e.assignments.alreadyPresent,resolvedPropertyCount:e.resolvedTargetKeys.length,overlapCount:e.overlapCount,addedProviderCalls:e.execution.addedProviderCalls,fullRunProviderCalls:e.execution.fullRunProviderCalls}}function MD(e){return e.kind===`exact`?e.url??``:e.kind===`prefix`?`https://${e.host??``}${e.pathPrefix===`/`?``:e.pathPrefix??``}/*`:e.host??``}function ND(e){let t=e.plan;if(t.schemaVersion===2)return{defaultContext:{providers:[],locations:[]},targets:t.targets.map(e=>({stableKey:e.stableKey,label:e.label,status:`included`,aliases:[...e.aliases],urlMatchers:e.urlMatchers.map(MD).filter(Boolean),source:e.discoveryIdentity?`sitemap`:`manual`,...e.discoveryIdentity?{discoveryIdentity:e.discoveryIdentity}:{}})),assignments:t.assignments.map(e=>({targetKey:e.targetKey,queryId:e.queryId,queryClass:e.queryClass,classificationSource:`operator`})),groups:t.groups.map(e=>({stableKey:e.stableKey,label:e.label,targetKeys:[...e.targetKeys],competitors:e.competitors.map(e=>({...e,aliases:[...e.aliases]}))}))};let n=t.targetQuerySelections.flatMap(e=>e.queryIds.map(t=>({targetKey:e.targetKey,queryId:t,queryClass:`unclassified`,classificationSource:`rule`})));return{defaultContext:{providers:[],locations:[]},targets:t.targets.map(e=>({stableKey:e.stableKey,label:e.label,status:`included`,aliases:[...e.aliases],urlMatchers:e.urls.map(MD).filter(Boolean),source:`manual`})),assignments:n,groups:t.groups.map(e=>({stableKey:e.stableKey,label:e.label,targetKeys:[...e.targetKeys],competitors:(e.competitors??[]).map(e=>({stableKey:cD(e,`competitor`),label:e,domain:e,aliases:[]}))}))}}function PD({projectName:e,projectDomain:t,queries:n,isQueryLoading:r,isQueryError:i,onRetryQueries:a,publishedPlan:o,canEdit:s=!0,sweepActive:c=!1,executionProviders:l=XE,executionProviderModels:u=ZE,onCreateQueries:d,onManageProjectQueries:f,onPublished:p,service:m=Zc}){let[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(`import`),[x,S]=(0,Z.useState)(!0),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)([]),[k,A]=(0,Z.useState)(()=>({...qE,sitemapUrl:t&&Lt(t)?`https://${Lt(t)}/sitemap.xml`:``})),[j,M]=(0,Z.useState)(`idle`),[N,P]=(0,Z.useState)(``),[F,I]=(0,Z.useState)(YE),[ee,L]=(0,Z.useState)([]),[R,z]=(0,Z.useState)([]),[te,ne]=(0,Z.useState)({kind:`none`}),[B,V]=(0,Z.useState)(``),[H,re]=(0,Z.useState)(``),[U,ie]=(0,Z.useState)(``),[W,ae]=(0,Z.useState)(null),[oe,se]=(0,Z.useState)(null),[ce,le]=(0,Z.useState)(!1),[ue,de]=(0,Z.useState)(null),[fe,pe]=(0,Z.useState)(0),[me,he]=(0,Z.useState)(null),[ge,_e]=(0,Z.useState)(null),[ve,ye]=(0,Z.useState)(null),[be,xe]=(0,Z.useState)(!1),[Se,Ce]=(0,Z.useState)(null),[we,Te]=(0,Z.useState)(0),[Ee,De]=(0,Z.useState)(null),[Oe,G]=(0,Z.useState)({...JE}),[ke,Ae]=(0,Z.useState)(null),[je,Ne]=(0,Z.useState)(``),[Pe,Fe]=(0,Z.useState)(null),[Ie,Le]=(0,Z.useState)(!1),[Re,ze]=(0,Z.useState)(!1),[Be,Ve]=(0,Z.useState)(null),[He,Ue]=(0,Z.useState)(null),[We,Ge]=(0,Z.useState)(null),[Ke,qe]=(0,Z.useState)(null),[Je,Ye]=(0,Z.useState)(null),Xe=(0,Z.useRef)(0),Ze=(0,Z.useRef)(0),$e=(0,Z.useRef)(0),et=_?.draft??null,tt=_?.etag??null,nt=(0,Z.useMemo)(()=>!s&&o?{baseActiveRevision:o.revision,authoring:ND(o)}:null,[s,o]),rt=et??nt;async function it(t){let n=++Xe.current;S(!0),w(null);try{let[r,i]=await Promise.all([m.loadSetup(e),m.loadDraft(e)]);if(!i.draft&&t&&s&&(await m.createDraft(e,r.activeRevision),[r,i]=await Promise.all([m.loadSetup(e),m.loadDraft(e)])),n!==Xe.current)return;g(r),v(i),b(rD(i.draft));let a=sD(i.draft);L(a)}catch(e){if(n!==Xe.current)return;w(Kc(e,`Could not load advanced measurement setup.`))}finally{n===Xe.current&&S(!1)}}(0,Z.useEffect)(()=>(it(!0),()=>{Xe.current+=1}),[e,s,m]),(0,Z.useEffect)(()=>{!x&&!et&&nt&&b(`properties`)},[et,x,nt]);async function at(){let t=await m.loadDraft(e);return v(t),t}async function ot(t){Ye(null);try{let[n,r]=await Promise.all([m.loadSetup(e),m.loadDraft(e)]);g(n),v(r);let i=sD(r.draft);L(i),b(e=>iD(r.draft,e)),E(t)}catch(e){E(Kc(e,t))}}async function st(e,t,n,r={}){let{preserveBusyAction:i=!1}=r;if(!s||!tt||We&&!i)return null;i||Ge(e),E(null),Ye(null);try{let e=await t(tt),n=await at();return O((e.warnings??[]).map((e,t)=>TD(e,t,n.draft?.authoring))),n}catch(e){return Xc(e)?await ot(`This setup changed in another session. The latest draft is loaded; review your changes again.`):E(Kc(e,n)),null}finally{i||Ge(null)}}let ct=(0,Z.useMemo)(()=>(rt?.authoring.targets??[]).map(e=>{let t=aD(e);return{id:e.stableKey,name:e.label,url:t[0]??`No URL`,urls:t,state:oD(e.status)}}),[rt]),lt=(0,Z.useMemo)(()=>rt?.authoring.targets.filter(e=>e.status===`included`)??[],[rt]),ut=(0,Z.useMemo)(()=>lt.map(e=>({id:e.stableKey,label:e.label,urlCount:aD(e).length})),[lt]),dt=rt?.authoring.assignments.length??0,ft=(0,Z.useMemo)(()=>{if(!rt)return[];let e=new Set(n.map(e=>e.id)),t=n.map(e=>({id:e.id,text:e.query,source:`saved-project-queries`,propertyIds:DD(rt.authoring.assignments.filter(t=>t.queryId===e.id).map(e=>e.targetKey))})),r=DD(rt.authoring.assignments.map(e=>e.queryId).filter(t=>!e.has(t))).map(e=>({id:e,source:`unavailable-tracked-query`,state:`missing`,propertyIds:DD(rt.authoring.assignments.filter(t=>t.queryId===e).map(e=>e.targetKey))}));return[...t,...r]},[n,rt]),pt=(0,Z.useMemo)(()=>(rt?.authoring.groups??[]).map(e=>({id:e.stableKey,name:e.label,propertyIds:e.targetKeys,competitors:e.competitors.map(e=>e.domain)})),[rt]),mt=(0,Z.useMemo)(()=>(rt?.authoring.reportingScopes??[]).map(e=>({id:e.stableKey,label:e.label,measurementCount:e.usageEdges.length,assignmentIds:e.usageEdges.map(Qe),groupId:e.groupKey})),[rt]),ht=(0,Z.useMemo)(()=>(rt?.authoring.assignments??[]).flatMap(e=>{let t=lt.find(t=>t.stableKey===e.targetKey);return t?(e.executionContexts??[]).flatMap(r=>{if(!r.executionNodeKey)return[];let i={executionNodeKey:r.executionNodeKey,targetKey:e.targetKey,queryId:e.queryId};return[{id:Qe(i),edge:i,property:t.label,query:n.find(t=>t.id===e.queryId)?.query??`Unavailable query`,context:`${r.providers.map(e=>`${Vo(e)}${r.models[e]&&r.models[e]!==an(e)?` · ${Me(r.models[e])}`:``}`).join(`, `)} · ${r.location?.label??`No location`}`,queryClass:e.queryClass===`branded`?`Branded`:e.queryClass===`non-brand`?`Non-brand`:`Unknown class`,groupIds:(rt?.authoring.groups??[]).filter(t=>t.targetKeys.includes(e.targetKey)).map(e=>e.stableKey)}]}):[]}),[lt,n,rt]),gt=(0,Z.useMemo)(()=>{let e=new Map,t=(t,n={})=>{for(let r of t){if(!Qn(r))continue;let t=zn(r)?void 0:n[r],i=AD(r,t);e.has(i)||e.set(i,{id:i,provider:r,label:t?`${Vo(r)} · ${Me(t)}`:Vo(r),...t?{model:t}:{}})}};t(l,u);let n=rt?.authoring.defaultContext;n&&t(n.providers,n.models);for(let e of rt?.authoring.assignments??[]){e.contextOverride&&t(e.contextOverride.providers??n?.providers??[],e.contextOverride.models??n?.models);for(let n of e.executionContexts??[])t(n.providers,n.models)}return[...e.values()]},[u,l,rt]),_t=(0,Z.useMemo)(()=>{if(!B)return;let e=gt.find(e=>e.id===B);if(e)return{providers:[e.provider],models:e.model?{[e.provider]:e.model}:{}}},[B,gt]),vt=(0,Z.useMemo)(()=>{if(!U)return;let e=gt.find(e=>e.id===U);if(e)return{providers:[e.provider],models:e.model?{[e.provider]:e.model}:{}}},[gt,U]),yt=(0,Z.useMemo)(()=>H&&vt?{marketKeys:[H],contextOverride:vt}:null,[vt,H]),bt=yt?JSON.stringify(yt):``,xt=(0,Z.useMemo)(()=>!W||oe!==bt||W.draftEtag!==tt?null:{matchedMeasurements:W.matchedEdges,changedMeasurements:W.changedEdges,addedProviderCalls:W.execution.addedProviderCalls,fullRunProviderCalls:W.execution.fullRunProviderCalls},[tt,W,oe,bt]);(0,Z.useEffect)(()=>{B&&!gt.some(e=>e.id===B)&&V(``)},[B,gt]),(0,Z.useEffect)(()=>{U&&!gt.some(e=>e.id===U)&&ie(``)},[gt,U]),(0,Z.useEffect)(()=>{H&&!mt.some(e=>e.id===H)&&re(``)},[H,mt]);let St=(0,Z.useMemo)(()=>{if(R.length===0)return null;let e=kD(te,ut.map(e=>e.id),R,_t);return(e.groupKeys?.length??e.targetKeys?.length??0)>0?e:null},[_t,te,ut,R]),Ct=St?JSON.stringify(St):``;(0,Z.useEffect)(()=>{let t=St,n=++Ze.current;if(!s||!et||!tt||!t){_e(null),ye(null),Ce(null),xe(!1);return}_e(null),ye(null),Ce(null),xe(!0);let r=window.setTimeout(()=>{m.previewAssignments(e,t).then(e=>{n===Ze.current&&(e.draftEtag===tt?(_e(e),ye(Ct)):(_e(null),ye(null),Ce(`The setup changed while calculating assignment impact. Refresh the draft and try again.`)))}).catch(e=>{n===Ze.current&&(_e(null),ye(null),Ce(Jc(e)))}).finally(()=>{n===Ze.current&&xe(!1)})},250);return()=>{window.clearTimeout(r),Ze.current+=1}},[St,Ct,we,s,et,tt,e,m]),(0,Z.useEffect)(()=>{let t=yt,n=++$e.current;if(!s||!et||!tt||!t){ae(null),se(null),de(null),le(!1);return}ae(null),se(null),de(null),le(!0);let r=window.setTimeout(()=>{m.previewMarketRouting(e,t).then(e=>{n===$e.current&&(e.draftEtag===tt?(ae(e),se(bt)):de(`The setup changed while calculating market impact. Refresh the draft and try again.`))}).catch(e=>{n===$e.current&&de(Kc(e,`Could not calculate market routing impact.`))}).finally(()=>{n===$e.current&&le(!1)})},250);return()=>{window.clearTimeout(r),$e.current+=1}},[s,et,tt,yt,fe,bt,e,m]);let wt=(0,Z.useMemo)(()=>[...dt===0?[{id:`no-query-assignments`,title:`Assign at least one query`,detail:`Apply a tracked query to at least one Property before publishing.`,tone:`negative`}]:[],...rt?.authoring.assignments.some(e=>e.queryClass===`unclassified`)&&!(nt&&o?.plan.schemaVersion===1)?[{id:`unclassified-query-assignments`,title:`Remove an unavailable query`,detail:`One or more saved assignments no longer have a tracked query. Clear them before publishing.`,tone:`negative`}]:[],...D],[dt,nt,o,D,rt]),Tt=r?{status:`unavailable`,message:`Tracked queries are loading.`}:i?{status:`unavailable`,message:`Tracked queries could not be loaded. Retry before assigning Properties.`}:{status:`available`};async function Et(t){let n;try{n=nD(t)}catch(e){E(Kc(e,`Check the sitemap details and try again.`));return}A(t),M(`reviewing`);let r=await st(`import`,t=>m.importSitemap(e,t,n),`Could not review this sitemap.`);if(r?.draft){let e=r.draft.authoring.targets.filter(e=>e.status===`included`).map(e=>e.stableKey);L(e),P(``),I(YE),b(`properties`),M(`idle`)}else M(`error`)}async function Dt(t){let n=t.urls[0];if(!n)return E(`Enter the page URL for this Property.`),!1;let r=cD(n,`property`);if(et?.authoring.targets.some(e=>e.stableKey===r))return E(`This Property page is already in the draft. Select it in Properties.`),!1;let i=await st(`property`,n=>m.upsertTarget(e,n,{stableKey:r,label:t.name,status:`included`,source:`manual`,aliases:t.aliases,urlMatchers:t.urls}),`Could not add this Property.`);return i?.draft?(L(sD(i.draft)),!0):!1}async function Ot(t,n){let r=et?.authoring.targets.find(e=>e.stableKey===t);if(!r)return!1;let{identityAliases:i,...a}=r;return await st(`property-names`,t=>m.upsertTarget(e,t,{...a,label:n.name,aliases:n.aliases,...n.identityAliases.length>0?{identityAliases:n.identityAliases}:{}}),`Could not save this Property’s names.`)!==null}async function kt(t){let n=et?.authoring.reportingScopes?.find(e=>e.stableKey===t.id);if(t.id&&!n)return E(`This market is no longer in the draft. Cancel the edit and review the latest setup.`),!1;let r=n?.stableKey??cD(t.name,`market`);if(!n&&et?.authoring.reportingScopes?.some(e=>e.stableKey===r))return E(`A market with this name already exists. Edit that market or choose another name.`),!1;let i=t.assignmentIds.map(e=>ht.find(t=>t.id===e));return i.some(e=>!e)?(E(`A selected assignment changed. Reopen the market and review its assignments.`),!1):await st(`market`,a=>m.upsertMarket(e,a,{stableKey:r,label:t.name.trim(),kind:`market`,...n?.groupKey?{groupKey:n.groupKey}:{},usageEdges:i.map(e=>e.edge)}),`Could not save this market.`)!==null}async function At(e){if(!d||e.length===0||We)return[];Ge(`create-queries`),qe(null);try{return await d(e)}catch(e){throw qe(ws(e)),e}finally{Ge(null)}}async function jt(t){if(!et||!tt||We)return;let n=new Set(t),r=et.authoring.targets.filter(e=>e.status===`proposed`&&e.discoveryIdentity).map(e=>({discoveryIdentity:e.discoveryIdentity,action:n.has(e.stableKey)?`create`:`ignore`})),i=r.length>0||et.authoring.targets.some(e=>e.status!==`proposed`&&e.status===`included`!==n.has(e.stableKey));Ge(`properties`),E(null),Ye(null);try{if(!i){L([...n]),ne({kind:`none`}),b(`groups`);return}await m.applySitemapSelection(e,tt,r,[...n]);let t=sD((await at()).draft);L(t),ne({kind:`none`}),b(`groups`)}catch(e){Xc(e)?await ot(`This setup changed in another session. The latest Properties are loaded.`):E(Kc(e,`Could not save the selected Properties.`))}finally{Ge(null)}}async function Mt(t){let n=t.groupIds&&t.groupIds.length>0?{groupKeys:OD(t.groupIds),queryIds:OD(t.queryIds),..._t?{contextOverride:_t}:{}}:{targetKeys:OD(t.propertyIds),queryIds:OD(t.queryIds),..._t?{contextOverride:_t}:{}};!ge||ve!==JSON.stringify(n)||!tt||ge.draftEtag!==tt?E(`Review the latest assignment impact before assigning queries.`):await st(`assignments`,t=>m.applyAssignments(e,t,n),`Could not apply these queries.`)&&(z([]),De(`${ge.assignments.added} new assignment${ge.assignments.added===1?``:`s`} added. Existing assignments were kept.`))}async function Nt(t){t.propertyIds.length!==0&&await st(`replace-assignments`,n=>m.replaceAssignments(e,n,{targetKeys:DD(t.propertyIds),queryIds:[t.queryId],..._t?{contextOverride:_t}:{}}),`Could not replace this query assignment.`)&&(z(e=>e.filter(e=>e!==t.queryId)),De(`Query assignments replaced.`))}async function Pt(){if(!yt||!W||oe!==JSON.stringify(yt)||!tt||W.draftEtag!==tt){E(`Review the latest market routing impact before saving.`);return}let t=mt.find(e=>e.id===H);await st(`route-markets`,t=>m.routeMarkets(e,t,yt),`Could not save this market routing.`)&&he(`${t?.label??`Market`} routing saved. Existing locations were preserved.`)}async function Ft(t,n=!1){if(t.length!==0&&!await st(`paired-assignments`,n=>_t?m.applyPairedAssignments(e,n,[...t],_t):m.applyPairedAssignments(e,n,[...t]),`Could not assign these queries.`,{preserveBusyAction:n}))throw Error(`Could not assign these queries.`)}async function It(e){if(s&&d&&e.length!==0&&!We){Ge(`create-and-pair-questions`),qe(null);try{let t;try{t=await d(DD(e.map(e=>e.text)))}catch(e){throw qe(ws(e)),e}let n=new Map(t.map(e=>[e.query,e.id])),r=e.map(e=>({targetKey:e.propertyId,queryId:n.get(e.text)})).filter(e=>e.queryId!==void 0);if(r.length!==e.length){let e=Error(`The created queries could not be matched to their Properties.`);throw qe(`The queries were added, but could not be paired with every Property. Try again to pair them.`),e}try{await Ft(r,!0)}catch(e){throw qe(`The queries were added, but could not be assigned to their Properties. Try again to pair them.`),e}}finally{Ge(null)}}}async function Rt(t){if(!et)return;let n=DD(et.authoring.assignments.filter(e=>e.queryId===t).map(e=>e.targetKey));n.length!==0&&await st(`remove-${t}`,r=>m.removeAssignment(e,r,n,t),`Could not clear this query assignment.`)&&z(e=>e.filter(e=>e!==t))}async function zt(t){if(!et||!tt||We)return;let n=t.name.trim();if(!n)return;let r=ke??cD(n,`group`),i=et.authoring.groups.find(e=>e.stableKey===r);if(i&&ke===null){E(`A group named "${i.label}" already exists. Edit it or choose a different name.`);return}let a=t.competitorDomains.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean),o=a.find(e=>lD(e)===null);if(o){E(`"${o}" is not a valid competitor domain.`);return}let s=DD(a.map(e=>lD(e)));Ge(`group`),E(null),Ye(null);try{let a=await m.upsertGroup(e,tt,{stableKey:r,label:n,targetKeys:DD(t.propertyIds),competitors:s.map(e=>i?.competitors.find(t=>t.domain===e)??{stableKey:cD(e,`competitor`),label:e,domain:e,aliases:[]})}),o=await at();O(a.warnings.map((e,t)=>TD(e,t,o.draft?.authoring))),G({...JE}),Ae(null)}catch(e){Xc(e)?await ot(`This setup changed in another session. The latest groups are loaded.`):E(Kc(e,`Could not save this group.`))}finally{Ge(null)}}function Bt(e){let t=et?.authoring.groups.find(t=>t.stableKey===e);t&&(Ae(e),G({name:t.label,propertyIds:[...t.targetKeys],competitorDomains:t.competitors.map(e=>e.domain).join(`, `)}))}async function Vt(t){await st(`remove-group`,n=>m.removeGroup(e,n,t),`Could not remove this group.`)&&(ne(e=>e.kind===`groups`&&e.groupIds.includes(t)?{kind:`none`}:e),ke===t&&(Ae(null),G({...JE})))}function Ht(e){Ne(e),Fe(null),Ve(null),Ue(null)}async function Ut(){if(s&&je.trim()&&!Ie&&!Re){Le(!0),Ve(null),Ue(null);try{Fe(await m.previewGroupMembership(e,{csv:je}))}catch(e){Fe(null),Ve(Kc(e,`Could not review this CSV.`))}finally{Le(!1)}}}async function Wt(t){if(s&&tt&&Pe&&t.length!==0&&!We){if(Pe.draftEtag!==tt)Ve(`The setup changed while this CSV was open. Review the latest CSV before applying it.`);else{ze(!0),Ge(`group-import`),Ve(null),Ue(null),Ye(null);try{let n=await m.applyGroupMembership(e,tt,{csv:je,sourceChecksum:Pe.sourceChecksum,previewChecksum:Pe.previewChecksum,acceptedRows:DD(t.map(String)).map(Number)}),r=await at();O(n.warnings.map((e,t)=>TD(e,t,r.draft?.authoring))),Ne(``),Fe(null),Ue(`${n.addedMemberships} membership${n.addedMemberships===1?``:`s`} added${n.unchangedMemberships>0?`; ${n.unchangedMemberships} already present`:``}.`)}catch(e){Xc(e)?(await ot(`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(Kc(e,`Could not apply this CSV.`))}finally{Ge(null),ze(!1)}}}}async function Gt(){if(et&&tt&&!We&&dt!==0){Ge(`review`),E(null),Ye(null);try{let[t,r]=await Promise.all([m.compilePreview(e),m.diffPreview(e)]),i=[...t.checks,...r.checks],a=i.some(e=>e.ruleId===`active-revision-schema-v1`);if(O(CD(i.filter(e=>e.ruleId!==`active-revision-schema-v1`),{authoring:rt?.authoring,queries:n})),!t.ok||!r.ok)return;if(r.diff.activeRevision!==et.baseActiveRevision){await ot(`The published setup changed while you were reviewing. The latest draft is loaded; review it again.`);return}if(t.compiledChecksum!==r.compiledChecksum){E(`The setup changed while it was being reviewed. Review the latest changes again.`);return}Ye({etag:tt,baseActiveRevision:et.baseActiveRevision,compiledChecksum:t.compiledChecksum,changes:ED(r.diff,a),providerCalls:t.plan.executionNodes.reduce((e,t)=>e+t.expectedSnapshots,0)})}catch(e){E(Kc(e,`Could not review this setup.`))}finally{Ge(null)}}}async function Kt(){if(et&&tt&&Je&&!We){if(tt!==Je.etag||et.baseActiveRevision!==Je.baseActiveRevision)Ye(null),E(`The setup changed after review. Review the latest changes before publishing.`);else{Ge(`publish`),E(null);try{await m.publish(e,tt,{expectedActiveRevision:Je.baseActiveRevision,expectedCompiledChecksum:Je.compiledChecksum}),v({draft:null,etag:null}),Ye(null),p?.()}catch(e){Xc(e)?await ot(`The setup changed before it could be published. Review the latest draft and publish again.`):E(Kc(e,`Could not publish this setup.`))}finally{Ge(null)}}}}async function qt(){if(tt&&!We){Ge(`discard`),E(null);try{await m.discard(e,tt),v({draft:null,etag:null}),Ye(null),p?.()}catch(e){Xc(e)?await ot(`This setup changed in another session. The latest draft is loaded.`):E(Kc(e,`Could not discard these changes.`))}finally{Ge(null)}}}async function Jt(){if(et&&tt&&h&&!We){Ge(`restart`),E(null),Ye(null);try{await m.discard(e,tt),await m.createDraft(e,h.activeRevision),A({...qE}),P(``),L([]),z([]),ne({kind:`none`}),_e(null),Ce(null),De(null),G({...JE}),Ae(null),Ne(``),Fe(null),Ve(null),Ue(null),await it(!1)}catch(e){Xc(e)?await ot(`The setup changed again. Reloaded the latest draft and published setup.`):E(Kc(e,`Could not restart this setup.`))}finally{Ge(null)}}}if(x)return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-loading-title`,className:`space-y-4`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`h2`,{id:`advanced-measurement-loading-title`,children:`Advanced measurement setup`})}),(0,Q.jsx)(`div`,{className:`h-28 animate-pulse rounded-md bg-surface-subtle`,"aria-label":`Loading advanced measurement setup`})]});if(C)return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-error-title`,className:`space-y-4`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`h2`,{id:`advanced-measurement-error-title`,children:`Advanced measurement setup`})}),(0,Q.jsxs)(`div`,{role:`alert`,className:`border-y border-negative-800/40 bg-negative-950/20 py-4 text-label-14 text-negative`,children:[(0,Q.jsx)(`p`,{children:C}),(0,Q.jsx)(q,{className:`mt-3 pointer-coarse:min-h-11`,type:`button`,size:`sm`,variant:`outline`,onClick:()=>{it(!0)},children:`Try again`})]})]});if(!rt||s&&!tt)return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-empty-title`,className:`space-y-4`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`h2`,{id:`advanced-measurement-empty-title`,children:`Advanced measurement setup`})}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:s?`Start setup from the project Overview.`:`No advanced setup is available to review.`})]});if(s&&et&&h&&et.baseActiveRevision!==h.activeRevision)return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-stale-draft-title`,className:`space-y-4`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`h2`,{id:`advanced-measurement-stale-draft-title`,children:`Advanced measurement setup`})}),(0,Q.jsxs)(`div`,{role:`alert`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:`This draft is based on an older published setup.`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Restart from the latest setup before making more changes.`}),(0,Q.jsx)(q,{className:`mt-3 pointer-coarse:min-h-11`,type:`button`,size:`sm`,variant:`outline`,disabled:We===`restart`,onClick:()=>{Jt()},children:We===`restart`?`Restarting…`:`Discard draft and restart`})]}),T?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:T}):null]});let Yt=i&&a?(0,Q.jsx)(`div`,{className:`flex justify-end`,children:(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:a,children:`Retry queries`})}):null;return(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[h?.mode===`active-v1`?(0,Q.jsx)(`p`,{role:`status`,className:`border-y border-caution-800/40 bg-caution-950/20 py-3 text-copy-14 text-secondary`,children:`Review and publish this setup to enable class-filtered reporting.`}):null,T?(0,Q.jsx)(`p`,{role:`alert`,className:`border-y border-negative-800/40 bg-negative-950/20 py-3 text-copy-14 text-negative`,children:T}):null,Yt,y===`import`||y===`properties`?(0,Q.jsx)(KE,{currentStep:y,hasDraft:et!==null,canEdit:s,onStepChange:s?void 0:b,onDiscard:()=>{qt()},importProperties:{importDraft:k,onImportDraftChange:e=>{A(e),M(`idle`),E(null)},onReviewSitemap:e=>{Et(e)},reviewState:j,properties:ct,propertiesState:`ready`,propertiesSearch:N,onPropertiesSearchChange:P,maxVisibleProperties:F,onShowAllProperties:()=>I(ct.length),selectedPropertyIds:ee,onSelectedPropertyIdsChange:e=>L([...e]),onContinue:e=>{jt(e)},isContinuing:We!==null,onRetryProperties:()=>{at()},onReturnToImport:()=>b(`import`),onAddProperty:Dt}}):y===`queries`?(0,Q.jsx)(KE,{currentStep:`queries`,hasDraft:et!==null,canEdit:s,onStepChange:s?void 0:b,onDiscard:()=>{qt()},onManageProjectQueries:f,queries:{onCreateQueries:d?e=>At(e):void 0,isCreatingQueries:We===`create-queries`||We===`create-and-pair-questions`,isBusy:We!==null,createQueriesError:Ke,availability:Tt,properties:ut,queries:ft,selectedQueryIds:R,isApplying:We===`assignments`||We===`paired-assignments`,onSelectedQueryIdsChange:e=>z([...e]),onApplySelectedQueries:e=>Mt(e),groups:pt,audience:te,onAudienceChange:e=>{ne(e),De(null)},executionOptions:gt,executionOptionId:B,onExecutionOptionChange:e=>{V(e),De(null)},markets:mt,marketAssignments:ht,onSaveMarket:s?kt:void 0,marketId:H,onMarketChange:e=>{re(e),he(null)},marketExecutionOptionId:U,onMarketExecutionOptionChange:e=>{ie(e),he(null)},onRouteMarket:Pt,isRoutingMarket:We===`route-markets`,isPreviewingMarketRouting:ce,marketRoutingImpact:xt,marketRoutingError:ue,onRetryMarketRouting:()=>pe(e=>e+1),marketRoutingNotice:me,assignmentImpact:ge&&ve===Ct&&ge.draftEtag===tt?jD(ge):null,isPreviewingAssignmentImpact:be,assignmentImpactError:Se,onRetryAssignmentImpact:()=>Te(e=>e+1),assignmentNotice:Ee,onReplaceAssignments:Nt,isReplacingAssignments:We===`replace-assignments`,onCreateAndPairQuestions:s&&d?It:void 0,onClearQueryAssignments:Rt,onRemoveQuery:Rt,canContinue:dt>0,onBack:()=>b(`groups`),onContinue:()=>b(`review`)}}):y===`groups`?(0,Q.jsx)(KE,{currentStep:`groups`,hasDraft:et!==null,canEdit:s,onStepChange:s?void 0:b,onDiscard:()=>{qt()},groups:{properties:ut,groups:pt,groupDraft:Oe,isSaving:We===`group`,onGroupDraftChange:G,onSaveGroup:zt,onEditGroup:e=>Bt(e.id),onRemoveGroup:Vt,onClearGroupDraft:()=>{Ae(null),G({...JE})},membershipImport:{csv:je,preview:Pe,isReviewing:Ie,isApplying:Re,error:Be,notice:He,onCsvChange:Ht,onReview:Ut,onApply:Wt},onBack:()=>{b(`properties`)},onContinue:()=>b(`queries`)}}):(0,Q.jsx)(KE,{currentStep:`review`,hasDraft:et!==null,canEdit:s,onStepChange:s?void 0:b,onDiscard:()=>{qt()},review:{properties:lt.map(e=>({id:e.stableKey,name:e.label,aliases:e.aliases,identityAliases:e.identityAliases??[],urls:e.urlMatchers})),onSaveProperty:s?Ot:void 0,counts:{properties:lt.length,queries:new Set(rt.authoring.assignments.map(e=>e.queryId)).size,groups:rt.authoring.groups.length,assignments:rt.authoring.assignments.length,providerCalls:Je?.providerCalls},flaggedExceptions:wt,reviewedChanges:Je?.changes,isReviewing:We===`review`,canReviewChanges:dt>0&&!We,onReviewChanges:Gt,onBack:()=>b(`queries`),canPublish:Je!==null&&!We&&!c,sweepActive:c,isPublishing:We===`publish`,onPublish:Kt}})]})}var FD=`Mentioned = the property’s name in the answer. Cited = one of the property’s own pages in the sources. Neither implies the other.`,ID=[{key:`label`,label:`Property`,numeric:!1},{key:`mentionCoverage`,label:`Mention`,numeric:!0},{key:`citationCoverage`,label:`Citation`,numeric:!0}];function LD(e){return e.label!==`Complete`}var RD=`__all_properties__`,zD=50,BD=50,VD=20,HD=50,UD=250,WD=5,GD=[{value:`all`,label:`All queries`},{value:`non-brand`,label:`Non-brand`},{value:`branded`,label:`Branded`}],KD={"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`},qD={plan_v1:`Setup update required.`,no_completed_run:`Not measured yet.`,no_population:`No matching queries.`,evidence_incomplete:`Evidence incomplete.`,identity_ambiguous:`${oi}.`,"identity-ambiguous":`${oi}.`,not_applicable:`Not applicable.`,incomplete:`The latest measurement is incomplete.`,"evidence-incomplete":`Some source evidence is incomplete.`,citation_not_measured:`The engines return no sources.`,"citation-not-measured":`The engines return no sources.`,"no-population":`No measurements are available for this selection.`,unavailable:`This measurement is unavailable.`},JD={numerator:null,denominator:null,reason:`plan_v1`};function YD(e){return e.numerator!==null&&Number.isFinite(e.numerator)&&Number.isFinite(e.denominator)&&e.numerator>=0&&e.denominator>0&&e.numerator<=e.denominator}function XD(e){return YD(e)?`${e.numerator} of ${e.denominator} (${Ut(e.numerator/e.denominator)})`:`N/A`}function ZD(e){if(YD(e))return``;let t=e.reason??`unavailable`;return qD[t]??t}function QD(e){let t=[];return e.market&&t.push(e.market),e.urls.length>0&&t.push(`${e.urls.length} ${e.urls.length===1?`URL`:`URLs`}`),t.join(` · `)}function $D(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||e<0||t<=0||e>t?null:`${e} of ${t}`}function eO(e){let t=e.trim();return t&&!t.toLocaleLowerCase().includes(`unavailable`)?t:null}function tO(e){return e?.closest?.(`button, a, input, select, textarea, [role="button"]`)!=null}function nO({metric:e,signal:t,compact:n=!1}){let r=n?YD(e)?`text-label-14-strong text-primary`:`text-label-14-strong text-secondary`:YD(e)?`text-label-18-strong text-heading`:`text-label-18-strong text-secondary`,i=YD(e)?Ir(e,t):null;return(0,Q.jsxs)(`span`,{className:`inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums`,...YD(e)?{}:{title:ZD(e)},children:[(0,Q.jsx)(`span`,{className:r,children:XD(e)}),i?(0,Q.jsx)(X,{tone:`caution`,placement:`bottom`,label:i.label,text:i.text}):null]})}function rO({shown:e,total:t,onShowAll:n,itemLabel:r}){return e>=t?null:(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing `,e,` of `,t]}),(0,Q.jsxs)(q,{size:`sm`,variant:`outline`,onClick:n,children:[`Show all `,t,` `,r]})]})}function iO({title:e,values:t,emptyLabel:n,valueClassName:r=`text-secondary`}){let[i,a]=(0,Z.useState)(BD),o=t.slice(0,i);return(0,Q.jsxs)(`section`,{"aria-label":e,children:[(0,Q.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:e}),t.length===0?(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:n}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1.5 text-label-14`,children:o.map((e,t)=>(0,Q.jsx)(`li`,{className:r,children:e},`${e}:${t}`))}),(0,Q.jsx)(rO,{shown:o.length,total:t.length,itemLabel:e.toLocaleLowerCase(),onShowAll:()=>a(2**53-1)})]})]})}function aO({evidence:e,state:t=`ready`,onRetry:n}){let[r,i]=(0,Z.useState)(BD),a=e.slice(0,r);return(0,Q.jsxs)(`section`,{"aria-label":`Evidence`,children:[(0,Q.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:`Evidence`}),t===`loading`?(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Loading evidence…`}):t===`error`?(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsx)(`span`,{children:`Evidence could not be loaded.`}),n?(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:n,children:`Retry evidence`}):null]}):e.length===0?(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`No source evidence is available.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mt-2 overflow-x-auto rounded-md border border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[640px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Status`}),(0,Q.jsx)(`th`,{children:`Query`}),(0,Q.jsx)(`th`,{children:`URL`})]})}),(0,Q.jsx)(`tbody`,{children:a.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`span`,{className:`flex flex-wrap items-center gap-1`,children:[(0,Q.jsx)(J,{tone:e.tone,children:KD[e.kind]}),e.historical?(0,Q.jsx)(J,{tone:`caution`,children:`Historical`}):null]})}),(0,Q.jsxs)(`td`,{className:`text-secondary`,children:[(0,Q.jsx)(`span`,{className:`block`,children:e.query}),e.provider||e.location?(0,Q.jsx)(`span`,{className:`mt-1 block text-label-12 text-muted`,children:[e.provider?Vo(e.provider):null,e.location].filter(Boolean).join(` · `)}):null]}),(0,Q.jsx)(`td`,{className:`break-all text-secondary`,children:e.url})]},e.id))})]})}),(0,Q.jsx)(rO,{shown:a.length,total:e.length,itemLabel:`evidence items`,onShowAll:()=>i(2**53-1)})]})]})}function oO({property:e,onRetryEvidence:t}){return(0,Q.jsxs)(`div`,{className:`space-y-5 py-2`,children:[(0,Q.jsx)(iO,{title:`Assigned queries`,values:e.assignedQueries,emptyLabel:`No queries are assigned.`}),(0,Q.jsx)(iO,{title:`URLs`,values:e.urls,emptyLabel:`No URLs are assigned.`,valueClassName:`break-all text-secondary`}),(0,Q.jsx)(aO,{evidence:e.evidence,state:e.evidenceState,onRetry:t})]})}function sO({values:e}){return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-share-of-voice`,className:`border-y border-default py-4`,children:[(0,Q.jsx)(`h2`,{id:`advanced-measurement-share-of-voice`,className:`text-heading-14 text-heading`,children:`Brand share of voice`}),(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[420px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Name`}),(0,Q.jsx)(`th`,{children:`Share of voice`})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.name}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:(0,Q.jsx)(nO,{metric:e.coverage,signal:`mentioned`,compact:!0})})]},e.name))})]})})]})}function cO({ariaLabelledBy:e,value:t,options:n,onChange:r,disabled:i=!1}){function a(e){if(i)return;let a=n.findIndex(e=>e.value===t),o=null;if(e.key===`ArrowRight`||e.key===`ArrowDown`?o=(a+1)%n.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?o=(a-1+n.length)%n.length:e.key===`Home`?o=0:e.key===`End`&&(o=n.length-1),o===null)return;e.preventDefault();let s=n[o];r(s.value),e.currentTarget.querySelectorAll(`[role="radio"]`)[o].focus()}return(0,Q.jsx)(`div`,{role:`radiogroup`,"aria-labelledby":e,"aria-disabled":i,className:`segmented flex-wrap`,onKeyDown:a,children:n.map(e=>{let n=e.value===t;return(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":n,tabIndex:n?0:-1,disabled:i,onClick:()=>r(e.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${n?`segmented-option-active`:``}`,children:e.label},e.value)})})}function lO({outcomes:e}){let t=[{key:`both`,count:e.bothSignals,label:`mentioned and cited`,tone:`text-primary`},{key:`mentioned-only`,count:e.mentionedOnly,label:`mentioned only`,tone:`text-primary`},{key:`cited-only`,count:e.citedOnly,label:`cited only`,tone:`text-primary`},{key:`neither`,count:e.neither,label:`neither signal`,tone:`text-negative`},...e.notMeasured>0?[{key:`not-measured`,count:e.notMeasured,label:`not measured`,tone:`text-faint`}]:[]];return(0,Q.jsx)(`div`,{"aria-label":`Property outcomes`,className:`flex flex-wrap gap-x-8 gap-y-3 py-3`,children:t.map(e=>(0,Q.jsxs)(`div`,{className:`whitespace-nowrap`,children:[(0,Q.jsx)(`p`,{className:`font-mono text-copy-20-strong tabular-nums ${e.tone}`,children:e.count}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:[e.label,e.key===`not-measured`?(0,Q.jsx)(X,{text:`One or both signals missing. Not the same as neither.`}):null]})]},e.key))})}function uO({report:e,canEdit:t,onRunMeasurement:n,onRepublishSetup:r,isRunningMeasurement:i=!1,isRepublishingSetup:a=!1,isViewLoading:o=!1,isLoadingMore:s=!1,isLoadMoreError:c=!1,viewSearch:l,onViewChange:u,onLoadMore:f,onPropertyExpand:p,onRetryEvidence:m,renderPropertyLink:h}){let g=e.currentView!=null,_=e.classReporting===`available`&&(g||e.classScopes!=null),[v,y]=(0,Z.useState)(e.currentView?.queryClass??`all`),[b,x]=(0,Z.useState)(e.currentView?.scope.key??RD),[S,C]=(0,Z.useState)(l??``),[w,T]=(0,Z.useState)(zD),[E,D]=(0,Z.useState)(VD),[O,k]=(0,Z.useState)(e.currentView?.sort??`label-asc`),[A,j]=(0,Z.useState)(null),M=(0,Z.useRef)(l??``),N=_&&!g&&v!==`all`?v===`non-brand`?e.classScopes.nonBrand:e.classScopes.branded:e.overall,P=g?{aggregate:e.currentView.aggregate,groups:[]}:N,F=(0,Z.useCallback)(e=>{if(!g||!u)return;let t=e.scope??(b===RD?`all`:`group`),n=e.search??S;M.current=n,u({scope:t,...t===`group`?{groupKey:e.groupKey??b}:{},queryClass:e.queryClass??v,...n?{search:n}:{},...e.sort?{sort:e.sort}:{}})},[u,S,v,b,g]);(0,Z.useEffect)(()=>{e.currentView&&!o&&(y(e.currentView.queryClass),x(e.currentView.scope.key??RD),e.currentView.sort&&k(e.currentView.sort))},[o,e.currentView]),(0,Z.useEffect)(()=>{l!==void 0&&(M.current=l,C(e=>e.trim()===l.trim()?e:l))},[l]),(0,Z.useEffect)(()=>{if(!g||!u||S===M.current)return;let e=window.setTimeout(()=>F({search:S}),UD);return()=>window.clearTimeout(e)},[u,F,S,g]);let I=e.availableGroups??P.groups;(0,Z.useEffect)(()=>{b===RD||I.some(e=>e.id===b)||x(RD)},[I,b]);let ee=g?void 0:P.groups.find(e=>e.id===b),L=ee?.aggregate??P.aggregate,R=e=>_?e:JD,z=O,te=S.trim().toLocaleLowerCase(),ne=(0,Z.useMemo)(()=>!g&&te?L.properties.filter(e=>e.name.toLocaleLowerCase().includes(te)):L.properties,[L.properties,te,g]),B=g?ne:ne.slice(0,w),V=(g?e.currentView?.scope.kind===`group`:ee!=null)&&v===`non-brand`&&_&&(g||ee.confirmedCompetitorCount>0)&&(L.shareOfVoice?.length??0)>0,H=_?L.unavailablePropertyCount??0:0,re=e.flaggedResults.reduce((e,t)=>e+(t.count??1),0),U=e.flaggedResultsTotal??re,ie=[R(L.metrics.propertiesMentioned),R(L.metrics.mentionCoverage),R(L.metrics.citationCoverage)].map(ZD).find(Boolean),W=_?e.nextActionText??ie??(H>0?`${H} ${H===1?`property is`:`properties are`} unavailable.`:U>0?`${U} flagged ${U===1?`result needs`:`results need`} review.`:null):qD.plan_v1,ae=e.latestMeasurement.status.tone!==`negative`&&e.latestMeasurement.completedSlots<e.latestMeasurement.totalSlots?$D(e.latestMeasurement.completedSlots,e.latestMeasurement.totalSlots):null,oe=eO(e.latestMeasurement.date),se=[{value:RD,label:`All properties`},...I.map(e=>({value:e.id,label:e.label}))],ce=I.length>WD;function le(e){x(e),F(e===RD?{scope:`all`}:{scope:`group`,groupKey:e})}function ue(e){y(e),F({queryClass:e})}function de(e){let t=A!==e;j(t?e:null),t&&p?.(e)}return(0,Q.jsxs)(`section`,{"aria-label":`Advanced measurement overview`,"aria-busy":o,className:`space-y-5`,children:[(0,Q.jsx)(`header`,{className:`border-b border-default pb-4`,children:(0,Q.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?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Updating results…`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(J,{tone:e.latestMeasurement.status.tone,children:e.latestMeasurement.status.label}),e.latestMeasurement.includesBridgedHistory?(0,Q.jsx)(J,{tone:`caution`,children:`Includes historical data`}):null,ae?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary tabular-nums`,children:ae}):null,oe?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:oe}):null,W?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:W}):null,t&&_&&n?(0,Q.jsx)(q,{className:`ml-auto`,size:`sm`,onClick:()=>{n()},disabled:i,children:i?`Starting measurement…`:`Run measurement`}):t&&!_?(0,Q.jsx)(q,{className:`ml-auto`,size:`sm`,onClick:()=>{r?.()},disabled:!r||a,children:a?`Opening setup…`:`Republish setup`}):null]})})}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end gap-4 border-b border-default pb-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1`,children:[(0,Q.jsx)(`label`,{id:`advanced-measurement-group-label`,htmlFor:ce?`advanced-measurement-group`:void 0,className:`block text-label-14-strong text-heading`,children:`Group`}),ce?(0,Q.jsx)(`select`,{id:`advanced-measurement-group`,value:b,onChange:e=>le(e.target.value),className:`h-9 rounded-md border border-default bg-surface px-3 text-label-14 text-primary focus:outline-none focus:ring-2 focus:ring-mono-400`,children:se.map(e=>(0,Q.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,Q.jsx)(cO,{ariaLabelledBy:`advanced-measurement-group-label`,value:b,options:se,onChange:le})]}),(0,Q.jsxs)(`div`,{className:`space-y-1`,children:[(0,Q.jsx)(`label`,{id:`advanced-measurement-class-label`,className:`block text-label-14-strong text-heading`,children:`Query type`}),(0,Q.jsx)(cO,{ariaLabelledBy:`advanced-measurement-class-label`,value:v,options:GD,onChange:ue,disabled:!_})]}),(0,Q.jsxs)(`div`,{className:`ml-auto min-w-52 max-w-xs flex-1 space-y-1`,children:[(0,Q.jsx)(`label`,{htmlFor:`advanced-measurement-search`,className:`block text-label-14-strong text-heading`,children:`Search properties`}),(0,Q.jsx)(`input`,{id:`advanced-measurement-search`,type:`search`,value:S,onChange:e=>C(e.target.value),placeholder:`Search properties`,className:`h-9 w-full rounded-md border border-default bg-surface px-3 text-label-14 text-primary placeholder-mono-400 focus:outline-none focus:ring-2 focus:ring-mono-400`})]})]}),!o&&V?(0,Q.jsx)(sO,{values:L.shareOfVoice??[]}):null,o?(0,Q.jsx)(`div`,{className:`h-44 animate-pulse rounded-md bg-surface-subtle`,"aria-label":`Updating Property results`}):(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-properties-title`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-2`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center`,children:[(0,Q.jsx)(`h2`,{id:`advanced-measurement-properties-title`,className:`text-heading-16 text-heading`,children:`Properties`}),(0,Q.jsx)(X,{text:FD})]}),(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[e.currentView?.propertyTotal??ne.length,` `,(e.currentView?.propertyTotal??ne.length)===1?`property`:`properties`]})]}),e.currentView?.outcomes?(0,Q.jsx)(lO,{outcomes:e.currentView.outcomes}):null,(0,Q.jsx)(`div`,{className:`overflow-x-auto rounded-md border border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[720px]`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Property measurement results`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[ID.map(e=>{let t=z.startsWith(`${e.key}-`),n=t&&z.endsWith(`-desc`)?`descending`:t?`ascending`:`none`;return(0,Q.jsx)(`th`,{"aria-sort":n,className:(e.numeric,void 0),children:u?(0,Q.jsxs)(`button`,{type:`button`,className:`inline-flex items-center gap-1 text-inherit hover:text-heading`,onClick:()=>{let n=`${e.key}-${t&&z.endsWith(`-asc`)?`desc`:`asc`}`;k(n),F({sort:n})},"aria-label":`Sort by ${e.label.toLowerCase()}`,children:[e.label,(0,Q.jsx)(d,{className:`h-3 w-3 transition-transform ${t?`opacity-100`:`opacity-0`} ${n===`ascending`?`rotate-180`:``}`,"aria-hidden":`true`})]}):e.label},e.key)}),(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Details`})})]})}),(0,Q.jsxs)(`tbody`,{children:[B.map(e=>{let t=A===e.id;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:`cursor-pointer transition-colors hover:bg-surface-subtle`,onClick:t=>{tO(t.target)||de(e.id)},children:[(0,Q.jsxs)(`td`,{className:`text-label-14-strong text-heading`,children:[h?h({id:e.id,name:e.name}):e.name,LD(e.status)||e.historical?(0,Q.jsxs)(`span`,{className:`ml-2 inline-flex flex-wrap items-center gap-1 align-middle`,children:[LD(e.status)?(0,Q.jsx)(J,{tone:e.status.tone,children:e.status.label}):null,e.historical?(0,Q.jsx)(J,{tone:`caution`,children:`Historical`}):null]}):null,QD(e)?(0,Q.jsx)(`div`,{className:`mt-0.5 text-label-12 text-faint`,children:QD(e)}):null]}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:(0,Q.jsx)(nO,{metric:e.mentionCoverage,signal:`mentioned`,compact:!0})}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:(0,Q.jsx)(nO,{metric:e.citationCoverage,signal:`cited`,compact:!0})}),(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsx)(q,{size:`icon`,variant:`ghost`,"aria-expanded":t,"aria-label":t?`Hide details for ${e.name}`:`Show details for ${e.name}`,onClick:()=>de(e.id),children:(0,Q.jsx)(d,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${t?`rotate-180`:``}`,"aria-hidden":`true`})})})]},e.id),t?(e.providers??[]).map(t=>(0,Q.jsxs)(`tr`,{className:`measurement-subrow`,children:[(0,Q.jsx)(`td`,{className:`measurement-subrow-name`,children:Vo(t.provider)}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:(0,Q.jsx)(nO,{metric:t.mentionCoverage,signal:`mentioned`,compact:!0})}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:(0,Q.jsx)(nO,{metric:t.citationCoverage,signal:`cited`,compact:!0})}),(0,Q.jsx)(`td`,{})]},`${e.id}:${t.provider}`)):null,t?(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`bg-surface-subtle px-4`,children:(0,Q.jsx)(oO,{property:e,onRetryEvidence:m})})},`${e.id}:details`):null]},e.id)}),B.length===0?(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`py-8 text-center text-label-14 text-secondary`,children:`No properties match this search.`})}):null]})]})}),g&&e.currentView.nextCursor&&f?(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing `,B.length,` of `,e.currentView.propertyTotal]}),c?(0,Q.jsx)(`span`,{role:`alert`,children:`Could not load more properties.`}):null,(0,Q.jsx)(q,{size:`sm`,variant:`outline`,disabled:s,onClick:()=>f(e.currentView.nextCursor),children:s?`Loading…`:c?`Retry loading more properties`:`Show 50 more`})]}):g?B.length<e.currentView.propertyTotal?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:[`Showing `,B.length,` of `,e.currentView.propertyTotal]}):null:(0,Q.jsx)(rO,{shown:B.length,total:ne.length,itemLabel:`properties`,onShowAll:()=>T(2**53-1)})]}),!o&&!te&&U>0?(0,Q.jsx)(`section`,{"aria-label":`Flagged results`,className:`border-t border-default pt-4`,children:(0,Q.jsxs)(`details`,{children:[(0,Q.jsxs)(`summary`,{className:`cursor-pointer text-label-14-strong text-heading`,children:[`Flagged results (`,U,`)`]}),(0,Q.jsx)(`ul`,{className:`mt-3 space-y-3`,children:e.flaggedResults.slice(0,E).map(e=>(0,Q.jsxs)(`li`,{className:`flex flex-wrap items-start gap-2 text-label-14`,children:[(0,Q.jsx)(J,{tone:e.tone,children:`Flagged`}),(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e.property}),(0,Q.jsx)(`span`,{className:`text-secondary`,children:e.summary})]},e.id))}),E<e.flaggedResults.length?(0,Q.jsxs)(`div`,{className:`mt-3 flex items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing details for `,e.flaggedResults.slice(0,E).reduce((e,t)=>e+(t.count??1),0),` of `,U,` flagged results`]}),(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>D(t=>Math.min(e.flaggedResults.length,t+HD)),children:`Show 50 more`})]}):re<U?(0,Q.jsxs)(`div`,{className:`mt-3 flex items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing details for `,re,` of `,U,` flagged results`]}),g&&e.currentView.nextCursor&&f?(0,Q.jsx)(q,{size:`sm`,variant:`outline`,disabled:s,onClick:()=>f(e.currentView.nextCursor),children:s?`Loading…`:c?`Retry loading more Properties`:`Load more Properties`}):null]}):null]})}):null]})}function dO(e){return e===`continue`?`Continue setup`:e===`edit`?`Edit setup`:e===`republish`?`Republish setup`:`Set up advanced measurement`}function fO(e){return e.activePlanSchemaVersion===null?{surface:`simple-overview`,setupAction:e.hasDraft?`continue`:`set-up`}:e.activePlanSchemaVersion<2?{surface:`advanced-overview-v1`,setupAction:`republish`}:{surface:`advanced-overview`,setupAction:e.hasDraft?`continue`:`edit`}}function pO(e){let t=e.targets.length,n=e.groups.filter(e=>e.parentGroupKey===void 0).length,r=[`${t} ${t===1?`property`:`properties`}`];return n>0&&r.push(`${n} ${n===1?`market`:`markets`}`),r.join(` · `)}function mO({mode:e,canEdit:t,simpleOverview:n,report:r,reportState:i=`ready`,onOpenSetup:a,onRunMeasurement:o,onRetryReport:s,onViewChange:c,onLoadMore:l,onPropertyExpand:u,onRetryEvidence:d,renderPropertyLink:f,isRunningMeasurement:p,isOpeningSetup:m,isViewLoading:h,isLoadingMore:g,isLoadMoreError:_,viewSearch:v}){return e.surface===`simple-overview`?n:(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[e.setupAction===`republish`&&!r&&t&&a?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:m,onClick:a,children:m?`Opening setup…`:dO(e.setupAction)}),(0,Q.jsx)(`p`,{className:`supporting-copy m-0`,children:`Unpublished changes are waiting to go live.`})]}):null,i===`loading`?(0,Q.jsx)(`div`,{className:`h-32 animate-pulse rounded-md bg-surface-subtle`,"aria-label":`Loading advanced measurement report`}):i===`error`&&!r?(0,Q.jsxs)(`div`,{role:`alert`,className:`border-y border-negative-800/40 bg-negative-950/20 py-4 text-label-14 text-negative`,children:[(0,Q.jsx)(`p`,{children:`Could not load the advanced measurement report.`}),s?(0,Q.jsx)(q,{className:`mt-3`,type:`button`,size:`sm`,variant:`outline`,onClick:s,children:`Retry report`}):null]}):r?(0,Q.jsx)(uO,{report:r,canEdit:t,onRunMeasurement:o,onRepublishSetup:a,onViewChange:c,onLoadMore:l,onPropertyExpand:u,onRetryEvidence:d,renderPropertyLink:f,isRunningMeasurement:p,isRepublishingSetup:m,isViewLoading:h,isLoadingMore:g,isLoadMoreError:_,viewSearch:v}):(0,Q.jsx)(`div`,{role:`status`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4 text-label-14 text-secondary`,children:`No advanced measurement report is available yet.`})]})}var hO={numerator:null,denominator:null,reason:`plan_v1`};function gO(e){return e.kind===`exact`?e.url:e.kind===`prefix`?`https://${e.host}${e.pathPrefix}`:`https://${e.host}`}function _O(e){return e.numerator===null?{numerator:null,denominator:null,reason:e.reason}:{numerator:e.numerator,denominator:e.denominator,...e.unattributed===void 0?{}:{unattributed:e.unattributed},...e.unchecked===void 0?{}:{unchecked:e.unchecked},...e.citationNotMeasured===void 0?{}:{citationNotMeasured:e.citationNotMeasured}}}function vO(e){return e===`assigned`?`this-property`:e===`sibling`?`another-property`:e===`ownedUnmapped`?`owned-unassigned`:e===`external`?`external`:e===`ambiguous`?`multiple-properties`:`invalid-url`}function yO(e){return e===`assigned`?`positive`:e===`external`?`neutral`:e===`invalid`?`negative`:`caution`}function bO(e){if(!e)return`Date unavailable`;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,year:`numeric`,timeZone:`UTC`}):`Date unavailable`}function xO(e){return e.usageEdgeType!==`target`||!e.usageEdgeId.startsWith(`target:`)?null:e.usageEdgeId.slice(7).split(`:`,1)[0]??null}function SO(e){let t=new Map;for(let n of e){let e=xO(n);if(!e)continue;let r=t.get(e)??[];r.push(n),t.set(e,r)}return t}function CO(e,t){if(e.plan.schemaVersion!==1)throw Error(`Version-one report adapter received a different setup version.`);let n=e.plan,r=new Map(n.targets.map(e=>[e.stableKey,e])),i=new Map(n.querySnapshots.map(e=>[e.queryId,e.queryText])),a=new Map;for(let e of n.targetQuerySelections){let t=a.get(e.targetKey)??[];t.push(...e.queryIds.map(e=>i.get(e)).filter(e=>!!e)),a.set(e.targetKey,[...new Set(t)])}let o=SO(t.evidence),s=n.executionNodes.reduce((e,t)=>e+t.expectedSnapshots,0),c=t.run?.status===`completed`&&s>0,l=c?s:0,u=c?s:0,d=t.targets.map(e=>{let n=r.get(e.id),i=o.get(e.id)??[],s=i.map(e=>({id:`${e.observationId}:${e.usageEdgeId}:${e.sourceUrl}`,kind:vO(e.classification),query:e.queryText,url:e.sourceUrl,tone:yO(e.classification),historical:e.historical||e.bridged})),c=i.some(e=>e.historical||e.bridged),l=t.run?e.completeness.complete?n?.mentionNotApplicable?{label:`No aliases`,tone:`caution`}:{label:`Complete`,tone:`positive`}:{label:`Incomplete · ${e.completeness.executed} of ${e.completeness.expected}`,tone:`caution`}:{label:`Not measured`,tone:`neutral`};return{id:e.id,name:e.label,mentionCoverage:_O(e.mentionCoverage),citationCoverage:_O(e.citationCoverage),status:l,assignedQueries:a.get(e.id)??[],urls:n?.urls.map(gO)??[],evidence:s,historical:c}}),f=new Map(d.map(e=>[e.id,e])),p=new Map(n.groups.map(e=>[e.stableKey,e]));return{classReporting:`plan-v1`,latestMeasurement:{status:t.run?.status===`completed`?{label:`Complete`,tone:`positive`}:t.run?.status===`partial`?{label:`Partial result`,tone:`caution`}:{label:`Not measured`,tone:`neutral`},completedSlots:l,totalSlots:u,date:bO(t.run?.finishedAt??t.run?.createdAt??null),includesBridgedHistory:t.diagnostics.bridgedObservationIds.length>0||t.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:hO,mentionCoverage:hO,citationCoverage:hO},properties:d},groups:t.groups.map(e=>({id:e.id,label:e.label,confirmedCompetitorCount:p.get(e.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:hO,mentionCoverage:hO,citationCoverage:hO},properties:e.targetIds.map(e=>f.get(e)).filter(e=>!!e)}}))},flaggedResults:[]}}function wO({project:e,onUpdateProject:t}){let[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(e.displayName),[u,d]=(0,Z.useState)(e.canonicalDomain),[f,p]=(0,Z.useState)(e.country),[m,h]=(0,Z.useState)(e.language),[g,_]=(0,Z.useState)(e.ownedDomains??[]),[v,y]=(0,Z.useState)(``),[b,x]=(0,Z.useState)(e.aliases??[]),[S,C]=(0,Z.useState)(``),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(!1),[O,k]=(0,Z.useState)(!1),[A,j]=(0,Z.useState)(``),[M,N]=(0,Z.useState)(``),[P,F]=(0,Z.useState)(``),[I,ee]=(0,Z.useState)(``),[L,R]=(0,Z.useState)(``),[z,te]=(0,Z.useState)(null),[ne,B]=(0,Z.useState)(null),V=(0,Z.useId)();(0,Z.useEffect)(()=>{n||(l(e.displayName),d(e.canonicalDomain),p(e.country),h(e.language),_(e.ownedDomains??[]),x(e.aliases??[]))},[e,n]);function H(){r(!1),s(null),l(e.displayName),d(e.canonicalDomain),p(e.country),h(e.language),_(e.ownedDomains??[]),x(e.aliases??[]),y(``),C(``)}function re(){let e=v.trim();e&&(g.includes(e)||_([...g,e]),y(``))}function U(e){_(g.filter(t=>t!==e))}function ie(){let e=S.trim();if(!e)return;let t=e.toLowerCase();b.some(e=>e.toLowerCase()===t)||x([...b,e]),C(``)}function W(e){x(b.filter(t=>t!==e))}async function ae(){if(c.trim()&&u.trim()&&f.trim()&&m.trim()){a(!0),s(null);try{await t(e.name,{displayName:c.trim(),canonicalDomain:u.trim(),ownedDomains:g,aliases:b,country:f.trim(),language:m.trim()}),r(!1),li({title:`Project settings saved`,detail:`${c.trim()} was updated.`,tone:`positive`,dedupeKey:`project:update:${e.name}`,dedupeMode:`replace`})}catch(e){s(e instanceof Error?e.message:`Failed to save`)}finally{a(!1)}}}async function oe(){let t=A.trim(),n=M.trim(),r=P.trim(),i=I.trim();if(t&&n&&r&&i){D(!0),T(null);try{let a={label:t,city:n,region:r,country:i};L.trim()&&(a.timezone=L.trim()),await Xn(e.name,a),j(``),N(``),F(``),ee(``),R(``),k(!1),li({title:`Search location added`,detail:`${t} is now available for ${e.name}.`,tone:`positive`,dedupeKey:`project:location:add:${e.name}:${t}`,dedupeMode:`drop`})}catch(e){T(e instanceof Error?e.message:`Failed to add search location`)}finally{D(!1)}}}async function se(t){D(!0),T(null);try{await Mt(e.name,t),li({title:`Search location removed`,detail:`${t} was removed from ${e.name}.`,tone:`positive`,dedupeKey:`project:location:remove:${e.name}:${t}`,dedupeMode:`drop`})}catch(e){T(e instanceof Error?e.message:`Failed to remove search location`)}finally{D(!1)}}async function ce(t){D(!0),T(null);try{await Fn(e.name,t),li({title:`Default search location updated`,detail:`${t} is now the default for ${e.name}.`,tone:`positive`,dedupeKey:`project:location:default:${e.name}`,dedupeMode:`replace`})}catch(e){T(e instanceof Error?e.message:`Failed to set default search location`)}finally{D(!1)}}async function le(t){te(t),B(null);try{await dt(e.name,t),li({title:`${t.toUpperCase()} download started`,detail:`Historical citation and mention results for ${e.displayName}.`,tone:`positive`,dedupeKey:`project:results-export:${e.name}`,dedupeMode:`replace`})}catch(e){B(e instanceof Error?e.message:`Could not download tracking results.`)}finally{te(null)}}let ue=c!==e.displayName||u!==e.canonicalDomain||f!==e.country||m!==e.language||JSON.stringify(g)!==JSON.stringify(e.ownedDomains??[])||JSON.stringify(b)!==JSON.stringify(e.aliases??[]),de=!K()&&!rt(),fe=`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,pe=`mb-1 block text-label-14-strong text-secondary`,me=A.trim()&&M.trim()&&P.trim()&&I.trim();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`page-section`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h2`,{children:`Project settings`})}),de&&!n&&(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(!0),children:`Edit settings`})]}),o&&(0,Q.jsxs)(`div`,{className:`mb-3 rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-label-14 text-negative`,children:[o,(0,Q.jsx)(`button`,{type:`button`,className:`ml-2 text-negative-400 hover:text-negative-200`,onClick:()=>s(null),children:`×`})]}),de&&n?(0,Q.jsxs)(`div`,{className:`material-base p-4 space-y-4`,children:[(0,Q.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-4`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-display-name`,className:pe,children:`Display name`}),(0,Q.jsx)(`input`,{id:`${V}-display-name`,className:fe,type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`My Project`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-main-domain`,className:pe,children:`Main domain`}),(0,Q.jsx)(`input`,{id:`${V}-main-domain`,className:fe,type:`text`,value:u,onChange:e=>d(e.target.value),placeholder:`example.com`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-country`,className:pe,children:`Country`}),(0,Q.jsx)(`input`,{id:`${V}-country`,className:fe,type:`text`,value:f,onChange:e=>p(e.target.value),placeholder:`US`,maxLength:2})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-language`,className:pe,children:`Language`}),(0,Q.jsx)(`input`,{id:`${V}-language`,className:fe,type:`text`,value:m,onChange:e=>h(e.target.value),placeholder:`en`})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-owned-domain`,className:pe,children:`Owned domains`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:g.map(e=>(0,Q.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-label-12 text-neutral`,children:[e,(0,Q.jsx)(`button`,{type:`button`,className:`ml-0.5 text-muted hover:text-strong transition-colors`,onClick:()=>U(e),"aria-label":`Remove ${e}`,children:`×`})]},e))}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(`input`,{id:`${V}-owned-domain`,className:`${fe} flex-1`,type:`text`,placeholder:`docs.example.com`,value:v,onChange:e=>y(e.target.value),onKeyDown:e=>e.key===`Enter`&&(e.preventDefault(),re())}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:!v.trim(),onClick:re,children:`Add`})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-alias`,className:pe,children:`Aliases`}),(0,Q.jsx)(`p`,{className:`mb-1.5 text-copy-14 text-secondary`,children:`Other brand names that may appear in answers.`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:b.map(e=>(0,Q.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-label-12 text-neutral`,children:[e,(0,Q.jsx)(`button`,{type:`button`,className:`ml-0.5 text-muted hover:text-strong transition-colors`,onClick:()=>W(e),"aria-label":`Remove ${e}`,children:`×`})]},e))}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(`input`,{id:`${V}-alias`,className:`${fe} flex-1`,type:`text`,placeholder:`Facebook`,value:S,onChange:e=>C(e.target.value),onKeyDown:e=>e.key===`Enter`&&(e.preventDefault(),ie())}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:!S.trim(),onClick:ie,children:`Add`})]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 pt-2 border-t border-default`,children:[(0,Q.jsx)(q,{type:`button`,disabled:i||!ue||!c.trim()||!u.trim(),onClick:ci(ae),children:i?`Saving...`:`Save changes`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,disabled:i,onClick:H,children:`Cancel`})]})]}):(0,Q.jsx)(`div`,{className:`material-base overflow-hidden`,children:(0,Q.jsx)(`table`,{className:`w-full text-label-14`,children:(0,Q.jsxs)(`tbody`,{children:[(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong w-40`,children:`Display name`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-strong`,children:e.displayName||`—`})]}),(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Main domain`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-strong`,children:e.canonicalDomain})]}),(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Owned domains`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5`,children:(e.ownedDomains??[]).length>0?(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.ownedDomains.map(e=>(0,Q.jsx)(`span`,{className:`rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-label-12 text-neutral`,children:e},e))}):(0,Q.jsx)(`span`,{className:`text-muted`,children:`—`})})]}),(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Aliases`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5`,children:(e.aliases??[]).length>0?(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.aliases.map(e=>(0,Q.jsx)(`span`,{className:`rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-label-12 text-neutral`,children:e},e))}):(0,Q.jsx)(`span`,{className:`text-muted`,children:`—`})})]}),(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Market`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-strong`,children:zt(e.country,e.language)})]}),e.tags?.length?(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Tags`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5`,children:(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.tags.map(e=>(0,Q.jsx)(`span`,{className:`rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-label-12 text-neutral`,children:e},e))})})]}):null,(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong align-top pt-3`,children:`Search locations`}),(0,Q.jsxs)(`td`,{className:`px-4 py-2.5`,children:[w&&(0,Q.jsxs)(`div`,{className:`mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-label-12 text-negative`,children:[w,(0,Q.jsx)(`button`,{type:`button`,className:`ml-1 text-negative-400 hover:text-negative-200`,onClick:()=>T(null),children:`×`})]}),(e.locations??[]).length>0?(0,Q.jsxs)(`table`,{className:`w-full text-label-12 mb-2`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`text-faint`,children:[(0,Q.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Label`}),(0,Q.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`City`}),(0,Q.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Region`}),(0,Q.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Country`}),(0,Q.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Timezone`}),(0,Q.jsx)(`th`,{className:`pb-1`})]})}),(0,Q.jsx)(`tbody`,{children:e.locations.map(t=>(0,Q.jsxs)(`tr`,{className:`border-t border-mono-800/30`,children:[(0,Q.jsx)(`td`,{className:`py-1.5 pr-3`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-label-12-strong ${t.label===e.defaultLocation?`border-positive-700/60 bg-positive-950/30 text-positive`:`border-mono-700/60 bg-mono-800/40 text-neutral`}`,children:[t.label,t.label===e.defaultLocation?` ★`:``]})}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-neutral`,children:t.city}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-neutral`,children:t.region}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-neutral`,children:t.country}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-muted`,children:t.timezone??`—`}),(0,Q.jsx)(`td`,{className:`py-1.5`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[de&&t.label!==e.defaultLocation&&(0,Q.jsx)(`button`,{type:`button`,disabled:E,onClick:()=>{ce(t.label)},className:`text-button-14 text-secondary hover:text-positive-400 transition-colors disabled:opacity-40`,"aria-label":`Set ${t.label} as default search location`,children:`Set default`}),de&&(0,Q.jsx)(`button`,{type:`button`,disabled:E,onClick:()=>{se(t.label)},className:`text-button-14 text-secondary hover:text-negative-400 transition-colors disabled:opacity-40`,"aria-label":`Remove search location ${t.label}`,children:`Remove`})]})})]},t.label))})]}):(0,Q.jsx)(`p`,{className:`text-muted text-copy-13 mb-2`,children:`No search locations configured`}),de?O?(0,Q.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:`Add search location`}),(0,Q.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Label *`}),(0,Q.jsx)(`input`,{className:fe,type:`text`,value:A,onChange:e=>j(e.target.value),placeholder:`nyc`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`City *`}),(0,Q.jsx)(`input`,{className:fe,type:`text`,value:M,onChange:e=>N(e.target.value),placeholder:`New York`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Region *`}),(0,Q.jsx)(`input`,{className:fe,type:`text`,value:P,onChange:e=>F(e.target.value),placeholder:`NY`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Country *`}),(0,Q.jsx)(`input`,{className:fe,type:`text`,value:I,onChange:e=>ee(e.target.value),placeholder:`US`,maxLength:2})]}),(0,Q.jsxs)(`div`,{className:`col-span-2`,children:[(0,Q.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Timezone (optional)`}),(0,Q.jsx)(`input`,{className:fe,type:`text`,value:L,onChange:e=>R(e.target.value),placeholder:`America/New_York`})]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 pt-1`,children:[(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:E||!me,onClick:ci(oe),children:E?`Adding...`:`Add search location`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:E,onClick:()=>{k(!1),T(null)},children:`Cancel`})]})]}):(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>k(!0),children:`+ Add search location`}):null]})]})]})})})]}),(0,Q.jsxs)(`section`,{className:`page-section`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsxs)(`div`,{className:`inline-flex items-center`,children:[(0,Q.jsx)(`h2`,{children:`Tracking results`}),(0,Q.jsx)(X,{text:`Each exported row is one query and engine result, including the saved answer and source URLs. Includes completed, partial, and failed checks with saved results. Test runs, provider credentials, and raw provider payloads are excluded.`})]})}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`flex flex-wrap items-center gap-3`,children:(0,Q.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2`,children:[(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:z!==null,onClick:ci(()=>le(`csv`)),children:z===`csv`?`Preparing CSV...`:`Download CSV`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:z!==null,onClick:ci(()=>le(`json`)),children:z===`json`?`Preparing JSON...`:`Download JSON`})]})}),ne&&(0,Q.jsx)(`p`,{className:`mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-copy-14 text-negative`,children:ne})]})]})]})}var TO={edit:`Edit schedule`,pause:`Pause`,resume:`Resume`,save:`Save schedule`},EO=[{value:`daily`,label:`Every day`},{value:`weekly@mon`,label:`Every Monday`},{value:`weekly@wed`,label:`Every Wednesday`},{value:`weekly@fri`,label:`Every Friday`},{value:`twice-daily`,label:`Twice a day (6am & 6pm)`},{value:`calendar`,label:`Every N days`},{value:`custom`,label:`Custom cron expression`}],DO=[`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 OO(e,t){let n=t===`UTC`?`UTC`:t.split(`/`).pop()?.replace(/_/g,` `)??t,r=new Date(`${e.startDate}T00:00:00Z`),i=Number.isNaN(r.getTime())?e.startDate:new Intl.DateTimeFormat(`en-US`,{month:`short`,day:`numeric`,year:`numeric`,timeZone:`UTC`}).format(r),[a,o]=e.time.split(`:`).map(Number),s=Number.isInteger(a)&&Number.isInteger(o)?new Intl.DateTimeFormat(`en-US`,{hour:`numeric`,minute:`2-digit`,timeZone:`UTC`}).format(new Date(Date.UTC(1970,0,1,a,o))):e.time;return`Every ${e.everyDays} days starting ${i} at ${s} · ${n}`}function kO({projectName:e}){let t=(0,Z.useId)(),n=we(),r=!K()&&!rt()&&!n,i=z(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(`daily`),[d,f]=(0,Z.useState)(6),[p,m]=(0,Z.useState)(``),[h,g]=(0,Z.useState)(14),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(`00:00`),[x,S]=(0,Z.useState)(`UTC`),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(``),[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(!1),[j,M]=(0,Z.useState)(null),[N,P]=(0,Z.useState)(void 0),F=Wi({client:Y,path:{name:e}}),I=W({...po({client:Y,path:{name:e}}),staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`,retry:!1}),ee=I.isPending||I.isFetching,L=I.isError,R=I.data?.find(e=>e.kind===Qt[`answer-visibility`])??null,te=a&&N!==void 0&&(R?.updatedAt??null)!==N,ne=C?T.trim():x,B={timezone:ne,...l===`calendar`?{recurrence:{everyDays:h,startDate:_,time:y}}:l===`custom`?{cron:p.trim()}:{preset:ii(l,d)}},V=!!ne&&(l!==`custom`||!!p.trim())&&(l!==`calendar`||Number.isInteger(h)&&h>=1&&h<=3650&&!!_&&!!y),H=W({queryKey:[`schedule-preview`,e,B],queryFn:()=>mt(e,B),enabled:r&&a&&V,retry:!1,staleTime:0}),re=V&&H.isSuccess&&!H.isFetching&&!!H.data.nextRunAt,U=e=>{i.setQueryData(F,t=>{let n=(t??[]).filter(e=>e.kind!==Qt[`answer-visibility`]);return e?[...n,e]:n})},ie=e=>{if(e){if(e.recurrence)u(`calendar`),g(e.recurrence.everyDays),v(e.recurrence.startDate),b(e.recurrence.time);else{let t=qr(e.preset??null,e.cronExpr);u(t.freq),f(t.hour),m(t.customCron)}let t=DO.includes(e.timezone);S(t?e.timezone:`Other`),w(!t),E(t?``:e.timezone)}else{u(`daily`),f(6),m(``),g(14),v(``),b(`00:00`);let e=Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`,t=DO.includes(e);S(t?e:`Other`),w(!t),E(t?``:e)}P(e?.updatedAt??null)},ae=()=>{r&&(ie(R),c(!1),M(null),o(!0))},oe=()=>{ie(R),M(null)},se=async()=>{(await I.refetch()).isError?M(`The schedule changed, but Canonry could not load the latest version. Retry the schedule check.`):M(a?null:`This schedule changed elsewhere. The latest version is now shown; review it and try again.`)},ce=async(e,t)=>{e instanceof Ln&&e.code===`SCHEDULE_VERSION_CONFLICT`?await se():M(e instanceof Error?e.message:t)};return(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h2`,{children:`Scheduled runs`})}),r&&!ee&&!L&&!a&&(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:ae,children:R?TO.edit:`+ Set schedule`})]}),ee&&(0,Q.jsx)(`p`,{className:`supporting-copy`,children:`Loading…`}),j&&!a&&(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-negative`,role:`alert`,children:j}),!ee&&L&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`supporting-copy`,children:`Canonry could not verify this schedule.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>{I.refetch()},children:`Retry`})]}),!ee&&!L&&!a&&R===null&&(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`p`,{className:`supporting-copy`,children:n?`AI Visibility checks are run by your Canonry team`:`No schedule configured. Set one to automatically trigger AI Visibility checks.`})}),!ee&&!L&&!a&&R!==null&&(0,Q.jsx)(`div`,{children:(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1`,children:[n&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`AI Visibility checks are run by your Canonry team`}),(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:R.recurrence?OO(R.recurrence,R.timezone):jr(R.preset??null,R.cronExpr,R.timezone)}),!R.recurrence&&(0,Q.jsxs)(`details`,{className:`text-copy-13 text-muted`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer`,children:`Schedule details`}),(0,Q.jsxs)(`p`,{children:[`Cron: `,(0,Q.jsx)(`span`,{className:`font-mono`,children:R.cronExpr})]})]}),R.enabled&&R.nextRunAt&&(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[`Next run: `,un(R.nextRunAt,R.timezone)]}),R.lastRunAt&&(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[`Last run: `,new Date(R.lastRunAt).toLocaleString()]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,Q.jsx)(J,{tone:R.enabled?`positive`:`neutral`,children:R.enabled?`Active`:`Paused`}),r&&(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:D,onClick:ci(async()=>{if(!r||!R)return;if(!R.enabled){ie(R),c(!0),M(null),o(!0);return}let t=R.updatedAt;O(!0),M(null);try{let n=await I.refetch();if(n.isError||n.data===void 0){M(`Canonry could not verify the latest schedule. Try again before updating it.`);return}let r=n.data.find(e=>e.kind===Qt[`answer-visibility`])??null;if(!r||r.updatedAt!==t){M(`This schedule changed elsewhere. Review the latest version and try again.`);return}let i={timezone:r.timezone,enabled:!r.enabled,providers:r.providers,expectedUpdatedAt:t};r.recurrence?i.recurrence=r.recurrence:r.preset?i.preset=r.preset:i.cron=r.cronExpr;let a=await ut(e,i);U(a),li({title:a.enabled?`Schedule resumed`:`Schedule paused`,detail:a.recurrence?OO(a.recurrence,a.timezone):jr(a.preset??null,a.cronExpr,a.timezone),tone:`positive`,dedupeKey:`schedule:toggle:${e}`,dedupeMode:`replace`})}catch(e){await ce(e,`Failed to update schedule`)}finally{O(!1)}}),children:R.enabled?TO.pause:TO.resume}),r&&(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,disabled:k,onClick:ci(async()=>{if(!r||!R)return;let t=R.updatedAt;A(!0),M(null);try{await qn(e,t),U(null),o(!1),P(void 0),li({title:`Schedule removed`,detail:`${e} will no longer run automatically.`,tone:`positive`,dedupeKey:`schedule:remove:${e}`,dedupeMode:`drop`})}catch(e){await ce(e,`Failed to remove schedule`)}finally{A(!1)}}),children:k?`Removing…`:`Remove`})]})]})}),r&&a&&(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[te&&!D&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 rounded-md border border-caution bg-caution-soft px-3 py-2 text-label-14 text-caution`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:`This schedule changed elsewhere. Load the latest version before saving.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:oe,children:`Load latest schedule`})]}),(0,Q.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Frequency`}),(0,Q.jsx)(`select`,{className:`w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Frequency`,value:l,onChange:e=>u(e.target.value),children:EO.map(e=>(0,Q.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),l!==`calendar`&&(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsxs)(`label`,{className:`text-label-13-strong text-secondary`,htmlFor:`${t}-hour`,children:[`Time · `,ne||`choose timezone`]}),(0,Q.jsx)(`select`,{id:`${t}-hour`,className:`w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40`,value:d,disabled:l===`twice-daily`||l===`custom`,onChange:e=>f(parseInt(e.target.value)),children:Array.from({length:24},(e,t)=>(0,Q.jsx)(`option`,{value:t,children:Lr(t)},t))})]})]}),l===`custom`&&(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-13-strong text-secondary`,htmlFor:`${t}-cron`,children:`Cron expression`}),(0,Q.jsx)(`input`,{id:`${t}-cron`,className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14-mono text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`text`,placeholder:`0 9 * * 1-5`,value:p,onChange:e=>m(e.target.value)})]}),l===`calendar`&&(0,Q.jsxs)(`div`,{className:`grid grid-cols-3 gap-3`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Repeat every`}),(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Repeat every days`,type:`number`,min:`1`,max:`3650`,value:h,onChange:e=>g(Number(e.target.value))}),(0,Q.jsx)(`p`,{className:`text-copy-13 text-muted`,children:`days`})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Start date`}),(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Start date`,type:`date`,value:_,onChange:e=>v(e.target.value)})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Time`}),(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Recurrence time`,type:`time`,value:y,onChange:e=>b(e.target.value)})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Timezone`}),(0,Q.jsxs)(`select`,{className:`w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Timezone`,value:C?`Other`:x,onChange:e=>{e.target.value===`Other`?(w(!0),S(`Other`)):(w(!1),S(e.target.value))},children:[DO.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e)),(0,Q.jsxs)(`option`,{value:`Other`,children:[`Other (enter manually)`,`…`]})]}),C&&(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`text`,"aria-label":`Custom timezone`,placeholder:`e.g. America/New_York`,value:T,onChange:e=>E(e.target.value)})]}),V&&(0,Q.jsx)(`div`,{"aria-live":`polite`,className:`text-copy-14`,children:H.isFetching||H.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`text-secondary`,children:`Checking next run…`}):H.isError?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-negative`,children:be(H.error)}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{H.refetch()},children:`Retry preview`})]}):(0,Q.jsxs)(`p`,{className:`text-heading`,children:[`Next run: `,H.data.nextRunAt?(0,Q.jsx)(`time`,{dateTime:H.data.nextRunAt,children:un(H.data.nextRunAt,H.data.timezone)}):`No future occurrence`]})}),j&&(0,Q.jsx)(`p`,{className:`text-negative-400 text-copy-14`,role:`alert`,children:j}),(0,Q.jsxs)(`div`,{className:`flex gap-2 justify-end`,children:[(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{o(!1),P(void 0),M(null)},children:`Cancel`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:D||I.isFetching||L||te||!re,onClick:ci(async()=>{if(r&&!te&&N!==void 0&&re){O(!0),M(null);try{let t=await I.refetch();if(t.isError||t.data===void 0){M(`Canonry could not verify the latest schedule. Try again before saving.`);return}let n=t.data.find(e=>e.kind===Qt[`answer-visibility`])??null;if((n?.updatedAt??null)!==N)return;let r={...B,enabled:s||(n?.enabled??!0),providers:n?.providers??[],expectedUpdatedAt:N},i=await ut(e,r);o(!1),P(void 0),U(i),li({title:`Schedule saved`,detail:i.recurrence?OO(i.recurrence,i.timezone):jr(i.preset??null,i.cronExpr,i.timezone),tone:`positive`,dedupeKey:`schedule:${e}`,dedupeMode:`replace`})}catch(e){await ce(e,`Failed to save schedule`)}finally{O(!1)}}}),children:D?`Saving…`:s?`Enable schedule`:TO.save})]})]})]})}var AO={"citation.lost":`Citation lost`,"citation.gained":`Citation gained`,"mention.lost":`Mention lost`,"mention.gained":`Mention gained`,"run.completed":`Run completed`,"run.failed":`Run failed`,"insight.critical":`Critical insight`,"insight.high":`High-severity insight`,"health.degraded":`Health degraded`,"health.recovered":`Health recovered`,"health.urgent":`Urgent health problem`,"health.urgent-resolved":`Urgent problem resolved`,"review.negative":`Negative review`,"review.rating-dropped":`Rating dropped`,"traffic.agent.discovered":`New bot or agent`,"site-health.issue.new":`New Agent Readiness problem`,"sentiment.unfavorable":`Answer turned unfavorable`},jO=er.options.map(e=>({value:e,label:AO[e],description:dn[e]})),MO=[`mention.lost`,`mention.gained`,`citation.lost`,`citation.gained`];function NO(e){let t=er.safeParse(e);return t.success?AO[t.data]:e}function PO({projectName:e}){let[t,n]=(0,Z.useState)(`loading`),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(MO),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)({}),[h,g]=(0,Z.useState)(new Set),_=!K()&&!rt();(0,Z.useEffect)(()=>{Ne(e).then(n).catch(()=>n([]))},[e]);let v=e=>{c(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},y=async()=>{if(a.trim()&&s.length!==0){u(!0),f(null);try{let t=await nn(e,{channel:`webhook`,url:a.trim(),events:s});n(e=>e===`loading`?[t]:[...e,t]),o(``),c(MO),i(!1),li({title:`Webhook added`,detail:`Notifications will be sent to ${t.url}.`,tone:`positive`,dedupeKey:`notification:add:${e}`,dedupeMode:`drop`})}catch(e){f(e instanceof Error?e.message:`Failed to add webhook`)}finally{u(!1)}}},b=async t=>{if(!h.has(t)){g(e=>new Set(e).add(t));try{await Ie(e,t),n(e=>e===`loading`?e:e.filter(e=>e.id!==t)),li({title:`Webhook removed`,detail:`${e} no longer sends notifications to this endpoint.`,tone:`positive`,dedupeKey:`notification:remove:${e}:${t}`,dedupeMode:`drop`})}catch(e){f(e instanceof Error?e.message:`Failed to remove webhook`)}finally{g(e=>{let n=new Set(e);return n.delete(t),n})}}},x=async t=>{m(e=>({...e,[t]:{state:`testing`}}));try{let n=await fn(e,t);m(e=>({...e,[t]:{state:n.ok?`ok`:`fail`,status:n.status}})),n.ok&&li({title:`Test notification sent`,detail:`Webhook returned status ${n.status}.`,tone:`positive`,dedupeKey:`notification:test:${e}:${t}`,dedupeMode:`replace`})}catch{m(e=>({...e,[t]:{state:`fail`}}))}};return(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h2`,{children:`Notifications`})}),_&&t!==`loading`&&(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{i(!r),f(null)},children:r?`Cancel`:`+ Add webhook`})]}),_&&r&&(0,Q.jsxs)(`div`,{className:`mb-3 material-base p-4 space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Webhook URL`}),(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`url`,placeholder:`https://hooks.example.com/canonry`,value:a,onChange:e=>o(e.target.value)})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Trigger on`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-3`,children:jO.map(e=>(0,Q.jsxs)(`label`,{title:e.description,className:`flex items-center gap-1.5 cursor-pointer select-none`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`rounded border-mono-600 bg-mono-800`,checked:s.includes(e.value),onChange:()=>v(e.value)}),(0,Q.jsx)(`span`,{className:`text-label-14 text-neutral`,children:e.label})]},e.value))})]}),d&&(0,Q.jsx)(`p`,{className:`text-negative-400 text-copy-14`,children:d}),(0,Q.jsxs)(`div`,{className:`flex gap-2 justify-end`,children:[(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{i(!1),f(null)},children:`Cancel`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:l||!a.trim()||s.length===0,onClick:ci(y),children:l?`Adding…`:`Add webhook`})]})]}),t===`loading`&&(0,Q.jsx)(`p`,{className:`supporting-copy`,children:`Loading…`}),t!==`loading`&&t.length===0&&!r&&(0,Q.jsx)(Cs,{className:`surface-card compact-card`,children:(0,Q.jsx)(`p`,{className:`supporting-copy`,children:`No webhooks configured. Add one to get alerted when mentions or citations change or runs complete.`})}),t!==`loading`&&t.length>0&&(0,Q.jsxs)(`div`,{className:`evidence-table-wrap`,children:[(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Endpoint`}),(0,Q.jsx)(`th`,{children:`Events`}),(0,Q.jsx)(`th`,{children:`Status`}),(0,Q.jsx)(`th`,{})]})}),(0,Q.jsx)(`tbody`,{children:t.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`evidence-query-cell`,children:(0,Q.jsx)(`span`,{className:`text-label-12-mono text-neutral break-all`,title:e.urlHost,children:e.urlDisplay??e.url})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.events.map(e=>(0,Q.jsx)(`span`,{title:e,className:`inline-flex items-center rounded-full border border-strong bg-surface-inset px-2 py-0.5 text-label-12-strong text-secondary normal-case`,children:NO(e)},e))})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:e.enabled?`positive`:`neutral`,children:e.enabled?`Active`:`Paused`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1 justify-end`,children:[p[e.id]&&(()=>{let t=p[e.id],n=t.state===`testing`?`Sending…`:t.state===`ok`?`Delivered${t.status?` (${t.status})`:``}`:`Failed${t.status?` (${t.status})`:``}`;return(0,Q.jsx)(J,{tone:t.state===`ok`?`positive`:t.state===`fail`?`negative`:`neutral`,children:n})})(),_&&(0,Q.jsx)(q,{variant:`ghost`,size:`sm`,type:`button`,disabled:p[e.id]?.state===`testing`,onClick:()=>{x(e.id)},children:`Test`}),_&&(0,Q.jsx)(q,{variant:`ghost`,size:`sm`,type:`button`,disabled:h.has(e.id),onClick:()=>{b(e.id)},children:h.has(e.id)?`Removing…`:`Remove`})]})})]},e.id))})]}),d&&(0,Q.jsx)(`p`,{className:`text-negative-400 text-copy-14 mt-2`,children:d})]})]})}var FO=e({COMPETITOR_COMPARISON_COPY:()=>WO,ProjectPage:()=>qO,ProjectSubnav:()=>YO,ProjectSweepConfirmation:()=>IO,patchProjectDashboardCache:()=>BO,projectSectionTabs:()=>JO});function IO({open:e,projectLabel:t,onOpenChange:n,onConfirm:r,onClosed:i,disabled:a,leftOut:o=[],preview:s,previewPending:c=!1,previewFailed:l=!1,onRetryPreview:u=()=>{}}){return K()||we()?null:(0,Q.jsx)(L,{open:e,onOpenChange:n,children:(0,Q.jsxs)(F,{children:[(0,Q.jsx)(N,{className:`fixed inset-0 z-50 bg-overlay-scrim/70 backdrop-blur-sm`}),(0,Q.jsxs)(I,{className:`material-modal fixed left-1/2 top-1/2 z-50 max-h-[85dvh] w-[calc(100%-2rem)] max-w-xl -translate-x-1/2 -translate-y-1/2 overflow-y-auto p-5`,onCloseAutoFocus:e=>{i&&(e.preventDefault(),i())},children:[(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(ee,{className:`text-heading-20 text-heading`,children:`Review AI Visibility check`}),(0,Q.jsxs)(P,{className:`text-copy-14 text-secondary`,children:[`Checks `,t,` using the scope below. View filters do not limit the check. Provider charges apply.`,o.length>0?` ${o.map(e=>Vo(e)).join(` and `)} ${o.length===1?`is`:`are`} left out: ${o.length===1?`it keeps failing on its account`:`they keep failing on their accounts`}.`:null]})]}),(0,Q.jsx)(`div`,{className:`mt-5`,children:(0,Q.jsx)(As,{preview:s,pending:c,failed:l,onRetry:u})}),(0,Q.jsx)(`p`,{className:`mt-4 text-copy-13 text-secondary`,children:`Runs once. Your schedule stays unchanged.`}),(0,Q.jsxs)(`div`,{className:`mt-6 flex flex-wrap gap-3`,children:[(0,Q.jsx)(q,{variant:`outline`,onClick:()=>n(!1),children:`Cancel`}),(0,Q.jsx)(fs,{disabled:a||c||l||s?.canStart!==!0,onClick:r,children:`Run project-wide check`})]})]})]})})}var LO=2e3,RO=3e5;function zO(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function BO(e,t){e.setQueriesData({predicate:e=>e.queryKey[0]===`project-dashboard-full`&&e.queryKey[1]===t.id},e=>!e||typeof e!=`object`||!(`project`in e)?e:{...e,project:t})}function VO({projectName:e}){let t=(0,Z.useId)(),n=z(),[r,i]=(0,Z.useState)(`google`),[a,o]=(0,Z.useState)(!0),[s,c]=(0,Z.useState)(`idle`),[l,u]=(0,Z.useState)(null),d=(0,Z.useRef)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),[g,v]=(0,Z.useState)(0);async function y(t=!1){t||o(!0),u(null);try{let[t,r]=await Promise.all([n.fetchQuery({...oo({client:Y,path:{name:e}}),staleTime:di}).catch(()=>[]),n.fetchQuery({...zi({client:Y,path:{name:e}}),staleTime:di}).catch(()=>null)]),i=t.find(e=>e.connectionType===`gsc`)??null;p(i),h(r)}catch(e){u(e instanceof Error?e.message:`Failed to load search engine connections`)}finally{o(!1)}}async function b(){if(s!==`idle`)return;d.current?.abort();let t=new AbortController;d.current=t;let r=t.signal;c(`syncing`),u(null),li({title:`Refreshing search coverage`,detail:`Queueing Google and Bing checks, then reloading the workspaces.`,tone:`neutral`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`});let i=[],a=[];try{async function t(){if(!f)return;let t=await gt(e);if(!t?.id)return;let n=Date.now()+RO;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,LO)),r.aborted))return;let e=await nr(t.id).catch(()=>null);if(!e)break;if([`completed`,`failed`,`cancelled`].includes(e.status)){e.status!==`completed`&&i.push(`Google sync ${e.status}`);return}}a.push(`Google sync is still running — search data will appear shortly`)}async function o(){if(!m?.connected)return;let t=await vt(e).catch(()=>null);if(!t?.id){i.push(`Bing check could not be started`);return}let n=Date.now()+RO;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,LO)),r.aborted))return;let e=await nr(t.id).catch(()=>null);if(!e)break;if([`completed`,`failed`,`cancelled`,`partial`].includes(e.status)){e.status===`failed`?i.push(`Bing check failed`):e.status===`partial`&&a.push(`Bing check finished with some pages unverified`);return}}a.push(`Bing check is still running. Coverage will update shortly.`)}async function s(){if(!m?.connected||!m.siteUrl)return;let t=await yr(e).catch(()=>null);if(!t?.id){i.push(`Bing data sync could not be started`);return}let n=Date.now()+RO;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,LO)),r.aborted))return;let e=await nr(t.id).catch(()=>null);if(!e)break;if([`completed`,`failed`,`cancelled`,`partial`].includes(e.status)){e.status===`failed`?i.push(`Bing data sync failed`):e.status===`partial`&&a.push(`Bing data sync finished with some sections missing`);return}}a.push(`Bing data sync is still running. Search data will update shortly.`)}let l=await Promise.allSettled([t(),o(),s()]);for(let e of l)e.status===`rejected`&&i.push(e.reason instanceof Error?e.reason.message:`Sync failed`);if(await Promise.all([ui(n,`gsc`),ui(n,`bing`),ui(n,`sitemaps`)]),r.aborted)return;if(c(`reloading`),await y(!0),v(e=>e+1),i.length>0){let t=`Partial refresh: ${[...i,...a].join(`; `)}`;u(t),li({title:`Search coverage partially refreshed`,detail:t,tone:`caution`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`})}else a.length>0?li({title:`Search coverage refresh incomplete`,detail:a.join(`; `),tone:`caution`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`}):li({title:`Search coverage refreshed`,detail:`Google and Bing workspaces are reloaded with the latest stored coverage.`,tone:`positive`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`})}catch(t){if(!r.aborted){let n=t instanceof Error?t.message:`Refresh failed`;u(n),li({title:`Search coverage refresh failed`,detail:n,tone:`negative`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`})}}finally{r.aborted||c(`idle`)}}return(0,Z.useEffect)(()=>(y(),()=>{d.current?.abort()}),[e]),(0,Q.jsxs)(`div`,{className:`space-y-6`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Q.jsx)(vl,{id:t,label:`Search engine workspaces`,value:r,onChange:i,className:`flex flex-wrap gap-2`,tabClassName:`project-subnav-link`,activeTabClassName:`project-subnav-link-active`,options:[[`google`,`Google`],[`bing`,`Bing`]]}),!K()&&(0,Q.jsxs)(fs,{type:`button`,variant:`outline`,size:`sm`,"aria-label":`Refresh search data`,disabled:a||s!==`idle`,onClick:()=>void b(),children:[(0,Q.jsx)(_,{className:`h-3.5 w-3.5 ${s===`idle`?``:`animate-spin`}`,"aria-hidden":`true`}),a?`Loading…`:s===`syncing`?`Refreshing search data…`:s===`reloading`?`Reloading workspaces…`:`Refresh search data`]})]}),l&&(0,Q.jsx)(`div`,{className:`rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-label-14 text-negative`,children:l}),(0,Q.jsxs)(`div`,{id:`${t}-panel`,role:`tabpanel`,"aria-labelledby":`${t}-${r}`,tabIndex:0,children:[r===`google`&&(0,Q.jsx)(Vd,{projectName:e,refreshNonce:g}),r===`bing`&&(0,Q.jsx)(sf,{projectName:e,refreshNonce:g})]})]})}function HO(e){return e.total-e.citationNotMeasured}function UO({label:e,summary:t,displayValue:n,tooltip:r}){let{figure:i,sign:a}=Pr(t.value),o=t.progress===void 0?0:Math.min(Math.max(t.progress,0),100);return(0,Q.jsxs)(`div`,{className:`aeo-hero-row`,children:[(0,Q.jsxs)(`p`,{className:`aeo-hero-row-label`,children:[e,(r||t.tooltip)&&(0,Q.jsx)(X,{text:r||t.tooltip||``})]}),(0,Q.jsx)(`p`,{className:`aeo-hero-row-value ${oc[t.tone]}`,children:n??(0,Q.jsxs)(Q.Fragment,{children:[i,a?(0,Q.jsx)(`span`,{className:`text-faint`,children:a}):null]})}),(0,Q.jsx)(`div`,{className:`aeo-hero-row-bar`,"aria-hidden":`true`,children:(0,Q.jsx)(`div`,{className:`metric-card-bar-fill progress-fill-${t.tone}`,style:{width:`${o}%`}})})]})}var WO={emptyTitle:`No competitors set`,emptyDetail:`Mention and citation gaps need at least one tracked competitor.`,add:`Add competitors`};function GO({id:e,title:t,meta:n,defaultOpen:r=!1,children:i}){let a=(0,Z.useId)(),o=(0,Z.useId)();return(0,Q.jsxs)(`details`,{id:e,className:`overview-disclosure page-section-divider scroll-mt-24`,open:r||void 0,children:[(0,Q.jsxs)(`summary`,{className:`overview-disclosure-summary`,"aria-labelledby":a,"aria-describedby":n?o:void 0,children:[(0,Q.jsx)(`h2`,{id:a,className:`overview-disclosure-title`,children:t}),(0,Q.jsxs)(`span`,{className:`overview-disclosure-meta`,children:[n&&(0,Q.jsx)(`span`,{id:o,children:n}),(0,Q.jsx)(d,{className:`overview-disclosure-icon`,size:16,"aria-hidden":`true`})]})]}),(0,Q.jsx)(`div`,{className:`overview-disclosure-body`,children:i})]})}function KO({insights:e,suggestedQueries:t,onManageQueries:n,siteDomain:r}){let{openEvidence:i}=Tc(),a=n?t.rows:[];if(e.length===0&&a.length===0)return null;let o=e=>(0,Q.jsxs)(`div`,{className:`py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:e.title}),e.detail?(0,Q.jsx)(`p`,{className:`mt-1 max-w-3xl text-copy-14 text-secondary`,children:e.detail}):null]}),(0,Q.jsx)(J,{tone:e.tone,children:e.actionLabel})]}),e.affectedPhrases.length>0?(0,Q.jsxs)(`details`,{className:`mt-2`,children:[(0,Q.jsxs)(`summary`,{className:`w-fit cursor-pointer text-label-14-strong text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60`,children:[`Evidence · `,e.affectedPhrases.length,` affected `,e.affectedPhrases.length===1?`query`:`queries`]}),(0,Q.jsx)(`ul`,{className:`mt-2 divide-y divide-subtle border-y border-subtle`,children:e.affectedPhrases.map((t,n)=>(0,Q.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 py-2`,children:[(0,Q.jsx)(_l,{state:t.citationState,...r&&t.siteCitation!==!1?{label:Mr(r,t.citationState)}:{}}),(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 text-label-14 text-strong`,children:t.query}),t.provider?(0,Q.jsx)(Xs,{provider:t.provider}):null,!K()&&t.evidenceId?(0,Q.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:e=>{e.currentTarget.focus({preventScroll:!0}),i(t.evidenceId)},children:`View evidence`}):null]},t.evidenceId||`${e.id}-${n}`))})]}):null]},e.id),s=e=>(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-4 py-3`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-label-12-strong normal-case text-muted`,children:`Suggested query`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14-strong text-strong`,children:e.query}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:e.reason})]}),n?(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:n,children:`Review in Queries`}):null]},e.query),c=e.slice(0,1),l=a.slice(0,1),u=e.slice(1),d=a.slice(1),f=u.length+d.length;return(0,Q.jsxs)(`section`,{className:`visibility-disclosure-panel`,"aria-labelledby":`overview-signals-title`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`h2`,{id:`overview-signals-title`,children:`Latest signals`})}),(0,Q.jsxs)(`div`,{className:`divide-y divide-default border-y border-default`,children:[c.map(o),l.map(s)]}),f>0?(0,Q.jsxs)(`details`,{className:`mt-2`,children:[(0,Q.jsxs)(`summary`,{className:`w-fit cursor-pointer text-label-14-strong text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60`,children:[f,` more `,f===1?`signal`:`signals`]}),(0,Q.jsxs)(`div`,{className:`mt-2 divide-y divide-default border-y border-default`,children:[u.map(o),d.map(s)]})]}):null]})}function qO(e){let{projectName:t}=H({from:`/projects/$projectName`}),n=Mc()?.dashboard.projects.find(e=>e.project.name===t||e.project.id===t)?.project.name??null,r=W({...ja({client:Y}),enabled:!n}),i=n??r.data?.find(e=>e.name===t||e.id===t)?.name??null,a=Un(),o=Os(e.tab,a),[s,c]=(0,Z.useState)(null),l=i!==null&&s===i,u=(0,Z.useCallback)(()=>{i&&c(i)},[i]),{commandCenter:d,isLoading:f,overviewLoading:p,overviewError:m,isError:h,latestVisibilityRevision:g,competitorHistoryRevision:_,refetch:v}=yc(i,{overview:o===`overview`&&l}),y=!n&&r.isLoading||f;return!i&&!n&&r.isSuccess&&!f?(0,Q.jsx)(`div`,{className:`page-container`,children:(0,Q.jsxs)(Cs,{className:`surface-card empty-card`,children:[(0,Q.jsx)(`h1`,{children:`Project not found`}),(0,Q.jsxs)(`p`,{children:[`Could not find a project named "`,t,`".`]}),(0,Q.jsx)(q,{asChild:!0,children:(0,Q.jsx)(U,{to:`/`,children:`Return to overview`})})]})}):!d&&(h||r.isError)?(0,Q.jsxs)(`div`,{className:`page-container`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:`Could not load this project.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:()=>{Promise.all([r.refetch(),v()])},children:`Retry`})]}):!d||y?(0,Q.jsxs)(`div`,{className:`page-skeleton`,children:[(0,Q.jsxs)(`div`,{className:`page-skeleton-header`,children:[(0,Q.jsx)(`div`,{className:`skeleton-text h-6 w-48`}),(0,Q.jsx)(`div`,{className:`skeleton-text-sm w-32`})]}),(0,Q.jsx)(`div`,{className:`grid grid-cols-3 gap-4`,children:[1,2,3].map(e=>(0,Q.jsxs)(`div`,{className:`page-skeleton-card flex flex-col items-center`,children:[(0,Q.jsx)(`div`,{className:`skeleton-circle size-20`}),(0,Q.jsx)(`div`,{className:`skeleton-text w-16 mt-3`})]},e))}),(0,Q.jsxs)(`div`,{className:`page-skeleton-card`,children:[(0,Q.jsx)(`div`,{className:`skeleton-text w-28`}),(0,Q.jsx)(`div`,{className:`space-y-2 mt-2`,children:[1,2,3,4].map(e=>(0,Q.jsx)(`div`,{className:`skeleton-text-sm w-full`},e))})]})]}):(0,Q.jsx)($O,{model:d,refetch:v,latestVisibilityRevision:g,competitorHistoryRevision:_,overviewLoading:p,overviewError:m,overviewRequested:l,onRequestOverview:u,...e})}function JO(e,{journeys:t}){return{primary:[{key:`overview`,label:`AI Visibility`,href:e},{key:`search-console`,label:`Search engines`,href:`${e}/search-console`},{key:`seo-data`,label:`SEO`,href:`${e}/seo-data`},{key:`activity`,label:`Activity`,href:`${e}/activity`},{key:`agent-readiness`,label:`Agent Readiness`,href:`${e}/agent-readiness`},...t?[{key:`journeys`,label:`Journeys`,href:`${e}/journeys`}]:[],{key:`traffic`,label:`Server traffic`,href:`${e}/traffic`},{key:`queries`,label:`Queries`,href:`${e}/queries`}],overflow:[{key:`conversions`,label:`Conversions`,href:`${e}/conversions`},{key:`local`,label:`Local presence`,href:`${e}/local`},{key:`backlinks`,label:`Backlinks`,href:`${e}/backlinks`},{key:`history`,label:`Change history`,href:`${e}/history`}]}}function YO({items:e,overflowItems:t,settingsItem:n,activeTab:r}){let i=(0,Z.useRef)(null),a=(0,Z.useRef)(null),[o,s]=(0,Z.useState)(null),{rowItems:c,menuOverflowItems:l}=(0,Z.useMemo)(()=>{let n=t.find(e=>e.key===r);return{rowItems:n?[...e,n]:e,menuOverflowItems:t.filter(e=>e!==n)}},[e,t,r]);(0,Z.useLayoutEffect)(()=>{let e=i.current,t=a.current;if(!e||!t)return;let o=()=>{let i=e.getBoundingClientRect().width;if(!i)return;let a=Number.parseFloat(getComputedStyle(e).columnGap)||0,o=new Map([...t.querySelectorAll(`[data-project-tab]`)].map(e=>[e.dataset.projectTab,e.getBoundingClientRect().width])),u=e=>o.get(e)??0,d=e=>e.reduce((e,t)=>e+u(t),0)+Math.max(0,e.length-1)*a,f=[...c.map(e=>e.key),...l.length?[`more`]:[],...n?[n.key]:[]],p=c.map(e=>e.key),m=!1;if(d(f)>i){let e=c.find(e=>e.key===r),t=e?[e.key]:[];m=!!(n&&n.key!==r&&d([...t,`more`,n.key])>i);let a=[`more`,...n&&!m?[n.key]:[]];for(let n of c)if(n.key!==e?.key){if(d([...t,n.key,...a])>i)break;t.push(n.key)}p=c.filter(e=>t.includes(e.key)).map(e=>e.key)}s(e=>e?.settingsInMore===m&&e.visibleKeys.join()===p.join()?e:{visibleKeys:p,settingsInMore:m})};if(o(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,o),()=>window.removeEventListener(`resize`,o);let u=new ResizeObserver(o);return u.observe(e),u.observe(t),()=>u.disconnect()},[c,l,n,r]);let u=!!o?.settingsInMore&&n?.key!==r,f=o?c.filter(e=>e.key===r||o.visibleKeys.includes(e.key)):c,p=[...c.filter(e=>!f.includes(e)),...l,...u&&n?[n]:[]];return(0,Q.jsxs)(`nav`,{className:`project-subnav`,"aria-label":`Project sections`,ref:i,children:[(0,Q.jsx)(`div`,{className:`project-subnav-measure`,"aria-hidden":`true`,children:(0,Q.jsxs)(`div`,{className:`project-subnav-measure-row`,ref:a,children:[[...c,...n?[n]:[]].map(e=>(0,Q.jsx)(`span`,{className:`project-subnav-link`,"data-project-tab":e.key,children:e.label},e.key)),(0,Q.jsxs)(`span`,{className:`project-subnav-link project-subnav-more-trigger`,"data-project-tab":`more`,children:[`More`,(0,Q.jsx)(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]})]})}),f.map(e=>(0,Q.jsx)(U,{to:e.href,search:e=>({...e,onboarding:void 0}),activeOptions:{exact:!0},className:`project-subnav-link ${e.key===r?`project-subnav-link-active project-subnav-current`:``}`,"aria-current":e.key===r?`page`:void 0,children:(0,Q.jsx)(`span`,{className:`project-subnav-label`,children:e.label})},e.key)),(0,Q.jsxs)(`div`,{className:`project-subnav-trailing`,children:[(0,Q.jsx)(XO,{items:p}),n&&!u&&(0,Q.jsx)(U,{to:n.href,search:e=>({...e,onboarding:void 0}),className:`project-subnav-link ${r===`settings`?`project-subnav-link-active`:``}`,"aria-current":r===`settings`?`page`:void 0,children:n.label})]})]})}function XO({items:e}){let[t,n]=(0,Z.useState)(!1),r=(0,Z.useRef)(null),i=(0,Z.useRef)(null),a=(0,Z.useRef)(`first`),o=(0,Z.useId)(),s=e.map(e=>e.key).join();return(0,Z.useEffect)(()=>{n(!1)},[s]),(0,Z.useEffect)(()=>{if(!t)return;let e=r.current?.querySelectorAll(`[role="menuitem"]`);(a.current===`last`?e?.[e.length-1]:e?.[0])?.focus()},[t]),(0,Z.useEffect)(()=>{if(!t)return;let e=e=>{r.current&&!r.current.contains(e.target)&&n(!1)},a=e=>{e.key===`Escape`&&(n(!1),i.current?.focus())};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,a),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,a)}},[t]),e.length===0?null:(0,Q.jsxs)(`div`,{className:`project-subnav-more`,ref:r,children:[(0,Q.jsxs)(`button`,{type:`button`,ref:i,className:`project-subnav-link project-subnav-more-trigger`,"aria-haspopup":`menu`,"aria-expanded":t,"aria-controls":t?o:void 0,onClick:()=>{a.current=`first`,n(e=>!e)},onKeyDown:e=>{(e.key===`ArrowDown`||e.key===`ArrowUp`)&&(e.preventDefault(),a.current=e.key===`ArrowUp`?`last`:`first`,n(!0))},children:[`More`,(0,Q.jsx)(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]}),t?(0,Q.jsx)(`div`,{className:`project-subnav-menu`,role:`menu`,id:o,"aria-label":`More project sections`,onKeyDown:e=>{let t=[...e.currentTarget.querySelectorAll(`[role="menuitem"]`)],n=t.indexOf(document.activeElement),r=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n-1+t.length)%t.length:null;r!==null&&(e.preventDefault(),t[r]?.focus())},onBlur:e=>{r.current?.contains(e.relatedTarget)||n(!1)},children:e.map(e=>(0,Q.jsx)(U,{to:e.href,search:e=>({...e,onboarding:void 0}),role:`menuitem`,tabIndex:-1,className:`project-subnav-menu-item`,onClick:()=>n(!1),children:e.label},e.key))}):null]})}var ZO=20,QO=5;function $O({tab:e,model:t,refetch:n,latestVisibilityRevision:r,competitorHistoryRevision:i,overviewLoading:a,overviewError:o,overviewRequested:s,onRequestOverview:c}){let l=B(),u=z(),{account:f,canWrite:p,isAdmin:m}=si(),[h,g]=(0,Z.useState)(null),_=(0,Z.useRef)(null),y=Mc(),b=t.project.name,x=y?.dashboard.projects.some(e=>e.project.name===b)??!1,S=V({strict:!1}),C=ic(S),w=hl(C),T=(0,Z.useMemo)(()=>Ns(Un()),[]),E=(0,Z.useMemo)(()=>Gs(Un()),[]),D=(0,Z.useMemo)(()=>Os(e,Un()),[e]),O=D===`overview`&&!K(),k=we(),A=W({...ia({client:Y,path:{name:b}}),enabled:!K()&&!!b&&(D===`overview`||D===`portfolio`||D===`settings`||w),staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`}),j=y?y.dashboard.settings.providerStatuses.filter(e=>e.state!==`needs-config`).map(e=>lc(e.name)):void 0,M=A.data?.answerVisibilityProviderReady,N=j,P=t.project.providers.map(lc),F=N?.some(e=>P.length===0||P.includes(e))===!0,I=P.length===0||P.includes(`cdp:chatgpt`),ee=W({...Ma({client:Y}),enabled:O&&!k&&p&&M===void 0&&I&&!F,staleTime:6e4,retry:!1}),L=I?ee.isSuccess?typeof ee.data.browserVersion==`string`:!ee.isError&&void 0:!1,R=M??zc({projectProviders:P,configuredApiProviders:N,cdpConfigured:L}),H=(0,Z.useMemo)(()=>t.competitors.map(e=>e.domain),[t.competitors]),re=(0,Z.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,e.aliases??[]])),[t.competitors]),ae=(0,Z.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,e.autoAliases??[]])),[t.competitors]),oe=(0,Z.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,[...e.aliases??[],...e.autoAliases??[]]])),[t.competitors]),[se,ce]=(0,Z.useState)(!1),[le,ue]=(0,Z.useState)(!1),de=Nc(),fe=(0,Z.useCallback)((e,t)=>{l({to:`.`,search:t=>qs(t,e),replace:t?.replace===!0})},[l]),pe=S.queryWorkspace===`research`||D===`discovery`&&S.queryWorkspace===void 0?`research`:`tracked`,me=fl(pe,dl(f?.role,f?.role===`viewer`?vn():null)),he=W({...Io({client:Y,path:{name:b}}),enabled:!K()&&(D===`queries`||D===`discovery`)&&me===`tracked`}),ge=S.manageQueries===!0,_e=(0,Z.useCallback)(()=>{l({to:`.`,replace:!0,search:e=>({...e,siteHealthRunId:void 0})})},[l]),[ve,ye]=(0,Z.useState)(ge),[be,xe]=(0,Z.useState)(``),[Se,Ce]=(0,Z.useState)(!1),[Te,Ee]=(0,Z.useState)(null),[De,Oe]=(0,Z.useState)(`30d`),[G,ke]=(0,Z.useState)(void 0),[Ae,je]=(0,Z.useState)(``),[Me,Ne]=(0,Z.useState)(!1),[Pe,Fe]=(0,Z.useState)(null),[Ie,Le]=(0,Z.useState)(!1),Re=nc(S),[ze,Be]=(0,Z.useState)(void 0),[Ve,He]=(0,Z.useState)(void 0),Ue=(0,Z.useCallback)(e=>{Be(e.search),e.sort&&He(e.sort),l({to:`.`,search:t=>({...t,...rc(e)}),replace:!1})},[l]),[We,Ge]=(0,Z.useState)(!1),Ke=t?.project.displayName||t?.project.name||b,qe=sc(),Je=Zs(b,O&&!k&&h===b),Ye=W({...Vi({client:Y,path:{name:b}}),enabled:D===`portfolio`&&!!b,staleTime:0,refetchOnMount:`always`}),Xe=W({...Di({client:Y,path:{name:b}}),enabled:!K()&&!!b&&(rt()||D===`portfolio`||D===`overview`||D===`settings`||p&&w),staleTime:0,refetchOnMount:`always`}),Qe=Xe.data?.active??null,$e=Xe.data!==void 0,et=new Set(Qe&&Number(Qe.plan.schemaVersion)===2?Qe.plan.groups?.map(e=>e.stableKey)??[]:[]),nt={...Re.scope===`group`&&Re.groupKey&&$e&&!et.has(Re.groupKey)?{scope:`all`,queryClass:Re.queryClass}:Re,...ze?{search:ze}:{}},ot=Qe===null?null:Number(Qe.plan.schemaVersion),st=Qe?.revision??0,ct=$e?`${b}:${st}`:null,lt=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=lt.current;ct!==null&&(lt.current=ct),Es(e,ct)&&(Ue({scope:`all`,queryClass:`all`}),Ge(!1))},[ct,Ue]);let ut={client:Y,path:{name:b},query:{scope:nt.scope,...nt.groupKey?{groupKey:nt.groupKey}:{},queryClass:nt.queryClass,...nt.search?{search:nt.search}:{},...Ve?{sort:Ve}:{},limit:50}},dt=ne({...Oo(ut),enabled:!1,initialPageParam:ut,getNextPageParam:(e,t)=>{if(!e.properties.nextCursor)return;let n=t[0]?.measurement.displayedRunId;return{path:ut.path,query:{...ut.query,cursor:e.properties.nextCursor,...n?{runId:n}:{}}}},placeholderData:te,staleTime:0,refetchOnMount:`always`}),ft=dt.data?.pages[0]?.measurement.displayedRunId,mt=W({...ea({client:Y,path:{name:b},query:{revision:st,...ft?{runId:ft}:{}}}),enabled:D===`overview`&&!!b&&Qe!==null&&ot===1,staleTime:0,refetchOnMount:`always`}),ht=Xe.data!==void 0,gt=Ye.data!==void 0,_t=Xe.isPending&&!ht,vt=Xe.isError&&!ht,yt=Ye.isPending&&!gt,bt=Ye.isError&&!gt,xt=mt.data!==void 0,St=fO({activePlanSchemaVersion:A.data?.activeSchemaVersion??ot,hasDraft:A.data?.draft!==null&&A.data?.draft!==void 0}),Ct=St.surface===`simple-overview`,Tt=rt()&&Qe?.plan.schemaVersion===2?pO(Qe.plan):null,Et=A.data===void 0&&Xe.data===void 0&&(Xe.isLoading||A.isLoading);(0,Z.useEffect)(()=>{D===`overview`&&Ct&&!Et&&c()},[Et,Ct,c,D]);let Dt=gl({tab:D,surface:Et?`unresolved`:St.surface,embedded:K(),scoped:w,queryWorkspace:me,tracking:he.isError?{state:`error`}:he.data?{state:`ready`,mode:he.data.mode,scopeUnavailable:pl(he.data,C)}:{state:`pending`}}),Ot=Z_(b,C,{enabled:Dt.kind===`report-picker`}),kt=D===`overview`&&Ct&&!Et,At=yc(b,{evidence:kt}),jt=At.commandCenter?.visibilityEvidence??t.visibilityEvidence,Mt=(0,Z.useMemo)(()=>{let e=new Map(jt.map(e=>[tt(e.query),e.queryClass??null])),n=Sr(pt(t.project));return t=>{let r=e.get(tt(t));return r===void 0?n?.classify(t)??null:r}},[jt,t.project]),Nt=(0,Z.useMemo)(()=>[...new Set([...jt.map(e=>e.query),...t.movementComparison.addedQueries,...t.movementComparison.removedQueries])],[jt,t.movementComparison]),Pt=(0,Z.useMemo)(()=>{if(!Sr(pt(t.project)))return!1;let e=new Set(jt.map(e=>Mt(e.query)));return e.has(`branded`)&&e.has(`non-brand`)},[t.project,jt,Mt]),Ft=(0,Z.useMemo)(()=>t.visibilitySweeps.map(e=>e.createdAt),[t.visibilitySweeps]),It=ot===2&&C.measurementScope===`group`?C.measurementScopeKey:void 0,Lt=ot===2&&C.measurementScope===`project`,Rt=(0,Z.useMemo)(()=>{if(Qe?.plan.schemaVersion===2&&It)return Qe.plan.groups.find(e=>e.stableKey===It)},[Qe,It]),zt={client:Y,path:{name:b},query:{window:De,queryClass:ot===2&&C.queryClass!==`unknown`?C.queryClass:`non-brand`,...It?{groupKey:It}:{},...Lt?{scope:`all-markets`}:{}}},Bt=D===`overview`&&!C.marketKey&&!!b&&(Ct||$e)&&!Et&&(Ct||(C.measurementScope===`project`||ot===2&&C.measurementScope===`group`)&&C.queryClass!==`unknown`&&(ot===2||C.queryClass!==`branded`)),[Vt,Ht]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{Bt||Ht(null)},[Bt]),(0,Z.useEffect)(()=>{Ht(null)},[b]);let Ut=Vt===b,Wt=(0,Z.useRef)(null),[Gt,Kt]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{Gt&&Ut&&(Kt(!1),Wt.current?.querySelector(`:scope > summary`)?.focus())},[Gt,Ut]);let qt=(0,Z.useId)(),Jt=(0,Z.useId)(),Yt=Bt&&Ut,Xt=W({...Do(zt),enabled:Yt,staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`});cc(b,JSON.stringify([i,t.competitors.map(e=>`${e.domain}=${[...e.aliases??[],...e.autoAliases??[]].join(`|`)}`).sort(),t.project.canonicalDomain,t.project.ownedDomains,t.project.aliases,t.project.displayName,st,A.data?.draft?.etag??null]),Yt);let Zt=Xt.isError?Xt.data===void 0?`Could not load competitors over time. Your pinned competitors remain available.`:`Could not refresh competitors over time. Showing the last available data.`:void 0,$t=(0,Z.useMemo)(()=>t.competitors.map(e=>({domain:e.domain,label:e.domain,surfaceClass:`direct-competitor`,pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:e.citationCount,answeredResults:e.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[t.competitors]),en=(0,Z.useMemo)(()=>{if(Qe?.plan.schemaVersion!==2)return $t;let e=It?Rt?.competitors??[]:Qe.plan.groups.flatMap(e=>e.competitors),t=new Map;for(let n of e){let e=n.domain.trim().toLowerCase();e&&!t.has(e)&&t.set(e,{domain:n.domain,label:n.label,surfaceClass:`direct-competitor`,pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(let e of $t){let n=e.domain.trim().toLowerCase();n&&!t.has(n)&&t.set(n,e)}return[...t.values()]},[Qe,It,$t,Rt]),tn=ot===2?en:$t,nn=ie({...Bi({client:Y}),meta:{skipGlobalErrorToast:!0}}),rn=A.data===void 0?A.isError?`error`:`pending`:`success`,an=(0,Z.useMemo)(()=>{let e=dt.data?.pages;return e?!Yc(e):!1},[dt.data]),sn=(0,Z.useMemo)(()=>{let e=dt.data?.pages,t=e?.[0],n=e?.at(-1);if(t&&n&&!an)return{...t,properties:{...t.properties,items:e.flatMap(e=>e.properties.items),nextCursor:n.properties.nextCursor}}},[an,dt.data]),cn=(0,Z.useMemo)(()=>{if(Qe)return Qe.plan.schemaVersion===1?mt.data?CO(Qe,mt.data):void 0:sn?Gc({overview:sn,activePlan:Qe,sort:Ve,report:mt.data,reportState:sn.measurement.displayedRunId===void 0?`ready`:mt.isFetching&&mt.data===void 0?`loading`:mt.isError&&mt.data===void 0?`error`:mt.data?`ready`:`loading`}):void 0},[Qe,mt.data,mt.isError,mt.isFetching,sn]),ln=ot===2?an?`error`:dt.isPending?`loading`:dt.isError&&cn===void 0?`error`:`ready`:mt.isPending&&!xt?`loading`:mt.isError&&!xt?`error`:`ready`,un=(t?.recentRuns??[]).some(e=>e.kind===Qt[`answer-visibility`]&&(e.status===hr.running||e.status===hr.queued)),dn=Lc(b,O&&!k,`manual`).data,fn=Lc(b,O,`scheduled`).data,pn=dn&&fn&&JSON.stringify(dn)!==JSON.stringify(fn),mn=dn?.refused===!0,hn=dn&&!dn.refused?Object.keys(dn.providers):[],gn=t.queryCounts.total>0,_n=(0,Z.useMemo)(()=>(t?.project.locations??[]).map(e=>e.label),[t?.project.locations]),yn=(0,Z.useMemo)(()=>new Set(jt.map(e=>e.location??``)),[jt]),bn=yn.has(``),xn=(0,Z.useMemo)(()=>[...new Set(jt.map(e=>e.query))].sort((e,t)=>e.localeCompare(t)),[jt]),Cn=xn.length>0||t.queryCounts.total>0,wn=A.data?.requiresPublication===!0,En=Cn||Qe!==null,Dn=p&&!En&&(Xe.data===void 0&&Xe.isPending||kt&&At.evidenceLoading),On=p&&A.isError&&!A.isFetching,kn=p&&!On&&(Dn||R===void 0||A.isFetching),An=!kn&&!On&&En&&!wn&&R===!0,jn=p&&!kn&&!An,Mn=O&&!k&&jn&&!En,Nn=W({...ko({client:Y,path:{name:b},query:{limit:ZO}}),enabled:Mn&&!!b,retry:!1}),Pn=Nn.isSuccess&&Nn.data.scans.some(e=>e.status===`completed`||e.status===`partial`),Fn=Mn&&Nn.isSuccess&&!Pn,In=Mn&&Pn,Ln=W({...po({client:Y,path:{name:b}}),enabled:O&&!k&&!!b,retry:!1}).data?.find(e=>e.kind===Qt[`answer-visibility`]),Rn=Ln?.enabled&&Ln.nextRunAt?kc(Ln.nextRunAt,Ln.timezone):null,zn=Rn?`Next AI Visibility check ${Rn}`:null,Bn=(0,Z.useMemo)(()=>{let e=[...yn].filter(Boolean);return e.length>1?e:_n},[yn,_n]);(0,Z.useEffect)(()=>{!kt||G===void 0||G===``||!b?(Fe(null),Le(!1)):(Le(!0),or(b,G,20).then(e=>{Fe(e),Le(!1)}).catch(()=>{Fe(null),Le(!1)}))},[G,b,kt]);let Vn=(0,Z.useMemo)(()=>{if(!Pe)return null;let e=new Map;for(let t of Pe){for(let[n,r]of Object.entries(t.providerRuns??{}))e.set(`${t.query}::${n}`,r.map(e=>({runId:e.runId,citationState:e.citationState,createdAt:e.createdAt,answerMentioned:e.answerMentioned,visibilityState:e.visibilityState,visibilityTransition:e.visibilityTransition,mentionState:e.mentionState,mentionTransition:e.mentionTransition})));(!t.providerRuns||Object.keys(t.providerRuns).length===0)&&e.set(`${t.query}::`,t.runs.map(e=>({runId:e.runId,citationState:e.citationState,createdAt:e.createdAt,answerMentioned:e.answerMentioned,visibilityState:e.visibilityState,visibilityTransition:e.visibilityTransition,mentionState:e.mentionState,mentionTransition:e.mentionTransition})))}return e},[Pe]),Hn=(0,Z.useMemo)(()=>{let e=G===void 0?jt:jt.filter(e=>G===``?!e.location:e.location===G);return Vn?e.map(e=>{let t=Vn.get(`${e.query}::${e.provider}`)??Vn.get(`${e.query}::`);return t?{...e,runHistory:t}:e}):e},[jt,G,Vn]);async function Wn(){if(!(Je.isError||Je.isFetching||Je.data?.canStart!==!0||h!==b||!p||!O||k||qe.isPending||un||mn||!An))try{await qe.mutateAsync({projectName:b,projectLabel:Ke,sourceAction:`project-run`}),g(null)}catch{}}function Gn(){l(wn?{to:`/projects/$projectName/portfolio`,params:{projectName:b}}:{to:`/setup`,search:{project:b,track:`ai-visibility`}})}function Kn(){l({to:`/projects/$projectName/agent-readiness`,params:{projectName:b}})}async function qn(){ue(!0);try{await at(b),li({title:`Project deleted`,detail:`${Ke} was removed.`,tone:`positive`,dedupeKey:`project:delete:${b}`,dedupeMode:`drop`}),await l({to:`/`})}catch(e){console.error(`Failed to delete project:`,e)}finally{ue(!1)}}async function Jn(){let e=be.split(`
14
- `).map(e=>e.trim()).filter(Boolean);if(e.length!==0){Ce(!0);try{await on(b,e),xe(``)}finally{Ce(!1)}}}async function Yn(e){Ee(e);try{await Ze(b,[e])}catch(t){li({title:`Could not remove query`,detail:t instanceof Error?t.message:`Failed to remove "${e}"`,tone:`negative`,dedupeKey:`query:remove`,dedupeMode:`replace`})}finally{Ee(null)}}async function Xn(e){let t=e.trim();if(!t)return!1;try{return await rr(b,[t]),!0}catch(e){let n=e,r=Tn(e);if(r?.reason===`bulk-add-unacknowledged`){let e=typeof r.trackedBefore==`number`?r.trackedBefore:`?`,i=typeof r.trackedAfter==`number`?r.trackedAfter:`?`,a=typeof r.windowHours==`number`?r.windowHours:24;if(window.confirm(`This add would grow tracked competitors from ${e} to ${i} within ${a} hours. Continue?`))try{return await rr(b,[t],{acknowledgeBulkAdd:!0}),!0}catch(e){n=e}}return li({title:`Could not add competitor`,detail:n instanceof Error?n.message:`Failed to add ${t}`,tone:`negative`,dedupeKey:`competitor:add`,dedupeMode:`replace`}),!1}}async function Zn(e){let n=t.competitors.find(t=>t.domain===e);if(!n)return li({title:`Could not remove competitor`,detail:`Could not find ${e} in the tracked competitor list`,tone:`negative`,dedupeKey:`competitor:remove`,dedupeMode:`replace`}),!1;try{return await wt(b,n.id),!0}catch(e){return li({title:`Could not remove competitor`,detail:e instanceof Error?e.message:`Failed to remove ${n.domain}`,tone:`negative`,dedupeKey:`competitor:remove`,dedupeMode:`replace`}),!1}}async function Qn(e){let t=e.trim();if(!t||!It||ot!==2||!p||K()||nn.isPending)return!1;try{let e=await nn.mutateAsync({client:Y,path:{name:b},headers:{"Idempotency-Key":zO()},body:{expectedActiveRevision:st,groupKey:It,domain:t}});return Promise.allSettled([A.refetch()]),li({title:e.draftCreated?`Competitor added to a market draft`:`Market competitor updated`,detail:`Publish the Advanced Measurement draft before ${t} is used in future market runs.`,tone:`positive`,dedupeKey:`competitor:market-pin:${It}:${t}`,dedupeMode:`replace`}),!0}catch(e){return li({title:`Could not add market competitor`,detail:e instanceof Error?e.message:`Failed to add ${t} to the market draft.`,tone:`negative`,dedupeKey:`competitor:market-pin:error`,dedupeMode:`replace`}),!1}}async function $n(e,t){let n=await Sn(e,t);return u.setQueryData(la({client:Y,path:{name:e}}),n),BO(u,n),n}let J=`/projects/${encodeURIComponent(t.project.name)}`,er=JO(J,{journeys:f?.role!==_r.viewer}),tr=[...er.primary.filter(e=>Sc(e.key,T)),...E===void 0?[]:[{key:`client-queries`,label:`Queries`,href:`${J}/client-queries`}]],nr=er.overflow.filter(e=>Sc(e.key,T)),ir=p||K()||rt(),ar=ir&&Sc(`settings`,T)?{key:`settings`,label:`Settings`,href:`${J}/settings`}:null;function sr(e){let n=Ct?e:(0,Q.jsx)(ev,{projectName:b,selection:C,showUnmeasuredFallback:!Qe&&!gn&&C.measurementScope===`project`&&C.queryClass===`all`&&!C.provider&&!C.model&&!C.location&&!C.from&&!C.to&&!C.revision&&!C.measurementRunId&&!C.queryKey&&!C.marketKey,onSelectionChange:fe,onManageQueries:K()?void 0:()=>{l({to:`/projects/$projectName/queries`,params:{projectName:b},search:e=>({...e,queryWorkspace:`tracked`,trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:K()?void 0:({id:e,label:t})=>(0,Q.jsx)(U,{to:`/projects/$projectName/properties/$targetKey`,params:{projectName:b,targetKey:e},search:Bs,"aria-label":`Property details for ${t}`,className:`inline-flex min-h-11 items-center text-label-14 text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:`Property details`}),trackingChangedAt:K()||k?void 0:Qe?.createdAt,nextSweepDate:K()||k||un?void 0:Rn??void 0,fallback:e});if(K())return n;let r=ec(C,Ct?`simple`:`advanced`,typeof S.sentimentEvaluationDefinitionId==`string`?S.sentimentEvaluationDefinitionId:void 0);return Ct&&(r.location=G===``?`none`:G,r=ks(r,Hn,Ae)),(0,Q.jsx)(Hs,{hasSourceEvidence:!Ct||!!(r.runId||r.runIds?.length),evidenceReady:!Ct||!(At.isLoading||At.evidenceLoading||At.evidenceError),waitForResolvedRun:!Ct,projectName:b,runOptions:t.visibilitySweeps.slice(0,QO).map(e=>({id:e.id,label:Jr(e.finishedAt??e.createdAt)})),selection:r,children:n})}function cr(){switch(Dt.kind){case`report-picker`:{if(Ot.error)return it(Tn(Ot.error))?(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:ul.savedScopeUnavailable}):null;let e=Ot.data;if(!e)return(0,Q.jsx)(`div`,{className:`skeleton-text h-11 w-56`,role:`status`,"aria-label":`Loading measurement scope`});if(e.selection.availability.state!==`available`||e.scopeOptions.length<=1)return null;let t=ml(e.scopeOptions,C)??e.selection.scope;return(0,Q.jsx)(qc,{labelVisibility:`sr-only`,options:e.scopeOptions,selected:t,marketKey:C.marketKey,onSelect:(e,t)=>fe({measurementScope:e.kind,measurementScopeKey:e.kind===`project`?void 0:e.id,measurementMarketKey:t})})}case`tracking-picker`:{let e=he.data?.scopeOptions??[],t=ml(e,C);return t?(0,Q.jsx)(qc,{labelVisibility:`sr-only`,options:e,selected:t,onSelect:e=>fe({measurementScope:e.kind,measurementScopeKey:e.kind===`project`?void 0:e.id})}):null}case`scope-unavailable`:return(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:ul.savedScopeUnavailable});case`project-wide`:return(0,Q.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:ul.projectWide}),(0,Q.jsx)(X,{text:ul.projectWideHelp})]});case`none`:return null}}let lr=D===`overview`&&!Ct&&(C.from||C.to)?`${C.from?.slice(0,10)??`First measurement`} to ${C.to?.slice(0,10)??`Latest measurement`}`:null,ur=cr(),dr=Bt?(0,Q.jsx)(Jl,{window:De,landscape:Xt.data,pinnedFallback:tn,competitorAliases:re,competitorAutoAliases:ae,canWrite:p,isEmbed:K(),onWindowChange:Oe,onPin:It&&p&&!K()?Qn:!Lt&&p&&!K()?Xn:void 0,onUnpin:It||Lt||!p||K()?void 0:Zn,onAddCompetitor:It&&p&&!K()?Qn:!Lt&&p&&!K()?Xn:void 0,error:Zt,onRetry:Yt?()=>{Xt.refetch()}:void 0,isLoading:Yt&&Xt.isPending&&Xt.data===void 0,scopeLabel:It?`${Rt?.label??It} group`:Lt?`All markets`:`Project-wide`,advancedPortfolio:!Ct}):null,fr=K()?null:(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(fs,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ye(!ve),children:ve?`Done`:`Manage queries`})}),pr=!K()&&ve?(0,Q.jsxs)(`div`,{className:`mb-3 material-base p-3`,children:[xn.length>0?(0,Q.jsx)(`ul`,{className:`mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto`,children:xn.map(e=>(0,Q.jsxs)(`li`,{className:`flex items-center justify-between gap-3 px-3 py-2`,children:[(0,Q.jsx)(`span`,{className:`min-w-0 truncate text-label-14 text-strong`,title:e,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`shrink-0 rounded px-1.5 py-0.5 text-button-14 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 ${e}`,title:`Stop tracking "${e}"`,disabled:Te!==null,onClick:()=>{Yn(e)},children:Te===e?`Removing…`:`Remove`})]},e))}):(0,Q.jsx)(`p`,{className:`mb-3 text-copy-13 text-muted`,children:`No queries tracked yet. Add some below.`}),(0,Q.jsx)(`textarea`,{className:`w-full resize-none rounded border border-strong bg-transparent px-2 py-1.5 text-copy-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,rows:3,placeholder:`Enter queries to add, one per line`,value:be,onChange:e=>xe(e.target.value)}),(0,Q.jsxs)(`div`,{className:`mt-2 flex items-center justify-between`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[be.split(`
15
- `).filter(e=>e.trim()).length,` to add`]}),(0,Q.jsx)(fs,{type:`button`,size:`sm`,disabled:!be.trim()||Se,onClick:ci(Jn),children:Se?`Adding...`:`Add queries`})]})]}):null;return(0,Q.jsxs)(`div`,{className:`page-container`,children:[K()?(0,Q.jsxs)(`div`,{className:`page-header`,children:[(0,Q.jsxs)(`div`,{className:`page-header-left`,children:[(0,Q.jsx)(`h1`,{className:`page-title`,children:t.project.displayName||t.project.name}),(0,Q.jsxs)(`p`,{className:`page-subtitle`,children:[t.project.canonicalDomain,` · `,t.contextLabel]})]}),(0,Q.jsx)(`div`,{className:k?`page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end`:`page-header-right`,children:lr===null?null:(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:lr})})]}):(0,Q.jsxs)(`div`,{className:`project-context-row`,children:[(0,Q.jsx)(`h1`,{className:`project-context-title md:sr-only`,children:t.project.displayName||t.project.name}),ur===null?null:(0,Q.jsx)(`div`,{className:`project-context-scope`,children:ur}),t.project.canonicalDomain?(0,Q.jsx)(`span`,{className:`project-context-domain`,children:t.project.canonicalDomain}):null,Tt===null?null:(0,Q.jsxs)(`span`,{className:`project-mode-tag`,children:[(0,Q.jsx)(`span`,{className:`project-mode-tag-label`,children:`Advanced`}),(0,Q.jsx)(`span`,{className:`project-mode-tag-detail`,children:Tt})]}),Fn||In?(0,Q.jsx)(`div`,{className:`project-context-actions`,"data-project-actions":!0,children:(0,Q.jsx)(fs,{type:`button`,onClick:Kn,children:Fn?`Check Agent Readiness`:`View Agent Readiness score`})}):null]}),(0,Q.jsx)(YO,{items:tr,overflowItems:nr,settingsItem:K()?ar:null,activeTab:D}),D===`portfolio`&&!K()?(0,Q.jsx)(PD,{projectName:b,projectDomain:t.project.canonicalDomain,canEdit:p,queries:Ye.data??[],isQueryLoading:yt,isQueryError:bt,onRetryQueries:()=>{Ye.refetch()},publishedPlan:Qe,sweepActive:un,executionProviders:t.project.providers,executionProviderModels:t.project.providerModels,onCreateQueries:async e=>(await de.mutateAsync({projectName:b,queries:[...e]}),(await Ye.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{l({to:`/projects/$projectName`,params:{projectName:b},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([A.refetch(),Xe.refetch()]).finally(()=>{l({to:`/projects/$projectName`,params:{projectName:b}})})}},b):D===`overview`?(0,Q.jsxs)(Q.Fragment,{children:[O?(0,Q.jsx)(`div`,{role:`group`,"aria-label":`AI Visibility checks`,className:`visibility-checks`,children:k?(0,Q.jsx)(Vs,{projectName:b,running:un}):(0,Q.jsxs)(Q.Fragment,{children:[zn?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:zn}):null,(0,Q.jsx)(fs,{type:`button`,variant:`outline`,disabled:qe.isPending||un||kn||mn&&!On&&!jn,onClick:On?()=>{A.refetch()}:jn?Gn:e=>{_.current=e.currentTarget,g(b)},children:qe.isPending?`Starting…`:un?`AI Visibility check running…`:kn?`Checking AI engines…`:On?`Retry engine check`:jn?wn?`Review and publish plan`:`Set up AI Visibility`:mn?`AI Visibility checks on hold`:`Run AI Visibility check`}),(0,Q.jsx)(IO,{open:h===b,projectLabel:Ke,onOpenChange:e=>g(e?b:null),onConfirm:ci(Wn),onClosed:()=>_.current?.focus(),disabled:qe.isPending||un||mn||!An,leftOut:hn,preview:Je.data,previewPending:Je.isFetching,previewFailed:Je.isError,onRetryPreview:()=>{Je.refetch()}})]})}):null,O?(0,Q.jsxs)(Q.Fragment,{children:[fn?(0,Q.jsx)(Ys,{admission:fn,canFix:p&&m,selection:pn||!dn?`scheduled`:void 0}):null,dn&&(pn||!fn)?(0,Q.jsx)(Ys,{admission:dn,canFix:p&&m,selection:`manual`}):null]}):null,Et||Ct&&!x&&(!s||a)?(0,Q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:`Loading project overview`}),(0,Q.jsx)(`div`,{className:`h-32 animate-pulse rounded-md bg-surface-subtle`,"aria-hidden":`true`})]}):Ct&&o?(0,Q.jsxs)(`div`,{role:`alert`,className:`page-section-divider`,children:[(0,Q.jsx)(`p`,{children:`Could not load AI visibility.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:()=>{n()},children:`Retry`})]}):(0,Q.jsxs)(Q.Fragment,{children:[vt?(0,Q.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-label-14 text-negative`,children:[(0,Q.jsx)(`span`,{children:`Could not check the advanced measurement setup. Existing project-wide results remain available.`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{Xe.refetch()},children:`Retry setup check`})]}):null,sr((0,Q.jsx)(mO,{mode:St,canEdit:p&&!K()&&!_t&&!vt,simpleOverview:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`section`,{className:`mb-6`,children:(0,Q.jsx)(zv,{projectName:t.project.name,competitorDomains:H,competitorAliases:oe,analyticsRevision:r,queryTexts:Nt,classifyQuery:Mt,sweepTimes:Ft,queryClassSplit:Pt})}),gn&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`section`,{className:`mb-6`,children:(0,Q.jsxs)(`details`,{className:`av-history`,open:H.length>0,children:[(0,Q.jsxs)(`summary`,{className:`av-card-head`,"aria-labelledby":qt,"aria-describedby":Jt,children:[(0,Q.jsx)(`h2`,{id:qt,className:`av-card-title`,children:H.length>0?`Where competitors are winning`:`Compare competitors`}),(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{id:Jt,className:`av-card-meta`,children:`Latest check`}),(0,Q.jsx)(d,{className:`overview-disclosure-icon`,size:16,"aria-hidden":`true`})]})]}),(0,Q.jsxs)(`div`,{className:`competitive-summary`,children:[(0,Q.jsx)(Tl,{summary:t.mentionShareSummary,projectLabel:t.project.displayName||t.project.name,competitorDomains:H},t.project.name),H.length>0?(0,Q.jsxs)(`div`,{className:`competitive-gaps`,children:[(0,Q.jsx)(`p`,{className:`competitive-gaps-scope`,children:`All queries`}),(0,Q.jsxs)(`div`,{className:`aeo-hero-rows`,children:[(0,Q.jsx)(UO,{label:`Mention gaps`,summary:t.mentionGaps,displayValue:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`text-primary`,children:t.mentionGaps.value}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[` / `,t.queryCounts.total]}),(0,Q.jsx)(`span`,{className:`sr-only`,children:` queries, all queries`})]}),tooltip:`Across all queries, branded and non-brand: a competitor was mentioned in an answer and your brand was not mentioned by any engine. The mention-share query type does not filter these counts.`}),(0,Q.jsx)(UO,{label:`Citation gaps`,summary:t.gapQueries,displayValue:HO(t.queryCounts)===0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`whitespace-nowrap text-label-13 text-secondary`,children:Ar.label}),(0,Q.jsx)(`span`,{className:`sr-only`,children:`, all queries`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`text-primary`,children:t.gapQueries.value}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[` / `,HO(t.queryCounts)]}),(0,Q.jsx)(`span`,{className:`sr-only`,children:` queries, all queries`})]}),tooltip:`Across all queries, branded and non-brand: a competitor was cited as a source and your domain was not cited by any engine. The mention-share query type does not filter these counts.`})]})]}):(0,Q.jsxs)(`div`,{className:`competitive-gaps`,children:[(0,Q.jsx)(`p`,{className:`text-label-14-strong text-strong`,children:WO.emptyTitle}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:WO.emptyDetail}),Bt&&p&&!K()?(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>{Ht(b),Kt(!0)},children:WO.add}):null]})]})]})}),(0,Q.jsx)(`div`,{className:`mb-6`,children:(0,Q.jsx)(o_,{projectName:t.project.name,revision:r})})]}),(0,Q.jsxs)(GO,{id:`evidence-section`,title:`Query evidence`,meta:`${t.queryCounts.total} measured ${t.queryCounts.total===1?`query`:`queries`}`,defaultOpen:!0,children:[t.project.locations.length>0&&(0,Q.jsxs)(`div`,{className:`filter-row mb-3`,role:`toolbar`,"aria-label":`Location filters`,children:[(0,Q.jsx)(`button`,{className:`filter-chip ${G===void 0?`filter-chip-active`:``}`,type:`button`,"aria-pressed":G===void 0,onClick:()=>{ke(void 0)},children:`All locations`}),t.project.locations.map(e=>(0,Q.jsx)(`button`,{className:`filter-chip ${G===e.label?`filter-chip-active`:``}`,type:`button`,"aria-pressed":G===e.label,onClick:()=>{ke(e.label),Ne(!1)},children:e.label},e.label)),bn&&(0,Q.jsx)(`button`,{className:`filter-chip ${G===``?`filter-chip-active`:``}`,type:`button`,"aria-pressed":G===``,onClick:()=>{ke(``),Ne(!1)},children:`No location`}),Bn.length>1&&G===void 0&&(0,Q.jsx)(`button`,{className:`filter-chip filter-chip-compare ${Me?`filter-chip-active`:``}`,type:`button`,"aria-pressed":Me,onClick:()=>Ne(e=>!e),title:`Side-by-side location comparison`,children:`Compare`})]}),At.evidenceLoading||At.evidenceError?(0,Q.jsxs)(Q.Fragment,{children:[fr&&(0,Q.jsx)(yu,{actions:fr}),pr,At.evidenceLoading?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading query evidence…`}):(0,Q.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-secondary`,children:[(0,Q.jsx)(`p`,{children:`Could not load query evidence.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:()=>{At.refetch()},children:`Retry`})]})]}):(0,Q.jsx)(bu,{evidence:Hn,compareLocations:Me,providerSelection:Ae,onProviderSelectionChange:je,addedQueries:t.movementComparison.addedQueries,actions:fr,actionPanel:pr})]}),!K()&&(0,Q.jsx)(`div`,{className:`page-section-divider`,children:(0,Q.jsx)(c_,{runs:t.recentRuns,projectName:t.project.name,collapsed:!0})})]}),report:cn,reportState:ln,onOpenSetup:K()?void 0:()=>{l({to:`/projects/$projectName/portfolio`,params:{projectName:b}})},onRetryReport:()=>{ot===2?Promise.all([dt.refetch(),mt.refetch()]):mt.refetch()},onViewChange:e=>{Ue({scope:e.scope,...e.groupKey?{groupKey:e.groupKey}:{},queryClass:e.queryClass,...e.search?.trim()?{search:e.search.trim()}:{}})},onLoadMore:e=>{e===sn?.properties.nextCursor&&dt.fetchNextPage()},onPropertyExpand:()=>{We&&mt.isError&&mt.refetch(),Ge(!0)},onRetryEvidence:()=>{mt.refetch()},isViewLoading:dt.isPlaceholderData,isLoadingMore:dt.isFetchingNextPage,isLoadMoreError:dt.isFetchNextPageError,viewSearch:nt.search??``},`${b}:${st}`)),!Ct&&C.measurementScope===`project`?(0,Q.jsxs)(`details`,{className:`visibility-disclosure`,onToggle:e=>{e.currentTarget.open&&c()},children:[(0,Q.jsx)(`summary`,{className:`visibility-disclosure-summary`,children:(0,Q.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Project signals`})}),!s||a?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading project signals…`}):o?(0,Q.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-secondary`,children:[(0,Q.jsx)(`p`,{children:`Could not load project signals.`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:()=>{n()},children:`Retry`})]}):(0,Q.jsx)(KO,{insights:t.insights,suggestedQueries:t.suggestedQueries,siteDomain:t.project.canonicalDomain||void 0,onManageQueries:K()?void 0:()=>{l({to:`/projects/$projectName/queries`,params:{projectName:b},search:e=>({...e,queryWorkspace:`tracked`,trackingQueryId:void 0})})}})]},b):null,dr===null?null:(0,Q.jsxs)(`details`,{ref:Wt,className:`visibility-disclosure${Ct?` page-section-divider`:``}`,open:Ut,onToggle:e=>Ht(e.currentTarget.open?b:null),children:[(0,Q.jsx)(`summary`,{className:`visibility-disclosure-summary`,children:(0,Q.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Competitor history`})}),(0,Q.jsx)(`div`,{className:`visibility-disclosure-panel`,children:dr})]})]})]}):D===`settings`?ir?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(wO,{project:{...t.project,displayName:t.project.displayName??t.project.name,defaultLocation:t.project.defaultLocation??null},onUpdateProject:async(e,t)=>{await $n(e,t)}}),(0,Q.jsx)(Pc,{project:t.project,onSave:async e=>{await $n(t.project.name,e)}}),(0,Q.jsx)(uc,{project:t.project,onSave:async e=>{await $n(t.project.name,e)}},t.project.id),p&&!K()?(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-20 text-heading`,children:`Advanced measurement`}),(0,Q.jsx)(`p`,{className:`supporting-copy mt-1 mb-3`,children:`Measure individual properties, locations, or site sections with separate query sets.`}),rn===`pending`?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading setup…`}):rn===`error`?(0,Q.jsxs)(`div`,{role:`alert`,className:`flex flex-wrap items-center gap-3 text-label-14 text-negative`,children:[(0,Q.jsx)(`span`,{children:`Could not load advanced measurement setup.`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{A.refetch()},children:`Retry`})]}):(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:()=>{l({to:`/projects/$projectName/portfolio`,params:{projectName:b}})},children:dO(St.setupAction)})]}):null,(0,Q.jsx)(kO,{projectName:t.project.name}),(0,Q.jsx)(PO,{projectName:t.project.name}),p&&!K()?(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-20 text-negative-400`,children:`Delete project`}),(0,Q.jsx)(`p`,{className:`supporting-copy mt-1 mb-3`,children:`Permanently deletes this project and all its queries, competitors, runs, and snapshots.`}),se?(0,Q.jsxs)(Cs,{className:`surface-card p-6 bg-negative-soft`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-negative-400 mb-2`,children:`Delete project?`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary mb-4`,children:[`This will permanently delete `,(0,Q.jsx)(`strong`,{className:`text-strong`,children:t.project.displayName||t.project.name}),` and all its queries, competitors, runs, and snapshots. This cannot be undone.`]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(q,{type:`button`,variant:`destructive`,disabled:le,onClick:ci(qn),children:le?`Deleting...`:`Yes, delete project`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,disabled:le,onClick:()=>ce(!1),children:`Cancel`})]})]}):(0,Q.jsxs)(fs,{type:`button`,variant:`outline`,onClick:()=>ce(!0),children:[(0,Q.jsx)(v,{className:`h-4 w-4 text-secondary`}),`Delete project`]})]}):null]}):(0,Q.jsxs)(Cs,{className:`surface-card empty-card`,children:[(0,Q.jsx)(`h2`,{children:`Project settings unavailable`}),(0,Q.jsx)(`p`,{children:`Your account has view-only access to this project.`}),(0,Q.jsx)(q,{asChild:!0,children:(0,Q.jsx)(U,{to:`/projects/$projectName`,params:{projectName:b},children:`Return to overview`})})]}):D===`client-queries`&&E!==void 0?(0,Q.jsx)(sb,{projectName:b,limit:E}):D===`queries`||D===`discovery`?(0,Q.jsx)(oy,{projectName:b,queryWorkspace:pe,onQueryWorkspaceChange:e=>fe({queryWorkspace:e,trackingQueryId:void 0}),researchMode:S.researchMode===`test`?`test`:`find`,onResearchModeChange:e=>fe({researchMode:e}),selection:C,onSelectionChange:fe,trackingQueryId:typeof S.trackingQueryId==`string`?S.trackingQueryId:void 0,onTrackingQueryIdChange:e=>fe({trackingQueryId:e}),publishGuard:{sweepActive:un}}):D===`agent-readiness`?(0,Q.jsx)($w,{projectName:t.project.name,projectId:t.project.id,initialRunId:S.siteHealthRunId,onReleaseInitialRun:_e}):D===`conversions`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(cE,{projectName:t.project.name},`${t.project.id}:performance`),(0,Q.jsx)(UT,{projectId:t.project.id,projectName:t.project.name},t.project.id)]}):D===`history`?(0,Q.jsx)(eT,{projectName:t.project.name}):D===`activity`?(0,Q.jsx)(vp,{projectName:t.project.name}):D===`traffic`?(0,Q.jsx)(ol,{view:`project`,projectName:b,initialCloudRunTarget:S.connectCloudRun,sourceId:typeof S.trafficSource==`string`?S.trafficSource:void 0,onSelectSource:e=>fe({trafficSource:e,connectCloudRun:void 0})},JSON.stringify([t.project.id,S.connectCloudRun])):D===`backlinks`?(0,Q.jsx)(Nm,{projectName:t.project.name}):D===`seo-data`?(0,Q.jsx)(hh,{projectName:t.project.name},t.project.id):D===`journeys`?(0,Q.jsx)(Lg,{projectName:t.project.name},t.project.id):D===`local`?(0,Q.jsx)(Qp,{projectName:t.project.name,projectId:t.project.id}):D===`search-console`?(0,Q.jsx)(VO,{projectName:t.project.name}):null]})}export{WO as COMPETITOR_COMPARISON_COPY,qO as ProjectPage,YO as ProjectSubnav,IO as ProjectSweepConfirmation,rS as n,BO as patchProjectDashboardCache,JO as projectSectionTabs,gb as r,FO as t};